3 * Version of LockManager based on using DB table locks.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup LockManager
25 * Version of LockManager based on using DB table locks.
26 * This is meant for multi-wiki systems that may share files.
27 * All locks are blocking, so it might be useful to set a small
28 * lock-wait timeout via server config to curtail deadlocks.
30 * All lock requests for a resource, identified by a hash string, will map
31 * to one bucket. Each bucket maps to one or several peer DBs, each on their
32 * own server, all having the filelocks.sql tables (with row-level locking).
33 * A majority of peer DBs must agree for a lock to be acquired.
35 * Caching is used to avoid hitting servers that are down.
37 * @ingroup LockManager
40 class DBLockManager
extends LockManager
{
41 /** @var Array Map of DB names to server config */
42 protected $dbServers; // (DB name => server config array)
43 /** @var Array Map of bucket indexes to peer DB lists */
44 protected $dbsByBucket; // (bucket index => (ldb1, ldb2, ...))
46 protected $statusCache;
48 protected $lockExpiry; // integer number of seconds
49 protected $safeDelay; // integer number of seconds
51 protected $session = 0; // random integer
52 /** @var Array Map Database connections (DB name => Database) */
53 protected $conns = array();
56 * Construct a new instance from configuration.
58 * $config paramaters include:
59 * 'dbServers' : Associative array of DB names to server configuration.
60 * Configuration is an associative array that includes:
61 * 'host' - DB server name
63 * 'type' - DB type (mysql,postgres,...)
65 * 'password' - DB user password
66 * 'tablePrefix' - DB table prefix
67 * 'flags' - DB flags (see DatabaseBase)
68 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
69 * each having an odd-numbered list of DB names (peers) as values.
70 * Any DB named 'localDBMaster' will automatically use the DB master
71 * settings for this wiki (without the need for a dbServers entry).
72 * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
73 * This tells the DB server how long to wait before assuming
74 * connection failure and releasing all the locks for a session.
76 * @param Array $config
78 public function __construct( array $config ) {
79 parent
::__construct( $config );
81 $this->dbServers
= isset( $config['dbServers'] )
82 ?
$config['dbServers']
83 : array(); // likely just using 'localDBMaster'
84 // Sanitize dbsByBucket config to prevent PHP errors
85 $this->dbsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
86 $this->dbsByBucket
= array_values( $this->dbsByBucket
); // consecutive
88 if ( isset( $config['lockExpiry'] ) ) {
89 $this->lockExpiry
= $config['lockExpiry'];
91 $met = ini_get( 'max_execution_time' );
92 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
94 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
95 ?
60 // pick a safe-ish number to match DB timeout default
96 : $this->lockExpiry
; // cover worst case
98 foreach ( $this->dbsByBucket
as $bucket ) {
99 if ( count( $bucket ) > 1 ) {
100 // Tracks peers that couldn't be queried recently to avoid lengthy
101 // connection timeouts. This is useless if each bucket has one peer.
102 $this->statusCache
= wfGetMainCache();
108 for ( $i = 0; $i < 5; $i++
) {
109 $this->session
.= mt_rand( 0, 2147483647 );
111 $this->session
= wfBaseConvert( sha1( $this->session
), 16, 36, 31 );
115 * @see LockManager::doLock()
116 * @param $paths array
120 protected function doLock( array $paths, $type ) {
121 $status = Status
::newGood();
123 $pathsToLock = array();
124 // Get locks that need to be acquired (buckets => locks)...
125 foreach ( $paths as $path ) {
126 if ( isset( $this->locksHeld
[$path][$type] ) ) {
127 ++
$this->locksHeld
[$path][$type];
128 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
129 $this->locksHeld
[$path][$type] = 1;
131 $bucket = $this->getBucketFromKey( $path );
132 $pathsToLock[$bucket][] = $path;
136 $lockedPaths = array(); // files locked in this attempt
137 // Attempt to acquire these locks...
138 foreach ( $pathsToLock as $bucket => $paths ) {
139 // Try to acquire the locks for this bucket
140 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
141 if ( $res === 'cantacquire' ) {
142 // Resources already locked by another process.
143 // Abort and unlock everything we just locked.
144 foreach ( $paths as $path ) {
145 $status->fatal( 'lockmanager-fail-acquirelock', $path );
147 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
149 } elseif ( $res !== true ) {
150 // Couldn't contact any DBs for this bucket.
151 // Abort and unlock everything we just locked.
152 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
153 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
156 // Record these locks as active
157 foreach ( $paths as $path ) {
158 $this->locksHeld
[$path][$type] = 1; // locked
160 // Keep track of what locks were made in this attempt
161 $lockedPaths = array_merge( $lockedPaths, $paths );
168 * @see LockManager::doUnlock()
169 * @param $paths array
173 protected function doUnlock( array $paths, $type ) {
174 $status = Status
::newGood();
176 foreach ( $paths as $path ) {
177 if ( !isset( $this->locksHeld
[$path] ) ) {
178 $status->warning( 'lockmanager-notlocked', $path );
179 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
180 $status->warning( 'lockmanager-notlocked', $path );
182 --$this->locksHeld
[$path][$type];
183 if ( $this->locksHeld
[$path][$type] <= 0 ) {
184 unset( $this->locksHeld
[$path][$type] );
186 if ( !count( $this->locksHeld
[$path] ) ) {
187 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
192 // Reference count the locks held and COMMIT when zero
193 if ( !count( $this->locksHeld
) ) {
194 $status->merge( $this->finishLockTransactions() );
201 * Get a connection to a lock DB and acquire locks on $paths.
202 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
204 * @param $lockDb string
205 * @param $paths Array
206 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
207 * @return bool Resources able to be locked
210 protected function doLockingQuery( $lockDb, array $paths, $type ) {
211 if ( $type == self
::LOCK_EX
) { // writer locks
212 $db = $this->getConnection( $lockDb );
214 return false; // bad config
216 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
217 # Build up values for INSERT clause
219 foreach ( $keys as $key ) {
220 $data[] = array( 'fle_key' => $key );
222 # Wait on any existing writers and block new ones if we get in
223 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
229 * Attempt to acquire locks with the peers for a bucket.
230 * This should avoid throwing any exceptions.
232 * @param $bucket integer
233 * @param $paths Array List of resource keys to lock
234 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
235 * @return bool|string One of (true, 'cantacquire', 'dberrors')
237 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
238 $yesVotes = 0; // locks made on trustable DBs
239 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
240 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
241 // Get votes for each DB, in order, until we have enough...
242 foreach ( $this->dbsByBucket
[$bucket] as $lockDb ) {
243 // Check that DB is not *known* to be down
244 if ( $this->cacheCheckFailures( $lockDb ) ) {
246 // Attempt to acquire the lock on this DB
247 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
248 return 'cantacquire'; // vetoed; resource locked
250 ++
$yesVotes; // success for this peer
251 if ( $yesVotes >= $quorum ) {
252 return true; // lock obtained
254 } catch ( DBConnectionError
$e ) {
255 $this->cacheRecordFailure( $lockDb );
256 } catch ( DBError
$e ) {
257 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
258 return 'cantacquire'; // vetoed; resource locked
263 $votesNeeded = $quorum - $yesVotes;
264 if ( $votesNeeded > $votesLeft ) {
265 // In "trust cache" mode we don't have to meet the quorum
266 break; // short-circuit
269 // At this point, we must not have meet the quorum
270 return 'dberrors'; // not enough votes to ensure correctness
274 * Get (or reuse) a connection to a lock DB
276 * @param $lockDb string
277 * @return DatabaseBase
280 protected function getConnection( $lockDb ) {
281 if ( !isset( $this->conns
[$lockDb] ) ) {
283 if ( $lockDb === 'localDBMaster' ) {
284 $lb = wfGetLBFactory()->newMainLB();
285 $db = $lb->getConnection( DB_MASTER
);
286 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
287 $config = $this->dbServers
[$lockDb];
288 $db = DatabaseBase
::factory( $config['type'], $config );
291 return null; // config error?
293 $this->conns
[$lockDb] = $db;
294 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
295 # If the connection drops, try to avoid letting the DB rollback
296 # and release the locks before the file operations are finished.
297 # This won't handle the case of DB server restarts however.
299 if ( $this->lockExpiry
> 0 ) {
300 $options['connTimeout'] = $this->lockExpiry
;
302 $this->conns
[$lockDb]->setSessionOptions( $options );
303 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
305 if ( !$this->conns
[$lockDb]->trxLevel() ) {
306 $this->conns
[$lockDb]->begin( __METHOD__
); // start transaction
308 return $this->conns
[$lockDb];
312 * Do additional initialization for new lock DB connection
314 * @param $lockDb string
315 * @param $db DatabaseBase
319 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
322 * Commit all changes to lock-active databases.
323 * This should avoid throwing any exceptions.
327 protected function finishLockTransactions() {
328 $status = Status
::newGood();
329 foreach ( $this->conns
as $lockDb => $db ) {
330 if ( $db->trxLevel() ) { // in transaction
332 $db->rollback( __METHOD__
); // finish transaction and kill any rows
333 } catch ( DBError
$e ) {
334 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
342 * Check if the last DB error for $lockDb indicates
343 * that a requested resource was locked by another process.
344 * This should avoid throwing any exceptions.
346 * @param $lockDb string
349 protected function lastErrorIndicatesLocked( $lockDb ) {
350 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
351 $db = $this->conns
[$lockDb];
352 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
358 * Checks if the DB has not recently had connection/query errors.
359 * This just avoids wasting time on doomed connection attempts.
361 * @param $lockDb string
364 protected function cacheCheckFailures( $lockDb ) {
365 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
366 $path = $this->getMissKey( $lockDb );
367 $misses = $this->statusCache
->get( $path );
374 * Log a lock request failure to the cache
376 * @param $lockDb string
377 * @return bool Success
379 protected function cacheRecordFailure( $lockDb ) {
380 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
381 $path = $this->getMissKey( $lockDb );
382 $misses = $this->statusCache
->get( $path );
384 return $this->statusCache
->incr( $path );
386 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
393 * Get a cache key for recent query misses for a DB
395 * @param $lockDb string
398 protected function getMissKey( $lockDb ) {
399 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
403 * Get the bucket for resource path.
404 * This should avoid throwing any exceptions.
406 * @param $path string
409 protected function getBucketFromKey( $path ) {
410 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
411 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
415 * Make sure remaining locks get cleared for sanity
417 function __destruct() {
418 foreach ( $this->conns
as $lockDb => $db ) {
419 if ( $db->trxLevel() ) { // in transaction
421 $db->rollback( __METHOD__
); // finish transaction and kill any rows
422 } catch ( DBError
$e ) {
432 * MySQL version of DBLockManager that supports shared locks.
433 * All locks are non-blocking, which avoids deadlocks.
435 * @ingroup LockManager
437 class MySqlLockManager
extends DBLockManager
{
438 /** @var Array Mapping of lock types to the type actually used */
439 protected $lockTypeMap = array(
440 self
::LOCK_SH
=> self
::LOCK_SH
,
441 self
::LOCK_UW
=> self
::LOCK_SH
,
442 self
::LOCK_EX
=> self
::LOCK_EX
446 * @param $lockDb string
447 * @param $db DatabaseBase
449 protected function initConnection( $lockDb, DatabaseBase
$db ) {
450 # Let this transaction see lock rows from other transactions
451 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
455 * @param $lockDb string
456 * @param $paths array
460 protected function doLockingQuery( $lockDb, array $paths, $type ) {
461 $db = $this->getConnection( $lockDb );
465 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
466 # Build up values for INSERT clause
468 foreach ( $keys as $key ) {
469 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
471 # Block new writers...
472 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
473 # Actually do the locking queries...
474 if ( $type == self
::LOCK_SH
) { // reader locks
475 # Bail if there are any existing writers...
476 $blocked = $db->selectField( 'filelocks_exclusive', '1',
477 array( 'fle_key' => $keys ),
480 # Prospective writers that haven't yet updated filelocks_exclusive
481 # will recheck filelocks_shared after doing so and bail due to our entry.
482 } else { // writer locks
483 $encSession = $db->addQuotes( $this->session
);
484 # Bail if there are any existing writers...
485 # The may detect readers, but the safe check for them is below.
486 # Note: if two writers come at the same time, both bail :)
487 $blocked = $db->selectField( 'filelocks_shared', '1',
488 array( 'fls_key' => $keys, "fls_session != $encSession" ),
492 # Build up values for INSERT clause
494 foreach ( $keys as $key ) {
495 $data[] = array( 'fle_key' => $key );
497 # Block new readers/writers...
498 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
499 # Bail if there are any existing readers...
500 $blocked = $db->selectField( 'filelocks_shared', '1',
501 array( 'fls_key' => $keys, "fls_session != $encSession" ),