FileProfilerStorage.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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 (!str_starts_with($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 && !str_contains($csvIp, $ip) || $url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($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. return $this->doRead($token);
  101. }
  102. /**
  103. * {@inheritdoc}
  104. *
  105. * @throws \RuntimeException
  106. */
  107. public function write(Profile $profile): bool
  108. {
  109. $file = $this->getFilename($profile->getToken());
  110. $profileIndexed = is_file($file);
  111. if (!$profileIndexed) {
  112. // Create directory
  113. $dir = \dirname($file);
  114. if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
  115. throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));
  116. }
  117. }
  118. $profileToken = $profile->getToken();
  119. // when there are errors in sub-requests, the parent and/or children tokens
  120. // may equal the profile token, resulting in infinite loops
  121. $parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;
  122. $childrenToken = array_filter(array_map(function (Profile $p) use ($profileToken) {
  123. return $profileToken !== $p->getToken() ? $p->getToken() : null;
  124. }, $profile->getChildren()));
  125. // Store profile
  126. $data = [
  127. 'token' => $profileToken,
  128. 'parent' => $parentToken,
  129. 'children' => $childrenToken,
  130. 'data' => $profile->getCollectors(),
  131. 'ip' => $profile->getIp(),
  132. 'method' => $profile->getMethod(),
  133. 'url' => $profile->getUrl(),
  134. 'time' => $profile->getTime(),
  135. 'status_code' => $profile->getStatusCode(),
  136. ];
  137. $data = serialize($data);
  138. if (\function_exists('gzencode')) {
  139. $data = gzencode($data, 3);
  140. }
  141. if (false === file_put_contents($file, $data, \LOCK_EX)) {
  142. return false;
  143. }
  144. if (!$profileIndexed) {
  145. // Add to index
  146. if (false === $file = fopen($this->getIndexFilename(), 'a')) {
  147. return false;
  148. }
  149. fputcsv($file, [
  150. $profile->getToken(),
  151. $profile->getIp(),
  152. $profile->getMethod(),
  153. $profile->getUrl(),
  154. $profile->getTime(),
  155. $profile->getParentToken(),
  156. $profile->getStatusCode(),
  157. ]);
  158. fclose($file);
  159. }
  160. return true;
  161. }
  162. /**
  163. * Gets filename to store data, associated to the token.
  164. *
  165. * @return string
  166. */
  167. protected function getFilename(string $token)
  168. {
  169. // Uses 4 last characters, because first are mostly the same.
  170. $folderA = substr($token, -2, 2);
  171. $folderB = substr($token, -4, 2);
  172. return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
  173. }
  174. /**
  175. * Gets the index filename.
  176. *
  177. * @return string
  178. */
  179. protected function getIndexFilename()
  180. {
  181. return $this->folder.'/index.csv';
  182. }
  183. /**
  184. * Reads a line in the file, backward.
  185. *
  186. * This function automatically skips the empty lines and do not include the line return in result value.
  187. *
  188. * @param resource $file The file resource, with the pointer placed at the end of the line to read
  189. *
  190. * @return mixed
  191. */
  192. protected function readLineFromFile($file)
  193. {
  194. $line = '';
  195. $position = ftell($file);
  196. if (0 === $position) {
  197. return null;
  198. }
  199. while (true) {
  200. $chunkSize = min($position, 1024);
  201. $position -= $chunkSize;
  202. fseek($file, $position);
  203. if (0 === $chunkSize) {
  204. // bof reached
  205. break;
  206. }
  207. $buffer = fread($file, $chunkSize);
  208. if (false === ($upTo = strrpos($buffer, "\n"))) {
  209. $line = $buffer.$line;
  210. continue;
  211. }
  212. $position += $upTo;
  213. $line = substr($buffer, $upTo + 1).$line;
  214. fseek($file, max(0, $position), \SEEK_SET);
  215. if ('' !== $line) {
  216. break;
  217. }
  218. }
  219. return '' === $line ? null : $line;
  220. }
  221. protected function createProfileFromData(string $token, array $data, Profile $parent = null)
  222. {
  223. $profile = new Profile($token);
  224. $profile->setIp($data['ip']);
  225. $profile->setMethod($data['method']);
  226. $profile->setUrl($data['url']);
  227. $profile->setTime($data['time']);
  228. $profile->setStatusCode($data['status_code']);
  229. $profile->setCollectors($data['data']);
  230. if (!$parent && $data['parent']) {
  231. $parent = $this->read($data['parent']);
  232. }
  233. if ($parent) {
  234. $profile->setParent($parent);
  235. }
  236. foreach ($data['children'] as $token) {
  237. if (null !== $childProfile = $this->doRead($token, $profile)) {
  238. $profile->addChild($childProfile);
  239. }
  240. }
  241. return $profile;
  242. }
  243. private function doRead($token, Profile $profile = null): ?Profile
  244. {
  245. if (!$token || !file_exists($file = $this->getFilename($token))) {
  246. return null;
  247. }
  248. $h = fopen($file, 'r');
  249. flock($h, \LOCK_SH);
  250. $data = stream_get_contents($h);
  251. flock($h, \LOCK_UN);
  252. fclose($h);
  253. if (\function_exists('gzdecode')) {
  254. $data = @gzdecode($data) ?: $data;
  255. }
  256. if (!$data = unserialize($data)) {
  257. return null;
  258. }
  259. return $this->createProfileFromData($token, $data, $profile);
  260. }
  261. }