4 * Version of LockManager based on using DB table locks.
5 * This is meant for multi-wiki systems that may share files.
6 * All locks are blocking, so it might be useful to set a small
7 * lock-wait timeout via server config to curtail deadlocks.
9 * All lock requests for a resource, identified by a hash string, will map
10 * to one bucket. Each bucket maps to one or several peer DBs, each on their
11 * own server, all having the filelocks.sql tables (with row-level locking).
12 * A majority of peer DBs must agree for a lock to be acquired.
14 * Caching is used to avoid hitting servers that are down.
16 * @ingroup LockManager
19 class DBLockManager
extends LockManager
{
20 /** @var Array Map of DB names to server config */
21 protected $dbServers; // (DB name => server config array)
22 /** @var Array Map of bucket indexes to peer DB lists */
23 protected $dbsByBucket; // (bucket index => (ldb1, ldb2, ...))
25 protected $statusCache;
27 protected $lockExpiry; // integer number of seconds
28 protected $safeDelay; // integer number of seconds
30 protected $session = 0; // random integer
31 /** @var Array Map Database connections (DB name => Database) */
32 protected $conns = array();
35 * Construct a new instance from configuration.
37 * $config paramaters include:
38 * 'dbServers' : Associative array of DB names to server configuration.
39 * Configuration is an associative array that includes:
40 * 'host' - DB server name
42 * 'type' - DB type (mysql,postgres,...)
44 * 'password' - DB user password
45 * 'tablePrefix' - DB table prefix
46 * 'flags' - DB flags (see DatabaseBase)
47 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
48 * each having an odd-numbered list of DB names (peers) as values.
49 * Any DB named 'localDBMaster' will automatically use the DB master
50 * settings for this wiki (without the need for a dbServers entry).
51 * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
52 * This tells the DB server how long to wait before assuming
53 * connection failure and releasing all the locks for a session.
55 * @param Array $config
57 public function __construct( array $config ) {
58 $this->dbServers
= isset( $config['dbServers'] )
59 ?
$config['dbServers']
60 : array(); // likely just using 'localDBMaster'
61 // Sanitize dbsByBucket config to prevent PHP errors
62 $this->dbsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
63 $this->dbsByBucket
= array_values( $this->dbsByBucket
); // consecutive
65 if ( isset( $config['lockExpiry'] ) ) {
66 $this->lockExpiry
= $config['lockExpiry'];
68 $met = ini_get( 'max_execution_time' );
69 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
71 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
72 ?
60 // pick a safe-ish number to match DB timeout default
73 : $this->lockExpiry
; // cover worst case
75 foreach ( $this->dbsByBucket
as $bucket ) {
76 if ( count( $bucket ) > 1 ) {
77 // Tracks peers that couldn't be queried recently to avoid lengthy
78 // connection timeouts. This is useless if each bucket has one peer.
79 $this->statusCache
= wfGetMainCache();
85 for ( $i = 0; $i < 5; $i++
) {
86 $this->session
.= mt_rand( 0, 2147483647 );
88 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
92 * @see LockManager::doLock()
94 protected function doLock( array $paths, $type ) {
95 $status = Status
::newGood();
97 $pathsToLock = array();
98 // Get locks that need to be acquired (buckets => locks)...
99 foreach ( $paths as $path ) {
100 if ( isset( $this->locksHeld
[$path][$type] ) ) {
101 ++
$this->locksHeld
[$path][$type];
102 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
103 $this->locksHeld
[$path][$type] = 1;
105 $bucket = $this->getBucketFromKey( $path );
106 $pathsToLock[$bucket][] = $path;
110 $lockedPaths = array(); // files locked in this attempt
111 // Attempt to acquire these locks...
112 foreach ( $pathsToLock as $bucket => $paths ) {
113 // Try to acquire the locks for this bucket
114 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
115 if ( $res === 'cantacquire' ) {
116 // Resources already locked by another process.
117 // Abort and unlock everything we just locked.
118 foreach ( $paths as $path ) {
119 $status->fatal( 'lockmanager-fail-acquirelock', $path );
121 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
123 } elseif ( $res !== true ) {
124 // Couldn't contact any DBs for this bucket.
125 // Abort and unlock everything we just locked.
126 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
127 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
130 // Record these locks as active
131 foreach ( $paths as $path ) {
132 $this->locksHeld
[$path][$type] = 1; // locked
134 // Keep track of what locks were made in this attempt
135 $lockedPaths = array_merge( $lockedPaths, $paths );
142 * @see LockManager::doUnlock()
144 protected function doUnlock( array $paths, $type ) {
145 $status = Status
::newGood();
147 foreach ( $paths as $path ) {
148 if ( !isset( $this->locksHeld
[$path] ) ) {
149 $status->warning( 'lockmanager-notlocked', $path );
150 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
151 $status->warning( 'lockmanager-notlocked', $path );
153 --$this->locksHeld
[$path][$type];
154 if ( $this->locksHeld
[$path][$type] <= 0 ) {
155 unset( $this->locksHeld
[$path][$type] );
157 if ( !count( $this->locksHeld
[$path] ) ) {
158 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
163 // Reference count the locks held and COMMIT when zero
164 if ( !count( $this->locksHeld
) ) {
165 $status->merge( $this->finishLockTransactions() );
172 * Get a connection to a lock DB and acquire locks on $paths.
173 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
175 * @param $lockDb string
176 * @param $paths Array
177 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
178 * @return bool Resources able to be locked
181 protected function doLockingQuery( $lockDb, array $paths, $type ) {
182 if ( $type == self
::LOCK_EX
) { // writer locks
183 $db = $this->getConnection( $lockDb );
185 return false; // bad config
187 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
188 # Build up values for INSERT clause
190 foreach ( $keys as $key ) {
191 $data[] = array( 'fle_key' => $key );
193 # Wait on any existing writers and block new ones if we get in
194 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
200 * Attempt to acquire locks with the peers for a bucket.
201 * This should avoid throwing any exceptions.
203 * @param $bucket integer
204 * @param $paths Array List of resource keys to lock
205 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
206 * @return bool|string One of (true, 'cantacquire', 'dberrors')
208 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
209 $yesVotes = 0; // locks made on trustable DBs
210 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
211 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
212 // Get votes for each DB, in order, until we have enough...
213 foreach ( $this->dbsByBucket
[$bucket] as $lockDb ) {
214 // Check that DB is not *known* to be down
215 if ( $this->cacheCheckFailures( $lockDb ) ) {
217 // Attempt to acquire the lock on this DB
218 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
219 return 'cantacquire'; // vetoed; resource locked
221 ++
$yesVotes; // success for this peer
222 if ( $yesVotes >= $quorum ) {
223 return true; // lock obtained
225 } catch ( DBConnectionError
$e ) {
226 $this->cacheRecordFailure( $lockDb );
227 } catch ( DBError
$e ) {
228 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
229 return 'cantacquire'; // vetoed; resource locked
234 $votesNeeded = $quorum - $yesVotes;
235 if ( $votesNeeded > $votesLeft ) {
236 // In "trust cache" mode we don't have to meet the quorum
237 break; // short-circuit
240 // At this point, we must not have meet the quorum
241 return 'dberrors'; // not enough votes to ensure correctness
245 * Get (or reuse) a connection to a lock DB
247 * @param $lockDb string
251 protected function getConnection( $lockDb ) {
252 if ( !isset( $this->conns
[$lockDb] ) ) {
254 if ( $lockDb === 'localDBMaster' ) {
255 $lb = wfGetLBFactory()->newMainLB();
256 $db = $lb->getConnection( DB_MASTER
);
257 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
258 $config = $this->dbServers
[$lockDb];
259 $db = DatabaseBase
::factory( $config['type'], $config );
262 return null; // config error?
264 $this->conns
[$lockDb] = $db;
265 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
266 # If the connection drops, try to avoid letting the DB rollback
267 # and release the locks before the file operations are finished.
268 # This won't handle the case of DB server restarts however.
270 if ( $this->lockExpiry
> 0 ) {
271 $options['connTimeout'] = $this->lockExpiry
;
273 $this->conns
[$lockDb]->setSessionOptions( $options );
274 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
276 if ( !$this->conns
[$lockDb]->trxLevel() ) {
277 $this->conns
[$lockDb]->begin(); // start transaction
279 return $this->conns
[$lockDb];
283 * Do additional initialization for new lock DB connection
285 * @param $lockDb string
286 * @param $db DatabaseBase
290 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
293 * Commit all changes to lock-active databases.
294 * This should avoid throwing any exceptions.
298 protected function finishLockTransactions() {
299 $status = Status
::newGood();
300 foreach ( $this->conns
as $lockDb => $db ) {
301 if ( $db->trxLevel() ) { // in transaction
303 $db->rollback(); // finish transaction and kill any rows
304 } catch ( DBError
$e ) {
305 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
313 * Check if the last DB error for $lockDb indicates
314 * that a requested resource was locked by another process.
315 * This should avoid throwing any exceptions.
317 * @param $lockDb string
320 protected function lastErrorIndicatesLocked( $lockDb ) {
321 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
322 $db = $this->conns
[$lockDb];
323 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
329 * Checks if the DB has not recently had connection/query errors.
330 * This just avoids wasting time on doomed connection attempts.
332 * @param $lockDb string
335 protected function cacheCheckFailures( $lockDb ) {
336 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
337 $path = $this->getMissKey( $lockDb );
338 $misses = $this->statusCache
->get( $path );
345 * Log a lock request failure to the cache
347 * @param $lockDb string
348 * @return bool Success
350 protected function cacheRecordFailure( $lockDb ) {
351 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
352 $path = $this->getMissKey( $lockDb );
353 $misses = $this->statusCache
->get( $path );
355 return $this->statusCache
->incr( $path );
357 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
364 * Get a cache key for recent query misses for a DB
366 * @param $lockDb string
369 protected function getMissKey( $lockDb ) {
370 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
374 * Get the bucket for resource path.
375 * This should avoid throwing any exceptions.
377 * @param $path string
380 protected function getBucketFromKey( $path ) {
381 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
382 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
386 * Make sure remaining locks get cleared for sanity
388 function __destruct() {
389 foreach ( $this->conns
as $lockDb => $db ) {
390 if ( $db->trxLevel() ) { // in transaction
392 $db->rollback(); // finish transaction and kill any rows
393 } catch ( DBError
$e ) {
403 * MySQL version of DBLockManager that supports shared locks.
404 * All locks are non-blocking, which avoids deadlocks.
406 * @ingroup LockManager
408 class MySqlLockManager
extends DBLockManager
{
409 /** @var Array Mapping of lock types to the type actually used */
410 protected $lockTypeMap = array(
411 self
::LOCK_SH
=> self
::LOCK_SH
,
412 self
::LOCK_UW
=> self
::LOCK_SH
,
413 self
::LOCK_EX
=> self
::LOCK_EX
416 protected function initConnection( $lockDb, DatabaseBase
$db ) {
417 # Let this transaction see lock rows from other transactions
418 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
421 protected function doLockingQuery( $lockDb, array $paths, $type ) {
422 $db = $this->getConnection( $lockDb );
426 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
427 # Build up values for INSERT clause
429 foreach ( $keys as $key ) {
430 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
432 # Block new writers...
433 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
434 # Actually do the locking queries...
435 if ( $type == self
::LOCK_SH
) { // reader locks
436 # Bail if there are any existing writers...
437 $blocked = $db->selectField( 'filelocks_exclusive', '1',
438 array( 'fle_key' => $keys ),
441 # Prospective writers that haven't yet updated filelocks_exclusive
442 # will recheck filelocks_shared after doing so and bail due to our entry.
443 } else { // writer locks
444 $encSession = $db->addQuotes( $this->session
);
445 # Bail if there are any existing writers...
446 # The may detect readers, but the safe check for them is below.
447 # Note: if two writers come at the same time, both bail :)
448 $blocked = $db->selectField( 'filelocks_shared', '1',
449 array( 'fls_key' => $keys, "fls_session != $encSession" ),
453 # Build up values for INSERT clause
455 foreach ( $keys as $key ) {
456 $data[] = array( 'fle_key' => $key );
458 # Block new readers/writers...
459 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
460 # Bail if there are any existing readers...
461 $blocked = $db->selectField( 'filelocks_shared', '1',
462 array( 'fls_key' => $keys, "fls_session != $encSession" ),