RedisProfilerStorage.php 10 KB

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