Drupal investigation

RedisProfilerStorage.php 10KB

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