You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

303 lines
8.9 KiB

3 years ago
  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. * Storage for profiler using files.
  13. *
  14. * @author Alexandre Salomé <alexandre.salome@gmail.com>
  15. */
  16. class FileProfilerStorage implements ProfilerStorageInterface
  17. {
  18. /**
  19. * Folder where profiler data are stored.
  20. *
  21. * @var string
  22. */
  23. private $folder;
  24. /**
  25. * Constructs the file storage using a "dsn-like" path.
  26. *
  27. * Example : "file:/path/to/the/storage/folder"
  28. *
  29. * @throws \RuntimeException
  30. */
  31. public function __construct(string $dsn)
  32. {
  33. if (0 !== strpos($dsn, 'file:')) {
  34. throw new \RuntimeException(sprintf('Please check your configuration. You are trying to use FileStorage with an invalid dsn "%s". The expected format is "file:/path/to/the/storage/folder".', $dsn));
  35. }
  36. $this->folder = substr($dsn, 5);
  37. if (!is_dir($this->folder) && false === @mkdir($this->folder, 0777, true) && !is_dir($this->folder)) {
  38. throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder));
  39. }
  40. }
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function find(?string $ip, ?string $url, ?int $limit, ?string $method, int $start = null, int $end = null, string $statusCode = null): array
  45. {
  46. $file = $this->getIndexFilename();
  47. if (!file_exists($file)) {
  48. return [];
  49. }
  50. $file = fopen($file, 'r');
  51. fseek($file, 0, \SEEK_END);
  52. $result = [];
  53. while (\count($result) < $limit && $line = $this->readLineFromFile($file)) {
  54. $values = str_getcsv($line);
  55. [$csvToken, $csvIp, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values;
  56. $csvTime = (int) $csvTime;
  57. if ($ip && false === strpos($csvIp, $ip) || $url && false === strpos($csvUrl, $url) || $method && false === strpos($csvMethod, $method) || $statusCode && false === strpos($csvStatusCode, $statusCode)) {
  58. continue;
  59. }
  60. if (!empty($start) && $csvTime < $start) {
  61. continue;
  62. }
  63. if (!empty($end) && $csvTime > $end) {
  64. continue;
  65. }
  66. $result[$csvToken] = [
  67. 'token' => $csvToken,
  68. 'ip' => $csvIp,
  69. 'method' => $csvMethod,
  70. 'url' => $csvUrl,
  71. 'time' => $csvTime,
  72. 'parent' => $csvParent,
  73. 'status_code' => $csvStatusCode,
  74. ];
  75. }
  76. fclose($file);
  77. return array_values($result);
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function purge()
  83. {
  84. $flags = \FilesystemIterator::SKIP_DOTS;
  85. $iterator = new \RecursiveDirectoryIterator($this->folder, $flags);
  86. $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
  87. foreach ($iterator as $file) {
  88. if (is_file($file)) {
  89. unlink($file);
  90. } else {
  91. rmdir($file);
  92. }
  93. }
  94. }
  95. /**
  96. * {@inheritdoc}
  97. */
  98. public function read(string $token): ?Profile
  99. {
  100. if (!$token || !file_exists($file = $this->getFilename($token))) {
  101. return null;
  102. }
  103. if (\function_exists('gzcompress')) {
  104. $file = 'compress.zlib://'.$file;
  105. }
  106. return $this->createProfileFromData($token, unserialize(file_get_contents($file)));
  107. }
  108. /**
  109. * {@inheritdoc}
  110. *
  111. * @throws \RuntimeException
  112. */
  113. public function write(Profile $profile): bool
  114. {
  115. $file = $this->getFilename($profile->getToken());
  116. $profileIndexed = is_file($file);
  117. if (!$profileIndexed) {
  118. // Create directory
  119. $dir = \dirname($file);
  120. if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  121. throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));
  122. }
  123. }
  124. $profileToken = $profile->getToken();
  125. // when there are errors in sub-requests, the parent and/or children tokens
  126. // may equal the profile token, resulting in infinite loops
  127. $parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;
  128. $childrenToken = array_filter(array_map(function (Profile $p) use ($profileToken) {
  129. return $profileToken !== $p->getToken() ? $p->getToken() : null;
  130. }, $profile->getChildren()));
  131. // Store profile
  132. $data = [
  133. 'token' => $profileToken,
  134. 'parent' => $parentToken,
  135. 'children' => $childrenToken,
  136. 'data' => $profile->getCollectors(),
  137. 'ip' => $profile->getIp(),
  138. 'method' => $profile->getMethod(),
  139. 'url' => $profile->getUrl(),
  140. 'time' => $profile->getTime(),
  141. 'status_code' => $profile->getStatusCode(),
  142. ];
  143. $context = stream_context_create();
  144. if (\function_exists('gzcompress')) {
  145. $file = 'compress.zlib://'.$file;
  146. stream_context_set_option($context, 'zlib', 'level', 3);
  147. }
  148. if (false === file_put_contents($file, serialize($data), 0, $context)) {
  149. return false;
  150. }
  151. if (!$profileIndexed) {
  152. // Add to index
  153. if (false === $file = fopen($this->getIndexFilename(), 'a')) {
  154. return false;
  155. }
  156. fputcsv($file, [
  157. $profile->getToken(),
  158. $profile->getIp(),
  159. $profile->getMethod(),
  160. $profile->getUrl(),
  161. $profile->getTime(),
  162. $profile->getParentToken(),
  163. $profile->getStatusCode(),
  164. ]);
  165. fclose($file);
  166. }
  167. return true;
  168. }
  169. /**
  170. * Gets filename to store data, associated to the token.
  171. *
  172. * @return string The profile filename
  173. */
  174. protected function getFilename(string $token)
  175. {
  176. // Uses 4 last characters, because first are mostly the same.
  177. $folderA = substr($token, -2, 2);
  178. $folderB = substr($token, -4, 2);
  179. return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
  180. }
  181. /**
  182. * Gets the index filename.
  183. *
  184. * @return string The index filename
  185. */
  186. protected function getIndexFilename()
  187. {
  188. return $this->folder.'/index.csv';
  189. }
  190. /**
  191. * Reads a line in the file, backward.
  192. *
  193. * This function automatically skips the empty lines and do not include the line return in result value.
  194. *
  195. * @param resource $file The file resource, with the pointer placed at the end of the line to read
  196. *
  197. * @return mixed A string representing the line or null if beginning of file is reached
  198. */
  199. protected function readLineFromFile($file)
  200. {
  201. $line = '';
  202. $position = ftell($file);
  203. if (0 === $position) {
  204. return null;
  205. }
  206. while (true) {
  207. $chunkSize = min($position, 1024);
  208. $position -= $chunkSize;
  209. fseek($file, $position);
  210. if (0 === $chunkSize) {
  211. // bof reached
  212. break;
  213. }
  214. $buffer = fread($file, $chunkSize);
  215. if (false === ($upTo = strrpos($buffer, "\n"))) {
  216. $line = $buffer.$line;
  217. continue;
  218. }
  219. $position += $upTo;
  220. $line = substr($buffer, $upTo + 1).$line;
  221. fseek($file, max(0, $position), \SEEK_SET);
  222. if ('' !== $line) {
  223. break;
  224. }
  225. }
  226. return '' === $line ? null : $line;
  227. }
  228. protected function createProfileFromData(string $token, array $data, Profile $parent = null)
  229. {
  230. $profile = new Profile($token);
  231. $profile->setIp($data['ip']);
  232. $profile->setMethod($data['method']);
  233. $profile->setUrl($data['url']);
  234. $profile->setTime($data['time']);
  235. $profile->setStatusCode($data['status_code']);
  236. $profile->setCollectors($data['data']);
  237. if (!$parent && $data['parent']) {
  238. $parent = $this->read($data['parent']);
  239. }
  240. if ($parent) {
  241. $profile->setParent($parent);
  242. }
  243. foreach ($data['children'] as $token) {
  244. if (!$token || !file_exists($file = $this->getFilename($token))) {
  245. continue;
  246. }
  247. if (\function_exists('gzcompress')) {
  248. $file = 'compress.zlib://'.$file;
  249. }
  250. $profile->addChild($this->createProfileFromData($token, unserialize(file_get_contents($file)), $profile));
  251. }
  252. return $profile;
  253. }
  254. }