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()
95 protected function doLock( array $paths, $type ) {
96 $status = Status
::newGood();
98 $pathsToLock = array();
99 // Get locks that need to be acquired (buckets => locks)...
100 foreach ( $paths as $path ) {
101 if ( isset( $this->locksHeld
[$path][$type] ) ) {
102 ++
$this->locksHeld
[$path][$type];
103 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
104 $this->locksHeld
[$path][$type] = 1;
106 $bucket = $this->getBucketFromKey( $path );
107 $pathsToLock[$bucket][] = $path;
111 $lockedPaths = array(); // files locked in this attempt
112 // Attempt to acquire these locks...
113 foreach ( $pathsToLock as $bucket => $paths ) {
114 // Try to acquire the locks for this bucket
115 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
116 if ( $res === 'cantacquire' ) {
117 // Resources already locked by another process.
118 // Abort and unlock everything we just locked.
119 foreach ( $paths as $path ) {
120 $status->fatal( 'lockmanager-fail-acquirelock', $path );
122 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
124 } elseif ( $res !== true ) {
125 // Couldn't contact any DBs for this bucket.
126 // Abort and unlock everything we just locked.
127 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
128 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
131 // Record these locks as active
132 foreach ( $paths as $path ) {
133 $this->locksHeld
[$path][$type] = 1; // locked
135 // Keep track of what locks were made in this attempt
136 $lockedPaths = array_merge( $lockedPaths, $paths );
143 * @see LockManager::doUnlock()
146 protected function doUnlock( array $paths, $type ) {
147 $status = Status
::newGood();
149 foreach ( $paths as $path ) {
150 if ( !isset( $this->locksHeld
[$path] ) ) {
151 $status->warning( 'lockmanager-notlocked', $path );
152 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
153 $status->warning( 'lockmanager-notlocked', $path );
155 --$this->locksHeld
[$path][$type];
156 if ( $this->locksHeld
[$path][$type] <= 0 ) {
157 unset( $this->locksHeld
[$path][$type] );
159 if ( !count( $this->locksHeld
[$path] ) ) {
160 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
165 // Reference count the locks held and COMMIT when zero
166 if ( !count( $this->locksHeld
) ) {
167 $status->merge( $this->finishLockTransactions() );
174 * Get a connection to a lock DB and acquire locks on $paths.
175 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
177 * @param $lockDb string
178 * @param $paths Array
179 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
180 * @return bool Resources able to be locked
183 protected function doLockingQuery( $lockDb, array $paths, $type ) {
184 if ( $type == self
::LOCK_EX
) { // writer locks
185 $db = $this->getConnection( $lockDb );
187 return false; // bad config
189 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
190 # Build up values for INSERT clause
192 foreach ( $keys as $key ) {
193 $data[] = array( 'fle_key' => $key );
195 # Wait on any existing writers and block new ones if we get in
196 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
202 * Attempt to acquire locks with the peers for a bucket.
203 * This should avoid throwing any exceptions.
205 * @param $bucket integer
206 * @param $paths Array List of resource keys to lock
207 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
208 * @return bool|string One of (true, 'cantacquire', 'dberrors')
210 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
211 $yesVotes = 0; // locks made on trustable DBs
212 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
213 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
214 // Get votes for each DB, in order, until we have enough...
215 foreach ( $this->dbsByBucket
[$bucket] as $lockDb ) {
216 // Check that DB is not *known* to be down
217 if ( $this->cacheCheckFailures( $lockDb ) ) {
219 // Attempt to acquire the lock on this DB
220 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
221 return 'cantacquire'; // vetoed; resource locked
223 ++
$yesVotes; // success for this peer
224 if ( $yesVotes >= $quorum ) {
225 return true; // lock obtained
227 } catch ( DBConnectionError
$e ) {
228 $this->cacheRecordFailure( $lockDb );
229 } catch ( DBError
$e ) {
230 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
231 return 'cantacquire'; // vetoed; resource locked
236 $votesNeeded = $quorum - $yesVotes;
237 if ( $votesNeeded > $votesLeft ) {
238 // In "trust cache" mode we don't have to meet the quorum
239 break; // short-circuit
242 // At this point, we must not have meet the quorum
243 return 'dberrors'; // not enough votes to ensure correctness
247 * Get (or reuse) a connection to a lock DB
249 * @param $lockDb string
250 * @return DatabaseBase
253 protected function getConnection( $lockDb ) {
254 if ( !isset( $this->conns
[$lockDb] ) ) {
256 if ( $lockDb === 'localDBMaster' ) {
257 $lb = wfGetLBFactory()->newMainLB();
258 $db = $lb->getConnection( DB_MASTER
);
259 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
260 $config = $this->dbServers
[$lockDb];
261 $db = DatabaseBase
::factory( $config['type'], $config );
264 return null; // config error?
266 $this->conns
[$lockDb] = $db;
267 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
268 # If the connection drops, try to avoid letting the DB rollback
269 # and release the locks before the file operations are finished.
270 # This won't handle the case of DB server restarts however.
272 if ( $this->lockExpiry
> 0 ) {
273 $options['connTimeout'] = $this->lockExpiry
;
275 $this->conns
[$lockDb]->setSessionOptions( $options );
276 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
278 if ( !$this->conns
[$lockDb]->trxLevel() ) {
279 $this->conns
[$lockDb]->begin(); // start transaction
281 return $this->conns
[$lockDb];
285 * Do additional initialization for new lock DB connection
287 * @param $lockDb string
288 * @param $db DatabaseBase
292 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
295 * Commit all changes to lock-active databases.
296 * This should avoid throwing any exceptions.
300 protected function finishLockTransactions() {
301 $status = Status
::newGood();
302 foreach ( $this->conns
as $lockDb => $db ) {
303 if ( $db->trxLevel() ) { // in transaction
305 $db->rollback(); // finish transaction and kill any rows
306 } catch ( DBError
$e ) {
307 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
315 * Check if the last DB error for $lockDb indicates
316 * that a requested resource was locked by another process.
317 * This should avoid throwing any exceptions.
319 * @param $lockDb string
322 protected function lastErrorIndicatesLocked( $lockDb ) {
323 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
324 $db = $this->conns
[$lockDb];
325 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
331 * Checks if the DB has not recently had connection/query errors.
332 * This just avoids wasting time on doomed connection attempts.
334 * @param $lockDb string
337 protected function cacheCheckFailures( $lockDb ) {
338 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
339 $path = $this->getMissKey( $lockDb );
340 $misses = $this->statusCache
->get( $path );
347 * Log a lock request failure to the cache
349 * @param $lockDb string
350 * @return bool Success
352 protected function cacheRecordFailure( $lockDb ) {
353 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
354 $path = $this->getMissKey( $lockDb );
355 $misses = $this->statusCache
->get( $path );
357 return $this->statusCache
->incr( $path );
359 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
366 * Get a cache key for recent query misses for a DB
368 * @param $lockDb string
371 protected function getMissKey( $lockDb ) {
372 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
376 * Get the bucket for resource path.
377 * This should avoid throwing any exceptions.
379 * @param $path string
382 protected function getBucketFromKey( $path ) {
383 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
384 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
388 * Make sure remaining locks get cleared for sanity
390 function __destruct() {
391 foreach ( $this->conns
as $lockDb => $db ) {
392 if ( $db->trxLevel() ) { // in transaction
394 $db->rollback(); // finish transaction and kill any rows
395 } catch ( DBError
$e ) {
405 * MySQL version of DBLockManager that supports shared locks.
406 * All locks are non-blocking, which avoids deadlocks.
408 * @ingroup LockManager
410 class MySqlLockManager
extends DBLockManager
{
411 /** @var Array Mapping of lock types to the type actually used */
412 protected $lockTypeMap = array(
413 self
::LOCK_SH
=> self
::LOCK_SH
,
414 self
::LOCK_UW
=> self
::LOCK_SH
,
415 self
::LOCK_EX
=> self
::LOCK_EX
418 protected function initConnection( $lockDb, DatabaseBase
$db ) {
419 # Let this transaction see lock rows from other transactions
420 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
423 protected function doLockingQuery( $lockDb, array $paths, $type ) {
424 $db = $this->getConnection( $lockDb );
428 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
429 # Build up values for INSERT clause
431 foreach ( $keys as $key ) {
432 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
434 # Block new writers...
435 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
436 # Actually do the locking queries...
437 if ( $type == self
::LOCK_SH
) { // reader locks
438 # Bail if there are any existing writers...
439 $blocked = $db->selectField( 'filelocks_exclusive', '1',
440 array( 'fle_key' => $keys ),
443 # Prospective writers that haven't yet updated filelocks_exclusive
444 # will recheck filelocks_shared after doing so and bail due to our entry.
445 } else { // writer locks
446 $encSession = $db->addQuotes( $this->session
);
447 # Bail if there are any existing writers...
448 # The may detect readers, but the safe check for them is below.
449 # Note: if two writers come at the same time, both bail :)
450 $blocked = $db->selectField( 'filelocks_shared', '1',
451 array( 'fls_key' => $keys, "fls_session != $encSession" ),
455 # Build up values for INSERT clause
457 foreach ( $keys as $key ) {
458 $data[] = array( 'fle_key' => $key );
460 # Block new readers/writers...
461 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
462 # Bail if there are any existing readers...
463 $blocked = $db->selectField( 'filelocks_shared', '1',
464 array( 'fls_key' => $keys, "fls_session != $encSession" ),