LockRegistry.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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\Cache;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Contracts\Cache\CacheInterface;
  13. use Symfony\Contracts\Cache\ItemInterface;
  14. /**
  15. * LockRegistry is used internally by existing adapters to protect against cache stampede.
  16. *
  17. * It does so by wrapping the computation of items in a pool of locks.
  18. * Foreach each apps, there can be at most 20 concurrent processes that
  19. * compute items at the same time and only one per cache-key.
  20. *
  21. * @author Nicolas Grekas <p@tchwork.com>
  22. */
  23. final class LockRegistry
  24. {
  25. private static $openedFiles = [];
  26. private static $lockedFiles;
  27. private static $signalingException;
  28. private static $signalingCallback;
  29. /**
  30. * The number of items in this list controls the max number of concurrent processes.
  31. */
  32. private static $files = [
  33. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractAdapter.php',
  34. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AbstractTagAwareAdapter.php',
  35. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'AdapterInterface.php',
  36. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ApcuAdapter.php',
  37. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ArrayAdapter.php',
  38. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ChainAdapter.php',
  39. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'DoctrineAdapter.php',
  40. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemAdapter.php',
  41. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'FilesystemTagAwareAdapter.php',
  42. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'MemcachedAdapter.php',
  43. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'NullAdapter.php',
  44. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PdoAdapter.php',
  45. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpArrayAdapter.php',
  46. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'PhpFilesAdapter.php',
  47. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'ProxyAdapter.php',
  48. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'Psr16Adapter.php',
  49. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisAdapter.php',
  50. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'RedisTagAwareAdapter.php',
  51. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'SimpleCacheAdapter.php',
  52. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapter.php',
  53. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TagAwareAdapterInterface.php',
  54. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableAdapter.php',
  55. __DIR__.\DIRECTORY_SEPARATOR.'Adapter'.\DIRECTORY_SEPARATOR.'TraceableTagAwareAdapter.php',
  56. ];
  57. /**
  58. * Defines a set of existing files that will be used as keys to acquire locks.
  59. *
  60. * @return array The previously defined set of files
  61. */
  62. public static function setFiles(array $files): array
  63. {
  64. $previousFiles = self::$files;
  65. self::$files = $files;
  66. foreach (self::$openedFiles as $file) {
  67. if ($file) {
  68. flock($file, \LOCK_UN);
  69. fclose($file);
  70. }
  71. }
  72. self::$openedFiles = self::$lockedFiles = [];
  73. return $previousFiles;
  74. }
  75. public static function compute(callable $callback, ItemInterface $item, bool &$save, CacheInterface $pool, \Closure $setMetadata = null, LoggerInterface $logger = null)
  76. {
  77. if ('\\' === \DIRECTORY_SEPARATOR && null === self::$lockedFiles) {
  78. // disable locking on Windows by default
  79. self::$files = self::$lockedFiles = [];
  80. }
  81. $key = self::$files ? abs(crc32($item->getKey())) % \count(self::$files) : -1;
  82. if ($key < 0 || self::$lockedFiles || !$lock = self::open($key)) {
  83. return $callback($item, $save);
  84. }
  85. self::$signalingException ?? self::$signalingException = unserialize("O:9:\"Exception\":1:{s:16:\"\0Exception\0trace\";a:0:{}}");
  86. self::$signalingCallback ?? self::$signalingCallback = function () { throw self::$signalingException; };
  87. while (true) {
  88. try {
  89. // race to get the lock in non-blocking mode
  90. $locked = flock($lock, \LOCK_EX | \LOCK_NB, $wouldBlock);
  91. if ($locked || !$wouldBlock) {
  92. $logger && $logger->info(sprintf('Lock %s, now computing item "{key}"', $locked ? 'acquired' : 'not supported'), ['key' => $item->getKey()]);
  93. self::$lockedFiles[$key] = true;
  94. $value = $callback($item, $save);
  95. if ($save) {
  96. if ($setMetadata) {
  97. $setMetadata($item);
  98. }
  99. $pool->save($item->set($value));
  100. $save = false;
  101. }
  102. return $value;
  103. }
  104. // if we failed the race, retry locking in blocking mode to wait for the winner
  105. $logger && $logger->info('Item "{key}" is locked, waiting for it to be released', ['key' => $item->getKey()]);
  106. flock($lock, \LOCK_SH);
  107. } finally {
  108. flock($lock, \LOCK_UN);
  109. unset(self::$lockedFiles[$key]);
  110. }
  111. try {
  112. $value = $pool->get($item->getKey(), self::$signalingCallback, 0);
  113. $logger && $logger->info('Item "{key}" retrieved after lock was released', ['key' => $item->getKey()]);
  114. $save = false;
  115. return $value;
  116. } catch (\Exception $e) {
  117. if (self::$signalingException !== $e) {
  118. throw $e;
  119. }
  120. $logger && $logger->info('Item "{key}" not found while lock was released, now retrying', ['key' => $item->getKey()]);
  121. }
  122. }
  123. return null;
  124. }
  125. private static function open(int $key)
  126. {
  127. if (null !== $h = self::$openedFiles[$key] ?? null) {
  128. return $h;
  129. }
  130. set_error_handler(function () {});
  131. try {
  132. $h = fopen(self::$files[$key], 'r+');
  133. } finally {
  134. restore_error_handler();
  135. }
  136. return self::$openedFiles[$key] = $h ?: @fopen(self::$files[$key], 'r');
  137. }
  138. }