RedisProfilerStorage.php 9.9 KB

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