Brak opisu

FileProfilerStorage.php 9.0KB

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