FileProfilerStorage.php 8.8 KB

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