3 * @defgroup LockManager Lock management
6 use Psr\Log\LoggerInterface
;
7 use Wikimedia\WaitConditionLoop
;
10 * Resource locking handling.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
28 * @ingroup LockManager
32 * @brief Class for handling resource locking.
34 * Locks on resource keys can either be shared or exclusive.
36 * Implementations must keep track of what is locked by this process
37 * in-memory and support nested locking calls (using reference counting).
38 * At least LOCK_UW and LOCK_EX must be implemented. LOCK_SH can be a no-op.
39 * Locks should either be non-blocking or have low wait timeouts.
41 * Subclasses should avoid throwing exceptions at all costs.
43 * @ingroup LockManager
46 abstract class LockManager
{
47 /** @var LoggerInterface */
50 /** @var array Mapping of lock types to the type actually used */
51 protected $lockTypeMap = [
52 self
::LOCK_SH
=> self
::LOCK_SH
,
53 self
::LOCK_UW
=> self
::LOCK_EX
, // subclasses may use self::LOCK_SH
54 self
::LOCK_EX
=> self
::LOCK_EX
57 /** @var array Map of (resource path => lock type => count) */
58 protected $locksHeld = [];
60 protected $domain; // string; domain (usually wiki ID)
61 protected $lockTTL; // integer; maximum time locks can be held
63 /** @var string Random 32-char hex number */
66 /** Lock types; stronger locks have higher values */
67 const LOCK_SH
= 1; // shared lock (for reads)
68 const LOCK_UW
= 2; // shared lock (for reads used to write elsewhere)
69 const LOCK_EX
= 3; // exclusive lock (for writes)
71 /** @var int Max expected lock expiry in any context */
72 const MAX_LOCK_TTL
= 7200; // 2 hours
75 * Construct a new instance from configuration
77 * @param array $config Parameters include:
78 * - domain : Domain (usually wiki ID) that all resources are relative to [optional]
79 * - lockTTL : Age (in seconds) at which resource locks should expire.
80 * This only applies if locks are not tied to a connection/process.
82 public function __construct( array $config ) {
83 $this->domain
= $config['domain'] ??
'global';
84 if ( isset( $config['lockTTL'] ) ) {
85 $this->lockTTL
= max( 5, $config['lockTTL'] );
86 } elseif ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ) {
87 $this->lockTTL
= 3600;
89 $met = ini_get( 'max_execution_time' ); // this is 0 in CLI mode
90 $this->lockTTL
= max( 5 * 60, 2 * (int)$met );
93 // Upper bound on how long to keep lock structures around. This is useful when setting
94 // TTLs, as the "lockTTL" value may vary based on CLI mode and app server group. This is
95 // a "safe" value that can be used to avoid clobbering other locks that use high TTLs.
96 $this->lockTTL
= min( $this->lockTTL
, self
::MAX_LOCK_TTL
);
99 for ( $i = 1; $i <= 5; ++
$i ) {
100 $random[] = mt_rand( 0, 0xFFFFFFF );
102 $this->session
= md5( implode( '-', $random ) );
104 $this->logger
= $config['logger'] ??
new \Psr\Log\
NullLogger();
108 * Lock the resources at the given abstract paths
110 * @param array $paths List of resource names
111 * @param int $type LockManager::LOCK_* constant
112 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.21)
113 * @return StatusValue
115 final public function lock( array $paths, $type = self
::LOCK_EX
, $timeout = 0 ) {
116 return $this->lockByType( [ $type => $paths ], $timeout );
120 * Lock the resources at the given abstract paths
122 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
123 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.21)
124 * @return StatusValue
127 final public function lockByType( array $pathsByType, $timeout = 0 ) {
128 $pathsByType = $this->normalizePathsByType( $pathsByType );
131 $loop = new WaitConditionLoop(
132 function () use ( &$status, $pathsByType ) {
133 $status = $this->doLockByType( $pathsByType );
135 return $status->isOK() ?
: WaitConditionLoop
::CONDITION_CONTINUE
;
145 * Unlock the resources at the given abstract paths
147 * @param array $paths List of paths
148 * @param int $type LockManager::LOCK_* constant
149 * @return StatusValue
151 final public function unlock( array $paths, $type = self
::LOCK_EX
) {
152 return $this->unlockByType( [ $type => $paths ] );
156 * Unlock the resources at the given abstract paths
158 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
159 * @return StatusValue
162 final public function unlockByType( array $pathsByType ) {
163 $pathsByType = $this->normalizePathsByType( $pathsByType );
164 $status = $this->doUnlockByType( $pathsByType );
170 * Get the base 36 SHA-1 of a string, padded to 31 digits.
171 * Before hashing, the path will be prefixed with the domain ID.
172 * This should be used internally for lock key or file names.
174 * @param string $path
177 final protected function sha1Base36Absolute( $path ) {
178 return Wikimedia\base_convert
( sha1( "{$this->domain}:{$path}" ), 16, 36, 31 );
182 * Get the base 16 SHA-1 of a string, padded to 31 digits.
183 * Before hashing, the path will be prefixed with the domain ID.
184 * This should be used internally for lock key or file names.
186 * @param string $path
189 final protected function sha1Base16Absolute( $path ) {
190 return sha1( "{$this->domain}:{$path}" );
194 * Normalize the $paths array by converting LOCK_UW locks into the
195 * appropriate type and removing any duplicated paths for each lock type.
197 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
201 final protected function normalizePathsByType( array $pathsByType ) {
203 foreach ( $pathsByType as $type => $paths ) {
204 $res[$this->lockTypeMap
[$type]] = array_unique( $paths );
211 * @see LockManager::lockByType()
212 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
213 * @return StatusValue
216 protected function doLockByType( array $pathsByType ) {
217 $status = StatusValue
::newGood();
218 $lockedByType = []; // map of (type => paths)
219 foreach ( $pathsByType as $type => $paths ) {
220 $status->merge( $this->doLock( $paths, $type ) );
221 if ( $status->isOK() ) {
222 $lockedByType[$type] = $paths;
224 // Release the subset of locks that were acquired
225 foreach ( $lockedByType as $lType => $lPaths ) {
226 $status->merge( $this->doUnlock( $lPaths, $lType ) );
236 * Lock resources with the given keys and lock type
238 * @param array $paths List of paths
239 * @param int $type LockManager::LOCK_* constant
240 * @return StatusValue
242 abstract protected function doLock( array $paths, $type );
245 * @see LockManager::unlockByType()
246 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
247 * @return StatusValue
250 protected function doUnlockByType( array $pathsByType ) {
251 $status = StatusValue
::newGood();
252 foreach ( $pathsByType as $type => $paths ) {
253 $status->merge( $this->doUnlock( $paths, $type ) );
260 * Unlock resources with the given keys and lock type
262 * @param array $paths List of paths
263 * @param int $type LockManager::LOCK_* constant
264 * @return StatusValue
266 abstract protected function doUnlock( array $paths, $type );