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
29 * @author Aaron Schulz
33 * @brief Class for handling resource locking.
35 * Locks on resource keys can either be shared or exclusive.
37 * Implementations must keep track of what is locked by this process
38 * in-memory and support nested locking calls (using reference counting).
39 * At least LOCK_UW and LOCK_EX must be implemented. LOCK_SH can be a no-op.
40 * Locks should either be non-blocking or have low wait timeouts.
42 * Subclasses should avoid throwing exceptions at all costs.
44 * @ingroup LockManager
47 abstract class LockManager
{
48 /** @var LoggerInterface */
51 /** @var array Mapping of lock types to the type actually used */
52 protected $lockTypeMap = [
53 self
::LOCK_SH
=> self
::LOCK_SH
,
54 self
::LOCK_UW
=> self
::LOCK_EX
, // subclasses may use self::LOCK_SH
55 self
::LOCK_EX
=> self
::LOCK_EX
58 /** @var array Map of (resource path => lock type => count) */
59 protected $locksHeld = [];
61 protected $domain; // string; domain (usually wiki ID)
62 protected $lockTTL; // integer; maximum time locks can be held
64 /** @var string Random 32-char hex number */
67 /** Lock types; stronger locks have higher values */
68 const LOCK_SH
= 1; // shared lock (for reads)
69 const LOCK_UW
= 2; // shared lock (for reads used to write elsewhere)
70 const LOCK_EX
= 3; // exclusive lock (for writes)
72 /** @var int Max expected lock expiry in any context */
73 const MAX_LOCK_TTL
= 7200; // 2 hours
76 * Construct a new instance from configuration
78 * @param array $config Parameters include:
79 * - domain : Domain (usually wiki ID) that all resources are relative to [optional]
80 * - lockTTL : Age (in seconds) at which resource locks should expire.
81 * This only applies if locks are not tied to a connection/process.
83 public function __construct( array $config ) {
84 $this->domain
= isset( $config['domain'] ) ?
$config['domain'] : 'global';
85 if ( isset( $config['lockTTL'] ) ) {
86 $this->lockTTL
= max( 5, $config['lockTTL'] );
87 } elseif ( PHP_SAPI
=== 'cli' ) {
88 $this->lockTTL
= 3600;
90 $met = ini_get( 'max_execution_time' ); // this is 0 in CLI mode
91 $this->lockTTL
= max( 5 * 60, 2 * (int)$met );
94 // Upper bound on how long to keep lock structures around. This is useful when setting
95 // TTLs, as the "lockTTL" value may vary based on CLI mode and app server group. This is
96 // a "safe" value that can be used to avoid clobbering other locks that use high TTLs.
97 $this->lockTTL
= min( $this->lockTTL
, self
::MAX_LOCK_TTL
);
100 for ( $i = 1; $i <= 5; ++
$i ) {
101 $random[] = mt_rand( 0, 0xFFFFFFF );
103 $this->session
= md5( implode( '-', $random ) );
105 $this->logger
= isset( $config['logger'] ) ?
$config['logger'] : new \Psr\Log\
NullLogger();
109 * Lock the resources at the given abstract paths
111 * @param array $paths List of resource names
112 * @param int $type LockManager::LOCK_* constant
113 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.21)
114 * @return StatusValue
116 final public function lock( array $paths, $type = self
::LOCK_EX
, $timeout = 0 ) {
117 return $this->lockByType( [ $type => $paths ], $timeout );
121 * Lock the resources at the given abstract paths
123 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
124 * @param int $timeout Timeout in seconds (0 means non-blocking) (since 1.21)
125 * @return StatusValue
128 final public function lockByType( array $pathsByType, $timeout = 0 ) {
129 $pathsByType = $this->normalizePathsByType( $pathsByType );
132 $loop = new WaitConditionLoop(
133 function () use ( &$status, $pathsByType ) {
134 $status = $this->doLockByType( $pathsByType );
136 return $status->isOK() ?
: WaitConditionLoop
::CONDITION_CONTINUE
;
146 * Unlock the resources at the given abstract paths
148 * @param array $paths List of paths
149 * @param int $type LockManager::LOCK_* constant
150 * @return StatusValue
152 final public function unlock( array $paths, $type = self
::LOCK_EX
) {
153 return $this->unlockByType( [ $type => $paths ] );
157 * Unlock the resources at the given abstract paths
159 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
160 * @return StatusValue
163 final public function unlockByType( array $pathsByType ) {
164 $pathsByType = $this->normalizePathsByType( $pathsByType );
165 $status = $this->doUnlockByType( $pathsByType );
171 * Get the base 36 SHA-1 of a string, padded to 31 digits.
172 * Before hashing, the path will be prefixed with the domain ID.
173 * This should be used internally for lock key or file names.
175 * @param string $path
178 final protected function sha1Base36Absolute( $path ) {
179 return Wikimedia\base_convert
( sha1( "{$this->domain}:{$path}" ), 16, 36, 31 );
183 * Get the base 16 SHA-1 of a string, padded to 31 digits.
184 * Before hashing, the path will be prefixed with the domain ID.
185 * This should be used internally for lock key or file names.
187 * @param string $path
190 final protected function sha1Base16Absolute( $path ) {
191 return sha1( "{$this->domain}:{$path}" );
195 * Normalize the $paths array by converting LOCK_UW locks into the
196 * appropriate type and removing any duplicated paths for each lock type.
198 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
202 final protected function normalizePathsByType( array $pathsByType ) {
204 foreach ( $pathsByType as $type => $paths ) {
205 $res[$this->lockTypeMap
[$type]] = array_unique( $paths );
212 * @see LockManager::lockByType()
213 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
214 * @return StatusValue
217 protected function doLockByType( array $pathsByType ) {
218 $status = StatusValue
::newGood();
219 $lockedByType = []; // map of (type => paths)
220 foreach ( $pathsByType as $type => $paths ) {
221 $status->merge( $this->doLock( $paths, $type ) );
222 if ( $status->isOK() ) {
223 $lockedByType[$type] = $paths;
225 // Release the subset of locks that were acquired
226 foreach ( $lockedByType as $lType => $lPaths ) {
227 $status->merge( $this->doUnlock( $lPaths, $lType ) );
237 * Lock resources with the given keys and lock type
239 * @param array $paths List of paths
240 * @param int $type LockManager::LOCK_* constant
241 * @return StatusValue
243 abstract protected function doLock( array $paths, $type );
246 * @see LockManager::unlockByType()
247 * @param array $pathsByType Map of LockManager::LOCK_* constants to lists of paths
248 * @return StatusValue
251 protected function doUnlockByType( array $pathsByType ) {
252 $status = StatusValue
::newGood();
253 foreach ( $pathsByType as $type => $paths ) {
254 $status->merge( $this->doUnlock( $paths, $type ) );
261 * Unlock resources with the given keys and lock type
263 * @param array $paths List of paths
264 * @param int $type LockManager::LOCK_* constant
265 * @return StatusValue
267 abstract protected function doUnlock( array $paths, $type );