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