ac9c0791d6557e313f3a388946dc9ae11c63bc39
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.
36 * $config paramaters include:
37 * 'dbServers' : Associative array of DB names to server configuration.
38 * Configuration is an associative array that includes:
39 * 'host' - DB server name
41 * 'type' - DB type (mysql,postgres,...)
43 * 'password' - DB user password
44 * 'tablePrefix' - DB table prefix
45 * 'flags' - DB flags (see DatabaseBase)
46 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
47 * each having an odd-numbered list of DB names (peers) as values.
48 * Any DB named 'localDBMaster' will automatically use the DB master
49 * settings for this wiki (without the need for a dbServers entry).
50 * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
51 * This tells the DB server how long to wait before assuming
52 * connection failure and releasing all the locks for a session.
54 * @param Array $config
56 public function __construct( array $config ) {
57 $this->dbServers
= $config['dbServers'];
58 // Sanitize dbsByBucket config to prevent PHP errors
59 $this->dbsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
60 $this->dbsByBucket
= array_values( $this->dbsByBucket
); // consecutive
62 if ( isset( $config['lockExpiry'] ) ) {
63 $this->lockExpiry
= $config['lockExpiry'];
65 $met = ini_get( 'max_execution_time' );
66 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
68 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
69 ?
60 // pick a safe-ish number to match DB timeout default
70 : $this->lockExpiry
; // cover worst case
72 foreach ( $this->dbsByBucket
as $bucket ) {
73 if ( count( $bucket ) > 1 ) {
74 // Tracks peers that couldn't be queried recently to avoid lengthy
75 // connection timeouts. This is useless if each bucket has one peer.
76 $this->statusCache
= wfGetMainCache();
82 for ( $i = 0; $i < 5; $i++
) {
83 $this->session
.= mt_rand( 0, 2147483647 );
85 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
89 * @see LockManager::doLock()
91 protected function doLock( array $paths, $type ) {
92 $status = Status
::newGood();
94 $pathsToLock = array();
95 // Get locks that need to be acquired (buckets => locks)...
96 foreach ( $paths as $path ) {
97 if ( isset( $this->locksHeld
[$path][$type] ) ) {
98 ++
$this->locksHeld
[$path][$type];
99 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
100 $this->locksHeld
[$path][$type] = 1;
102 $bucket = $this->getBucketFromKey( $path );
103 $pathsToLock[$bucket][] = $path;
107 $lockedPaths = array(); // files locked in this attempt
108 // Attempt to acquire these locks...
109 foreach ( $pathsToLock as $bucket => $paths ) {
110 // Try to acquire the locks for this bucket
111 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
112 if ( $res === 'cantacquire' ) {
113 // Resources already locked by another process.
114 // Abort and unlock everything we just locked.
115 foreach ( $paths as $path ) {
116 $status->fatal( 'lockmanager-fail-acquirelock', $path );
118 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
120 } elseif ( $res !== true ) {
121 // Couldn't contact any DBs for this bucket.
122 // Abort and unlock everything we just locked.
123 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
124 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
127 // Record these locks as active
128 foreach ( $paths as $path ) {
129 $this->locksHeld
[$path][$type] = 1; // locked
131 // Keep track of what locks were made in this attempt
132 $lockedPaths = array_merge( $lockedPaths, $paths );
139 * @see LockManager::doUnlock()
141 protected function doUnlock( array $paths, $type ) {
142 $status = Status
::newGood();
144 foreach ( $paths as $path ) {
145 if ( !isset( $this->locksHeld
[$path] ) ) {
146 $status->warning( 'lockmanager-notlocked', $path );
147 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
148 $status->warning( 'lockmanager-notlocked', $path );
150 --$this->locksHeld
[$path][$type];
151 if ( $this->locksHeld
[$path][$type] <= 0 ) {
152 unset( $this->locksHeld
[$path][$type] );
154 if ( !count( $this->locksHeld
[$path] ) ) {
155 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
160 // Reference count the locks held and COMMIT when zero
161 if ( !count( $this->locksHeld
) ) {
162 $status->merge( $this->finishLockTransactions() );
169 * Get a connection to a lock DB and acquire locks on $paths.
170 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
172 * @param $lockDb string
173 * @param $paths Array
174 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
175 * @return bool Resources able to be locked
178 protected function doLockingQuery( $lockDb, array $paths, $type ) {
179 if ( $type == self
::LOCK_EX
) { // writer locks
180 $db = $this->getConnection( $lockDb );
182 return false; // bad config
184 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
185 # Build up values for INSERT clause
187 foreach ( $keys as $key ) {
188 $data[] = array( 'fle_key' => $key );
190 # Wait on any existing writers and block new ones if we get in
191 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
197 * Attempt to acquire locks with the peers for a bucket.
198 * This should avoid throwing any exceptions.
200 * @param $bucket integer
201 * @param $paths Array List of resource keys to lock
202 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
203 * @return bool|string One of (true, 'cantacquire', 'dberrors')
205 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
206 $yesVotes = 0; // locks made on trustable DBs
207 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
208 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
209 // Get votes for each DB, in order, until we have enough...
210 foreach ( $this->dbsByBucket
[$bucket] as $lockDb ) {
211 // Check that DB is not *known* to be down
212 if ( $this->cacheCheckFailures( $lockDb ) ) {
214 // Attempt to acquire the lock on this DB
215 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
216 return 'cantacquire'; // vetoed; resource locked
218 ++
$yesVotes; // success for this peer
219 if ( $yesVotes >= $quorum ) {
220 return true; // lock obtained
222 } catch ( DBConnectionError
$e ) {
223 $this->cacheRecordFailure( $lockDb );
224 } catch ( DBError
$e ) {
225 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
226 return 'cantacquire'; // vetoed; resource locked
231 $votesNeeded = $quorum - $yesVotes;
232 if ( $votesNeeded > $votesLeft ) {
233 // In "trust cache" mode we don't have to meet the quorum
234 break; // short-circuit
237 // At this point, we must not have meet the quorum
238 return 'dberrors'; // not enough votes to ensure correctness
242 * Get (or reuse) a connection to a lock DB
244 * @param $lockDb string
248 protected function getConnection( $lockDb ) {
249 if ( !isset( $this->conns
[$lockDb] ) ) {
251 if ( $lockDb === 'localDBMaster' ) {
252 $lb = wfGetLBFactory()->newMainLB();
253 $db = $lb->getConnection( DB_MASTER
);
254 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
255 $config = $this->dbServers
[$lockDb];
256 $db = DatabaseBase
::factory( $config['type'], $config );
259 return null; // config error?
261 $this->conns
[$lockDb] = $db;
262 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
263 # If the connection drops, try to avoid letting the DB rollback
264 # and release the locks before the file operations are finished.
265 # This won't handle the case of DB server restarts however.
267 if ( $this->lockExpiry
> 0 ) {
268 $options['connTimeout'] = $this->lockExpiry
;
270 $this->conns
[$lockDb]->setSessionOptions( $options );
271 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
273 if ( !$this->conns
[$lockDb]->trxLevel() ) {
274 $this->conns
[$lockDb]->begin(); // start transaction
276 return $this->conns
[$lockDb];
280 * Do additional initialization for new lock DB connection
282 * @param $lockDb string
283 * @param $db DatabaseBase
287 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
290 * Commit all changes to lock-active databases.
291 * This should avoid throwing any exceptions.
295 protected function finishLockTransactions() {
296 $status = Status
::newGood();
297 foreach ( $this->conns
as $lockDb => $db ) {
298 if ( $db->trxLevel() ) { // in transaction
300 $db->rollback(); // finish transaction and kill any rows
301 } catch ( DBError
$e ) {
302 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
310 * Check if the last DB error for $lockDb indicates
311 * that a requested resource was locked by another process.
312 * This should avoid throwing any exceptions.
314 * @param $lockDb string
317 protected function lastErrorIndicatesLocked( $lockDb ) {
318 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
319 $db = $this->conns
[$lockDb];
320 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
326 * Checks if the DB has not recently had connection/query errors.
327 * This just avoids wasting time on doomed connection attempts.
329 * @param $lockDb string
332 protected function cacheCheckFailures( $lockDb ) {
333 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
334 $path = $this->getMissKey( $lockDb );
335 $misses = $this->statusCache
->get( $path );
342 * Log a lock request failure to the cache
344 * @param $lockDb string
345 * @return bool Success
347 protected function cacheRecordFailure( $lockDb ) {
348 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
349 $path = $this->getMissKey( $lockDb );
350 $misses = $this->statusCache
->get( $path );
352 return $this->statusCache
->incr( $path );
354 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
361 * Get a cache key for recent query misses for a DB
363 * @param $lockDb string
366 protected function getMissKey( $lockDb ) {
367 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
371 * Get the bucket for resource path.
372 * This should avoid throwing any exceptions.
374 * @param $path string
377 protected function getBucketFromKey( $path ) {
378 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
379 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
383 * Make sure remaining locks get cleared for sanity
385 function __destruct() {
386 foreach ( $this->conns
as $lockDb => $db ) {
387 if ( $db->trxLevel() ) { // in transaction
389 $db->rollback(); // finish transaction and kill any rows
390 } catch ( DBError
$e ) {
400 * MySQL version of DBLockManager that supports shared locks.
401 * All locks are non-blocking, which avoids deadlocks.
403 * @ingroup LockManager
405 class MySqlLockManager
extends DBLockManager
{
406 /** @var Array Mapping of lock types to the type actually used */
407 protected $lockTypeMap = array(
408 self
::LOCK_SH
=> self
::LOCK_SH
,
409 self
::LOCK_UW
=> self
::LOCK_SH
,
410 self
::LOCK_EX
=> self
::LOCK_EX
413 protected function initConnection( $lockDb, DatabaseBase
$db ) {
414 # Let this transaction see lock rows from other transactions
415 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
418 protected function doLockingQuery( $lockDb, array $paths, $type ) {
419 $db = $this->getConnection( $lockDb );
423 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
424 # Build up values for INSERT clause
426 foreach ( $keys as $key ) {
427 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
429 # Block new writers...
430 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
431 # Actually do the locking queries...
432 if ( $type == self
::LOCK_SH
) { // reader locks
433 # Bail if there are any existing writers...
434 $blocked = $db->selectField( 'filelocks_exclusive', '1',
435 array( 'fle_key' => $keys ),
438 # Prospective writers that haven't yet updated filelocks_exclusive
439 # will recheck filelocks_shared after doing so and bail due to our entry.
440 } else { // writer locks
441 $encSession = $db->addQuotes( $this->session
);
442 # Bail if there are any existing writers...
443 # The may detect readers, but the safe check for them is below.
444 # Note: if two writers come at the same time, both bail :)
445 $blocked = $db->selectField( 'filelocks_shared', '1',
446 array( 'fls_key' => $keys, "fls_session != $encSession" ),
450 # Build up values for INSERT clause
452 foreach ( $keys as $key ) {
453 $data[] = array( 'fle_key' => $key );
455 # Block new readers/writers...
456 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
457 # Bail if there are any existing readers...
458 $blocked = $db->selectField( 'filelocks_shared', '1',
459 array( 'fls_key' => $keys, "fls_session != $encSession" ),