PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/symfony/http-kernel/Profiler/RedisProfilerStorage.php

https://gitlab.com/Pasantias/pasantiasASLG
PHP | 394 lines | 223 code | 74 blank | 97 comment | 40 complexity | 8a22916242e01cfc5de62456bbe7d05d MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpKernel\Profiler;
  11. /**
  12. * RedisProfilerStorage stores profiling information in Redis.
  13. *
  14. * @author Andrej Hudec <pulzarraider@gmail.com>
  15. * @author Stephane PY <py.stephane1@gmail.com>
  16. */
  17. class RedisProfilerStorage implements ProfilerStorageInterface
  18. {
  19. const TOKEN_PREFIX = 'sf_profiler_';
  20. const REDIS_OPT_SERIALIZER = 1;
  21. const REDIS_OPT_PREFIX = 2;
  22. const REDIS_SERIALIZER_NONE = 0;
  23. const REDIS_SERIALIZER_PHP = 1;
  24. protected $dsn;
  25. protected $lifetime;
  26. /**
  27. * @var \Redis
  28. */
  29. private $redis;
  30. /**
  31. * Constructor.
  32. *
  33. * @param string $dsn A data source name
  34. * @param string $username Not used
  35. * @param string $password Not used
  36. * @param int $lifetime The lifetime to use for the purge
  37. */
  38. public function __construct($dsn, $username = '', $password = '', $lifetime = 86400)
  39. {
  40. $this->dsn = $dsn;
  41. $this->lifetime = (int) $lifetime;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function find($ip, $url, $limit, $method, $start = null, $end = null)
  47. {
  48. $indexName = $this->getIndexName();
  49. if (!$indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE)) {
  50. return array();
  51. }
  52. $profileList = array_reverse(explode("\n", $indexContent));
  53. $result = array();
  54. foreach ($profileList as $item) {
  55. if ($limit === 0) {
  56. break;
  57. }
  58. if ($item == '') {
  59. continue;
  60. }
  61. $values = explode("\t", $item, 7);
  62. list($itemToken, $itemIp, $itemMethod, $itemUrl, $itemTime, $itemParent) = $values;
  63. $statusCode = isset($values[6]) ? $values[6] : null;
  64. $itemTime = (int) $itemTime;
  65. if ($ip && false === strpos($itemIp, $ip) || $url && false === strpos($itemUrl, $url) || $method && false === strpos($itemMethod, $method)) {
  66. continue;
  67. }
  68. if (!empty($start) && $itemTime < $start) {
  69. continue;
  70. }
  71. if (!empty($end) && $itemTime > $end) {
  72. continue;
  73. }
  74. $result[] = array(
  75. 'token' => $itemToken,
  76. 'ip' => $itemIp,
  77. 'method' => $itemMethod,
  78. 'url' => $itemUrl,
  79. 'time' => $itemTime,
  80. 'parent' => $itemParent,
  81. 'status_code' => $statusCode,
  82. );
  83. --$limit;
  84. }
  85. return $result;
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function purge()
  91. {
  92. // delete only items from index
  93. $indexName = $this->getIndexName();
  94. $indexContent = $this->getValue($indexName, self::REDIS_SERIALIZER_NONE);
  95. if (!$indexContent) {
  96. return false;
  97. }
  98. $profileList = explode("\n", $indexContent);
  99. $result = array();
  100. foreach ($profileList as $item) {
  101. if ($item == '') {
  102. continue;
  103. }
  104. if (false !== $pos = strpos($item, "\t")) {
  105. $result[] = $this->getItemName(substr($item, 0, $pos));
  106. }
  107. }
  108. $result[] = $indexName;
  109. return $this->delete($result);
  110. }
  111. /**
  112. * {@inheritdoc}
  113. */
  114. public function read($token)
  115. {
  116. if (empty($token)) {
  117. return false;
  118. }
  119. $profile = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP);
  120. if (false !== $profile) {
  121. $profile = $this->createProfileFromData($token, $profile);
  122. }
  123. return $profile;
  124. }
  125. /**
  126. * {@inheritdoc}
  127. */
  128. public function write(Profile $profile)
  129. {
  130. $data = array(
  131. 'token' => $profile->getToken(),
  132. 'parent' => $profile->getParentToken(),
  133. 'children' => array_map(function ($p) { return $p->getToken(); }, $profile->getChildren()),
  134. 'data' => $profile->getCollectors(),
  135. 'ip' => $profile->getIp(),
  136. 'method' => $profile->getMethod(),
  137. 'url' => $profile->getUrl(),
  138. 'time' => $profile->getTime(),
  139. );
  140. $profileIndexed = false !== $this->getValue($this->getItemName($profile->getToken()));
  141. if ($this->setValue($this->getItemName($profile->getToken()), $data, $this->lifetime, self::REDIS_SERIALIZER_PHP)) {
  142. if (!$profileIndexed) {
  143. // Add to index
  144. $indexName = $this->getIndexName();
  145. $indexRow = implode("\t", array(
  146. $profile->getToken(),
  147. $profile->getIp(),
  148. $profile->getMethod(),
  149. $profile->getUrl(),
  150. $profile->getTime(),
  151. $profile->getParentToken(),
  152. $profile->getStatusCode(),
  153. ))."\n";
  154. return $this->appendValue($indexName, $indexRow, $this->lifetime);
  155. }
  156. return true;
  157. }
  158. return false;
  159. }
  160. /**
  161. * Internal convenience method that returns the instance of Redis.
  162. *
  163. * @return \Redis
  164. *
  165. * @throws \RuntimeException
  166. */
  167. protected function getRedis()
  168. {
  169. if (null === $this->redis) {
  170. $data = parse_url($this->dsn);
  171. if (false === $data || !isset($data['scheme']) || $data['scheme'] !== 'redis' || !isset($data['host']) || !isset($data['port'])) {
  172. throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use Redis with an invalid dsn "%s". The minimal expected format is "redis://[host]:port".', $this->dsn));
  173. }
  174. if (!extension_loaded('redis')) {
  175. throw new \RuntimeException('RedisProfilerStorage requires that the redis extension is loaded.');
  176. }
  177. $redis = new \Redis();
  178. $redis->connect($data['host'], $data['port']);
  179. if (isset($data['path'])) {
  180. $redis->select(substr($data['path'], 1));
  181. }
  182. if (isset($data['pass'])) {
  183. $redis->auth($data['pass']);
  184. }
  185. $redis->setOption(self::REDIS_OPT_PREFIX, self::TOKEN_PREFIX);
  186. $this->redis = $redis;
  187. }
  188. return $this->redis;
  189. }
  190. /**
  191. * Set instance of the Redis.
  192. *
  193. * @param \Redis $redis
  194. */
  195. public function setRedis($redis)
  196. {
  197. $this->redis = $redis;
  198. }
  199. private function createProfileFromData($token, $data, $parent = null)
  200. {
  201. $profile = new Profile($token);
  202. $profile->setIp($data['ip']);
  203. $profile->setMethod($data['method']);
  204. $profile->setUrl($data['url']);
  205. $profile->setTime($data['time']);
  206. $profile->setCollectors($data['data']);
  207. if (!$parent && $data['parent']) {
  208. $parent = $this->read($data['parent']);
  209. }
  210. if ($parent) {
  211. $profile->setParent($parent);
  212. }
  213. foreach ($data['children'] as $token) {
  214. if (!$token) {
  215. continue;
  216. }
  217. if (!$childProfileData = $this->getValue($this->getItemName($token), self::REDIS_SERIALIZER_PHP)) {
  218. continue;
  219. }
  220. $profile->addChild($this->createProfileFromData($token, $childProfileData, $profile));
  221. }
  222. return $profile;
  223. }
  224. /**
  225. * Gets the item name.
  226. *
  227. * @param string $token
  228. *
  229. * @return string
  230. */
  231. private function getItemName($token)
  232. {
  233. $name = $token;
  234. if ($this->isItemNameValid($name)) {
  235. return $name;
  236. }
  237. return false;
  238. }
  239. /**
  240. * Gets the name of the index.
  241. *
  242. * @return string
  243. */
  244. private function getIndexName()
  245. {
  246. $name = 'index';
  247. if ($this->isItemNameValid($name)) {
  248. return $name;
  249. }
  250. return false;
  251. }
  252. private function isItemNameValid($name)
  253. {
  254. $length = strlen($name);
  255. if ($length > 2147483648) {
  256. throw new \RuntimeException(sprintf('The Redis item key "%s" is too long (%s bytes). Allowed maximum size is 2^31 bytes.', $name, $length));
  257. }
  258. return true;
  259. }
  260. /**
  261. * Retrieves an item from the Redis server.
  262. *
  263. * @param string $key
  264. * @param int $serializer
  265. *
  266. * @return mixed
  267. */
  268. private function getValue($key, $serializer = self::REDIS_SERIALIZER_NONE)
  269. {
  270. $redis = $this->getRedis();
  271. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  272. return $redis->get($key);
  273. }
  274. /**
  275. * Stores an item on the Redis server under the specified key.
  276. *
  277. * @param string $key
  278. * @param mixed $value
  279. * @param int $expiration
  280. * @param int $serializer
  281. *
  282. * @return bool
  283. */
  284. private function setValue($key, $value, $expiration = 0, $serializer = self::REDIS_SERIALIZER_NONE)
  285. {
  286. $redis = $this->getRedis();
  287. $redis->setOption(self::REDIS_OPT_SERIALIZER, $serializer);
  288. return $redis->setex($key, $expiration, $value);
  289. }
  290. /**
  291. * Appends data to an existing item on the Redis server.
  292. *
  293. * @param string $key
  294. * @param string $value
  295. * @param int $expiration
  296. *
  297. * @return bool
  298. */
  299. private function appendValue($key, $value, $expiration = 0)
  300. {
  301. $redis = $this->getRedis();
  302. $redis->setOption(self::REDIS_OPT_SERIALIZER, self::REDIS_SERIALIZER_NONE);
  303. if ($redis->exists($key)) {
  304. $redis->append($key, $value);
  305. return $redis->setTimeout($key, $expiration);
  306. }
  307. return $redis->setex($key, $expiration, $value);
  308. }
  309. /**
  310. * Removes the specified keys.
  311. *
  312. * @param array $keys
  313. *
  314. * @return bool
  315. */
  316. private function delete(array $keys)
  317. {
  318. return (bool) $this->getRedis()->delete($keys);
  319. }
  320. }