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
18 class DBLockManager
extends LockManager
{
19 /** @var Array Map of DB names to server config */
20 protected $dbServers; // (DB name => server config array)
21 /** @var Array Map of bucket indexes to peer DB lists */
22 protected $dbsByBucket; // (bucket index => (ldb1, ldb2, ...))
24 protected $statusCache;
26 protected $lockExpiry; // integer number of seconds
27 protected $safeDelay; // integer number of seconds
29 protected $session = 0; // random integer
30 /** @var Array Map Database connections (DB name => Database) */
31 protected $conns = array();
34 * Construct a new instance from configuration.
35 * $config paramaters include:
36 * 'dbServers' : Associative array of DB names to server configuration.
37 * Configuration is an associative array that includes:
38 * 'host' - DB server name
40 * 'type' - DB type (mysql,postgres,...)
42 * 'password' - DB user password
43 * 'tablePrefix' - DB table prefix
44 * 'flags' - DB flags (see DatabaseBase)
45 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
46 * each having an odd-numbered list of DB names (peers) as values.
47 * Any DB named 'localDBMaster' will automatically use the DB master
48 * settings for this wiki (without the need for a dbServers entry).
49 * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
50 * This tells the DB server how long to wait before assuming
51 * connection failure and releasing all the locks for a session.
53 * @param Array $config
55 public function __construct( array $config ) {
56 $this->dbServers
= $config['dbServers'];
57 // Sanitize dbsByBucket config to prevent PHP errors
58 $this->dbsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
59 $this->dbsByBucket
= array_values( $this->dbsByBucket
); // consecutive
61 if ( isset( $config['lockExpiry'] ) ) {
62 $this->lockExpiry
= $config['lockExpiry'];
64 $met = ini_get( 'max_execution_time' );
65 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
67 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
68 ?
60 // pick a safe-ish number to match DB timeout default
69 : $this->lockExpiry
; // cover worst case
71 foreach ( $this->dbsByBucket
as $bucket ) {
72 if ( count( $bucket ) > 1 ) {
73 // Tracks peers that couldn't be queried recently to avoid lengthy
74 // connection timeouts. This is useless if each bucket has one peer.
75 $this->statusCache
= wfGetMainCache();
81 for ( $i = 0; $i < 5; $i++
) {
82 $this->session
.= mt_rand( 0, 2147483647 );
84 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
88 * @see LockManager::doLock()
90 protected function doLock( array $paths, $type ) {
91 $status = Status
::newGood();
93 $pathsToLock = array();
94 // Get locks that need to be acquired (buckets => locks)...
95 foreach ( $paths as $path ) {
96 if ( isset( $this->locksHeld
[$path][$type] ) ) {
97 ++
$this->locksHeld
[$path][$type];
98 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
99 $this->locksHeld
[$path][$type] = 1;
101 $bucket = $this->getBucketFromKey( $path );
102 $pathsToLock[$bucket][] = $path;
106 $lockedPaths = array(); // files locked in this attempt
107 // Attempt to acquire these locks...
108 foreach ( $pathsToLock as $bucket => $paths ) {
109 // Try to acquire the locks for this bucket
110 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
111 if ( $res === 'cantacquire' ) {
112 // Resources already locked by another process.
113 // Abort and unlock everything we just locked.
114 $status->fatal( 'lockmanager-fail-acquirelocks', implode( ', ', $paths ) );
115 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
117 } elseif ( $res !== true ) {
118 // Couldn't contact any DBs for this bucket.
119 // Abort and unlock everything we just locked.
120 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
121 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
124 // Record these locks as active
125 foreach ( $paths as $path ) {
126 $this->locksHeld
[$path][$type] = 1; // locked
128 // Keep track of what locks were made in this attempt
129 $lockedPaths = array_merge( $lockedPaths, $paths );
136 * @see LockManager::doUnlock()
138 protected function doUnlock( array $paths, $type ) {
139 $status = Status
::newGood();
141 foreach ( $paths as $path ) {
142 if ( !isset( $this->locksHeld
[$path] ) ) {
143 $status->warning( 'lockmanager-notlocked', $path );
144 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
145 $status->warning( 'lockmanager-notlocked', $path );
147 --$this->locksHeld
[$path][$type];
148 if ( $this->locksHeld
[$path][$type] <= 0 ) {
149 unset( $this->locksHeld
[$path][$type] );
151 if ( !count( $this->locksHeld
[$path] ) ) {
152 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
157 // Reference count the locks held and COMMIT when zero
158 if ( !count( $this->locksHeld
) ) {
159 $status->merge( $this->finishLockTransactions() );
166 * Get a connection to a lock DB and acquire locks on $paths.
167 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
169 * @param $lockDb string
170 * @param $paths Array
171 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
172 * @return bool Resources able to be locked
175 protected function doLockingQuery( $lockDb, array $paths, $type ) {
176 if ( $type == self
::LOCK_EX
) { // writer locks
177 $db = $this->getConnection( $lockDb );
179 return false; // bad config
181 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
182 # Build up values for INSERT clause
184 foreach ( $keys as $key ) {
185 $data[] = array( 'fle_key' => $key );
187 # Wait on any existing writers and block new ones if we get in
188 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
194 * Attempt to acquire locks with the peers for a bucket.
195 * This should avoid throwing any exceptions.
197 * @param $bucket integer
198 * @param $paths Array List of resource keys to lock
199 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
200 * @return bool|string One of (true, 'cantacquire', 'dberrors')
202 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
203 $yesVotes = 0; // locks made on trustable DBs
204 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
205 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
206 // Get votes for each DB, in order, until we have enough...
207 foreach ( $this->dbsByBucket
[$bucket] as $index => $lockDb ) {
208 // Check that DB is not *known* to be down
209 if ( $this->cacheCheckFailures( $lockDb ) ) {
211 // Attempt to acquire the lock on this DB
212 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
213 return 'cantacquire'; // vetoed; resource locked
215 ++
$yesVotes; // success for this peer
216 if ( $yesVotes >= $quorum ) {
217 return true; // lock obtained
219 } catch ( DBConnectionError
$e ) {
220 $this->cacheRecordFailure( $lockDb );
221 } catch ( DBError
$e ) {
222 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
223 return 'cantacquire'; // vetoed; resource locked
228 $votesNeeded = $quorum - $yesVotes;
229 if ( $votesNeeded > $votesLeft ) {
230 // In "trust cache" mode we don't have to meet the quorum
231 break; // short-circuit
234 // At this point, we must not have meet the quorum
235 return 'dberrors'; // not enough votes to ensure correctness
239 * Get (or reuse) a connection to a lock DB
241 * @param $lockDb string
245 protected function getConnection( $lockDb ) {
246 if ( !isset( $this->conns
[$lockDb] ) ) {
248 if ( $lockDb === 'localDBMaster' ) {
249 $lb = wfGetLBFactory()->newMainLB();
250 $db = $lb->getConnection( DB_MASTER
);
251 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
252 $config = $this->dbServers
[$lockDb];
253 $db = DatabaseBase
::factory( $config['type'], $config );
256 return null; // config error?
258 $this->conns
[$lockDb] = $db;
259 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
260 # If the connection drops, try to avoid letting the DB rollback
261 # and release the locks before the file operations are finished.
262 # This won't handle the case of DB server restarts however.
264 if ( $this->lockExpiry
> 0 ) {
265 $options['connTimeout'] = $this->lockExpiry
;
267 $this->conns
[$lockDb]->setSessionOptions( $options );
268 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
270 if ( !$this->conns
[$lockDb]->trxLevel() ) {
271 $this->conns
[$lockDb]->begin(); // start transaction
273 return $this->conns
[$lockDb];
277 * Do additional initialization for new lock DB connection
279 * @param $lockDb string
280 * @param $db DatabaseBase
284 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
287 * Commit all changes to lock-active databases.
288 * This should avoid throwing any exceptions.
292 protected function finishLockTransactions() {
293 $status = Status
::newGood();
294 foreach ( $this->conns
as $lockDb => $db ) {
295 if ( $db->trxLevel() ) { // in transaction
297 $db->rollback(); // finish transaction and kill any rows
298 } catch ( DBError
$e ) {
299 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
307 * Check if the last DB error for $lockDb indicates
308 * that a requested resource was locked by another process.
309 * This should avoid throwing any exceptions.
311 * @param $lockDb string
314 protected function lastErrorIndicatesLocked( $lockDb ) {
315 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
316 $db = $this->conns
[$lockDb];
317 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
323 * Checks if the DB has not recently had connection/query errors.
324 * This just avoids wasting time on doomed connection attempts.
326 * @param $lockDb string
329 protected function cacheCheckFailures( $lockDb ) {
330 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
331 $path = $this->getMissKey( $lockDb );
332 $misses = $this->statusCache
->get( $path );
339 * Log a lock request failure to the cache
341 * @param $lockDb string
342 * @return bool Success
344 protected function cacheRecordFailure( $lockDb ) {
345 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
346 $path = $this->getMissKey( $lockDb );
347 $misses = $this->statusCache
->get( $path );
349 return $this->statusCache
->incr( $path );
351 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
358 * Get a cache key for recent query misses for a DB
360 * @param $lockDb string
363 protected function getMissKey( $lockDb ) {
364 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
368 * Get the bucket for resource path.
369 * This should avoid throwing any exceptions.
371 * @param $path string
374 protected function getBucketFromKey( $path ) {
375 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
376 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
380 * Make sure remaining locks get cleared for sanity
382 function __destruct() {
383 foreach ( $this->conns
as $lockDb => $db ) {
384 if ( $db->trxLevel() ) { // in transaction
386 $db->rollback(); // finish transaction and kill any rows
387 } catch ( DBError
$e ) {
397 * MySQL version of DBLockManager that supports shared locks.
398 * All locks are non-blocking, which avoids deadlocks.
400 * @ingroup LockManager
402 class MySqlLockManager
extends DBLockManager
{
403 /** @var Array Mapping of lock types to the type actually used */
404 protected $lockTypeMap = array(
405 self
::LOCK_SH
=> self
::LOCK_SH
,
406 self
::LOCK_UW
=> self
::LOCK_SH
,
407 self
::LOCK_EX
=> self
::LOCK_EX
410 protected function initConnection( $lockDb, DatabaseBase
$db ) {
411 # Let this transaction see lock rows from other transactions
412 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
415 protected function doLockingQuery( $lockDb, array $paths, $type ) {
416 $db = $this->getConnection( $lockDb );
420 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
421 # Build up values for INSERT clause
423 foreach ( $keys as $key ) {
424 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
426 # Block new writers...
427 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
428 # Actually do the locking queries...
429 if ( $type == self
::LOCK_SH
) { // reader locks
430 # Bail if there are any existing writers...
431 $blocked = $db->selectField( 'filelocks_exclusive', '1',
432 array( 'fle_key' => $keys ),
435 # Prospective writers that haven't yet updated filelocks_exclusive
436 # will recheck filelocks_shared after doing so and bail due to our entry.
437 } else { // writer locks
438 $encSession = $db->addQuotes( $this->session
);
439 # Bail if there are any existing writers...
440 # The may detect readers, but the safe check for them is below.
441 # Note: if two writers come at the same time, both bail :)
442 $blocked = $db->selectField( 'filelocks_shared', '1',
443 array( 'fls_key' => $keys, "fls_session != $encSession" ),
447 # Build up values for INSERT clause
449 foreach ( $keys as $key ) {
450 $data[] = array( 'fle_key' => $key );
452 # Block new readers/writers...
453 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
454 # Bail if there are any existing readers...
455 $blocked = $db->selectField( 'filelocks_shared', '1',
456 array( 'fls_key' => $keys, "fls_session != $encSession" ),