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()
118 protected function doLock( array $paths, $type ) {
119 $status = Status
::newGood();
121 $pathsToLock = array();
122 // Get locks that need to be acquired (buckets => locks)...
123 foreach ( $paths as $path ) {
124 if ( isset( $this->locksHeld
[$path][$type] ) ) {
125 ++
$this->locksHeld
[$path][$type];
126 } elseif ( isset( $this->locksHeld
[$path][self
::LOCK_EX
] ) ) {
127 $this->locksHeld
[$path][$type] = 1;
129 $bucket = $this->getBucketFromKey( $path );
130 $pathsToLock[$bucket][] = $path;
134 $lockedPaths = array(); // files locked in this attempt
135 // Attempt to acquire these locks...
136 foreach ( $pathsToLock as $bucket => $paths ) {
137 // Try to acquire the locks for this bucket
138 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
139 if ( $res === 'cantacquire' ) {
140 // Resources already locked by another process.
141 // Abort and unlock everything we just locked.
142 foreach ( $paths as $path ) {
143 $status->fatal( 'lockmanager-fail-acquirelock', $path );
145 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
147 } elseif ( $res !== true ) {
148 // Couldn't contact any DBs for this bucket.
149 // Abort and unlock everything we just locked.
150 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
151 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
154 // Record these locks as active
155 foreach ( $paths as $path ) {
156 $this->locksHeld
[$path][$type] = 1; // locked
158 // Keep track of what locks were made in this attempt
159 $lockedPaths = array_merge( $lockedPaths, $paths );
166 * @see LockManager::doUnlock()
169 protected function doUnlock( array $paths, $type ) {
170 $status = Status
::newGood();
172 foreach ( $paths as $path ) {
173 if ( !isset( $this->locksHeld
[$path] ) ) {
174 $status->warning( 'lockmanager-notlocked', $path );
175 } elseif ( !isset( $this->locksHeld
[$path][$type] ) ) {
176 $status->warning( 'lockmanager-notlocked', $path );
178 --$this->locksHeld
[$path][$type];
179 if ( $this->locksHeld
[$path][$type] <= 0 ) {
180 unset( $this->locksHeld
[$path][$type] );
182 if ( !count( $this->locksHeld
[$path] ) ) {
183 unset( $this->locksHeld
[$path] ); // no SH or EX locks left for key
188 // Reference count the locks held and COMMIT when zero
189 if ( !count( $this->locksHeld
) ) {
190 $status->merge( $this->finishLockTransactions() );
197 * Get a connection to a lock DB and acquire locks on $paths.
198 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
200 * @param $lockDb string
201 * @param $paths Array
202 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
203 * @return bool Resources able to be locked
206 protected function doLockingQuery( $lockDb, array $paths, $type ) {
207 if ( $type == self
::LOCK_EX
) { // writer locks
208 $db = $this->getConnection( $lockDb );
210 return false; // bad config
212 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
213 # Build up values for INSERT clause
215 foreach ( $keys as $key ) {
216 $data[] = array( 'fle_key' => $key );
218 # Wait on any existing writers and block new ones if we get in
219 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
225 * Attempt to acquire locks with the peers for a bucket.
226 * This should avoid throwing any exceptions.
228 * @param $bucket integer
229 * @param $paths Array List of resource keys to lock
230 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
231 * @return bool|string One of (true, 'cantacquire', 'dberrors')
233 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
234 $yesVotes = 0; // locks made on trustable DBs
235 $votesLeft = count( $this->dbsByBucket
[$bucket] ); // remaining DBs
236 $quorum = floor( $votesLeft/2 +
1 ); // simple majority
237 // Get votes for each DB, in order, until we have enough...
238 foreach ( $this->dbsByBucket
[$bucket] as $lockDb ) {
239 // Check that DB is not *known* to be down
240 if ( $this->cacheCheckFailures( $lockDb ) ) {
242 // Attempt to acquire the lock on this DB
243 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
244 return 'cantacquire'; // vetoed; resource locked
246 ++
$yesVotes; // success for this peer
247 if ( $yesVotes >= $quorum ) {
248 return true; // lock obtained
250 } catch ( DBConnectionError
$e ) {
251 $this->cacheRecordFailure( $lockDb );
252 } catch ( DBError
$e ) {
253 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
254 return 'cantacquire'; // vetoed; resource locked
259 $votesNeeded = $quorum - $yesVotes;
260 if ( $votesNeeded > $votesLeft ) {
261 // In "trust cache" mode we don't have to meet the quorum
262 break; // short-circuit
265 // At this point, we must not have meet the quorum
266 return 'dberrors'; // not enough votes to ensure correctness
270 * Get (or reuse) a connection to a lock DB
272 * @param $lockDb string
273 * @return DatabaseBase
276 protected function getConnection( $lockDb ) {
277 if ( !isset( $this->conns
[$lockDb] ) ) {
279 if ( $lockDb === 'localDBMaster' ) {
280 $lb = wfGetLBFactory()->newMainLB();
281 $db = $lb->getConnection( DB_MASTER
);
282 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
283 $config = $this->dbServers
[$lockDb];
284 $db = DatabaseBase
::factory( $config['type'], $config );
287 return null; // config error?
289 $this->conns
[$lockDb] = $db;
290 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
291 # If the connection drops, try to avoid letting the DB rollback
292 # and release the locks before the file operations are finished.
293 # This won't handle the case of DB server restarts however.
295 if ( $this->lockExpiry
> 0 ) {
296 $options['connTimeout'] = $this->lockExpiry
;
298 $this->conns
[$lockDb]->setSessionOptions( $options );
299 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
301 if ( !$this->conns
[$lockDb]->trxLevel() ) {
302 $this->conns
[$lockDb]->begin( __METHOD__
); // start transaction
304 return $this->conns
[$lockDb];
308 * Do additional initialization for new lock DB connection
310 * @param $lockDb string
311 * @param $db DatabaseBase
315 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
318 * Commit all changes to lock-active databases.
319 * This should avoid throwing any exceptions.
323 protected function finishLockTransactions() {
324 $status = Status
::newGood();
325 foreach ( $this->conns
as $lockDb => $db ) {
326 if ( $db->trxLevel() ) { // in transaction
328 $db->rollback( __METHOD__
); // finish transaction and kill any rows
329 } catch ( DBError
$e ) {
330 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
338 * Check if the last DB error for $lockDb indicates
339 * that a requested resource was locked by another process.
340 * This should avoid throwing any exceptions.
342 * @param $lockDb string
345 protected function lastErrorIndicatesLocked( $lockDb ) {
346 if ( isset( $this->conns
[$lockDb] ) ) { // sanity
347 $db = $this->conns
[$lockDb];
348 return ( $db->wasDeadlock() ||
$db->wasLockTimeout() );
354 * Checks if the DB has not recently had connection/query errors.
355 * This just avoids wasting time on doomed connection attempts.
357 * @param $lockDb string
360 protected function cacheCheckFailures( $lockDb ) {
361 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
362 $path = $this->getMissKey( $lockDb );
363 $misses = $this->statusCache
->get( $path );
370 * Log a lock request failure to the cache
372 * @param $lockDb string
373 * @return bool Success
375 protected function cacheRecordFailure( $lockDb ) {
376 if ( $this->statusCache
&& $this->safeDelay
> 0 ) {
377 $path = $this->getMissKey( $lockDb );
378 $misses = $this->statusCache
->get( $path );
380 return $this->statusCache
->incr( $path );
382 return $this->statusCache
->add( $path, 1, $this->safeDelay
);
389 * Get a cache key for recent query misses for a DB
391 * @param $lockDb string
394 protected function getMissKey( $lockDb ) {
395 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
399 * Get the bucket for resource path.
400 * This should avoid throwing any exceptions.
402 * @param $path string
405 protected function getBucketFromKey( $path ) {
406 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
407 return intval( base_convert( $prefix, 16, 10 ) ) %
count( $this->dbsByBucket
);
411 * Make sure remaining locks get cleared for sanity
413 function __destruct() {
414 foreach ( $this->conns
as $lockDb => $db ) {
415 if ( $db->trxLevel() ) { // in transaction
417 $db->rollback( __METHOD__
); // finish transaction and kill any rows
418 } catch ( DBError
$e ) {
428 * MySQL version of DBLockManager that supports shared locks.
429 * All locks are non-blocking, which avoids deadlocks.
431 * @ingroup LockManager
433 class MySqlLockManager
extends DBLockManager
{
434 /** @var Array Mapping of lock types to the type actually used */
435 protected $lockTypeMap = array(
436 self
::LOCK_SH
=> self
::LOCK_SH
,
437 self
::LOCK_UW
=> self
::LOCK_SH
,
438 self
::LOCK_EX
=> self
::LOCK_EX
441 protected function initConnection( $lockDb, DatabaseBase
$db ) {
442 # Let this transaction see lock rows from other transactions
443 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
446 protected function doLockingQuery( $lockDb, array $paths, $type ) {
447 $db = $this->getConnection( $lockDb );
451 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
452 # Build up values for INSERT clause
454 foreach ( $keys as $key ) {
455 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
457 # Block new writers...
458 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
459 # Actually do the locking queries...
460 if ( $type == self
::LOCK_SH
) { // reader locks
461 # Bail if there are any existing writers...
462 $blocked = $db->selectField( 'filelocks_exclusive', '1',
463 array( 'fle_key' => $keys ),
466 # Prospective writers that haven't yet updated filelocks_exclusive
467 # will recheck filelocks_shared after doing so and bail due to our entry.
468 } else { // writer locks
469 $encSession = $db->addQuotes( $this->session
);
470 # Bail if there are any existing writers...
471 # The may detect readers, but the safe check for them is below.
472 # Note: if two writers come at the same time, both bail :)
473 $blocked = $db->selectField( 'filelocks_shared', '1',
474 array( 'fls_key' => $keys, "fls_session != $encSession" ),
478 # Build up values for INSERT clause
480 foreach ( $keys as $key ) {
481 $data[] = array( 'fle_key' => $key );
483 # Block new readers/writers...
484 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
485 # Bail if there are any existing readers...
486 $blocked = $db->selectField( 'filelocks_shared', '1',
487 array( 'fls_key' => $keys, "fls_session != $encSession" ),