Pass __METHOD__ to DatabaseBase::begin(), DatabaseBase::commit() and DatabaseBase...
[lhc/web/wiklou.git] / includes / filerepo / backend / lockmanager / DBLockManager.php
1 <?php
2
3 /**
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.
8 *
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.
13 *
14 * Caching is used to avoid hitting servers that are down.
15 *
16 * @ingroup LockManager
17 * @since 1.19
18 */
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, ...))
24 /** @var BagOStuff */
25 protected $statusCache;
26
27 protected $lockExpiry; // integer number of seconds
28 protected $safeDelay; // integer number of seconds
29
30 protected $session = 0; // random integer
31 /** @var Array Map Database connections (DB name => Database) */
32 protected $conns = array();
33
34 /**
35 * Construct a new instance from configuration.
36 *
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
41 * 'dbname' - DB name
42 * 'type' - DB type (mysql,postgres,...)
43 * 'user' - DB user
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.
54 *
55 * @param Array $config
56 */
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
64
65 if ( isset( $config['lockExpiry'] ) ) {
66 $this->lockExpiry = $config['lockExpiry'];
67 } else {
68 $met = ini_get( 'max_execution_time' );
69 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
70 }
71 $this->safeDelay = ( $this->lockExpiry <= 0 )
72 ? 60 // pick a safe-ish number to match DB timeout default
73 : $this->lockExpiry; // cover worst case
74
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();
80 break;
81 }
82 }
83
84 $this->session = '';
85 for ( $i = 0; $i < 5; $i++ ) {
86 $this->session .= mt_rand( 0, 2147483647 );
87 }
88 $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
89 }
90
91 /**
92 * @see LockManager::doLock()
93 * @return Status
94 */
95 protected function doLock( array $paths, $type ) {
96 $status = Status::newGood();
97
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;
105 } else {
106 $bucket = $this->getBucketFromKey( $path );
107 $pathsToLock[$bucket][] = $path;
108 }
109 }
110
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 );
121 }
122 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
123 return $status;
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 ) );
129 return $status;
130 }
131 // Record these locks as active
132 foreach ( $paths as $path ) {
133 $this->locksHeld[$path][$type] = 1; // locked
134 }
135 // Keep track of what locks were made in this attempt
136 $lockedPaths = array_merge( $lockedPaths, $paths );
137 }
138
139 return $status;
140 }
141
142 /**
143 * @see LockManager::doUnlock()
144 * @return Status
145 */
146 protected function doUnlock( array $paths, $type ) {
147 $status = Status::newGood();
148
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 );
154 } else {
155 --$this->locksHeld[$path][$type];
156 if ( $this->locksHeld[$path][$type] <= 0 ) {
157 unset( $this->locksHeld[$path][$type] );
158 }
159 if ( !count( $this->locksHeld[$path] ) ) {
160 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
161 }
162 }
163 }
164
165 // Reference count the locks held and COMMIT when zero
166 if ( !count( $this->locksHeld ) ) {
167 $status->merge( $this->finishLockTransactions() );
168 }
169
170 return $status;
171 }
172
173 /**
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.
176 *
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
181 * @throws DBError
182 */
183 protected function doLockingQuery( $lockDb, array $paths, $type ) {
184 if ( $type == self::LOCK_EX ) { // writer locks
185 $db = $this->getConnection( $lockDb );
186 if ( !$db ) {
187 return false; // bad config
188 }
189 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
190 # Build up values for INSERT clause
191 $data = array();
192 foreach ( $keys as $key ) {
193 $data[] = array( 'fle_key' => $key );
194 }
195 # Wait on any existing writers and block new ones if we get in
196 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
197 }
198 return true;
199 }
200
201 /**
202 * Attempt to acquire locks with the peers for a bucket.
203 * This should avoid throwing any exceptions.
204 *
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')
209 */
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 ) ) {
218 try {
219 // Attempt to acquire the lock on this DB
220 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
221 return 'cantacquire'; // vetoed; resource locked
222 }
223 ++$yesVotes; // success for this peer
224 if ( $yesVotes >= $quorum ) {
225 return true; // lock obtained
226 }
227 } catch ( DBConnectionError $e ) {
228 $this->cacheRecordFailure( $lockDb );
229 } catch ( DBError $e ) {
230 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
231 return 'cantacquire'; // vetoed; resource locked
232 }
233 }
234 }
235 --$votesLeft;
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
240 }
241 }
242 // At this point, we must not have meet the quorum
243 return 'dberrors'; // not enough votes to ensure correctness
244 }
245
246 /**
247 * Get (or reuse) a connection to a lock DB
248 *
249 * @param $lockDb string
250 * @return DatabaseBase
251 * @throws DBError
252 */
253 protected function getConnection( $lockDb ) {
254 if ( !isset( $this->conns[$lockDb] ) ) {
255 $db = null;
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 );
262 }
263 if ( !$db ) {
264 return null; // config error?
265 }
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.
271 $options = array();
272 if ( $this->lockExpiry > 0 ) {
273 $options['connTimeout'] = $this->lockExpiry;
274 }
275 $this->conns[$lockDb]->setSessionOptions( $options );
276 $this->initConnection( $lockDb, $this->conns[$lockDb] );
277 }
278 if ( !$this->conns[$lockDb]->trxLevel() ) {
279 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
280 }
281 return $this->conns[$lockDb];
282 }
283
284 /**
285 * Do additional initialization for new lock DB connection
286 *
287 * @param $lockDb string
288 * @param $db DatabaseBase
289 * @return void
290 * @throws DBError
291 */
292 protected function initConnection( $lockDb, DatabaseBase $db ) {}
293
294 /**
295 * Commit all changes to lock-active databases.
296 * This should avoid throwing any exceptions.
297 *
298 * @return Status
299 */
300 protected function finishLockTransactions() {
301 $status = Status::newGood();
302 foreach ( $this->conns as $lockDb => $db ) {
303 if ( $db->trxLevel() ) { // in transaction
304 try {
305 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
306 } catch ( DBError $e ) {
307 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
308 }
309 }
310 }
311 return $status;
312 }
313
314 /**
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.
318 *
319 * @param $lockDb string
320 * @return bool
321 */
322 protected function lastErrorIndicatesLocked( $lockDb ) {
323 if ( isset( $this->conns[$lockDb] ) ) { // sanity
324 $db = $this->conns[$lockDb];
325 return ( $db->wasDeadlock() || $db->wasLockTimeout() );
326 }
327 return false;
328 }
329
330 /**
331 * Checks if the DB has not recently had connection/query errors.
332 * This just avoids wasting time on doomed connection attempts.
333 *
334 * @param $lockDb string
335 * @return bool
336 */
337 protected function cacheCheckFailures( $lockDb ) {
338 if ( $this->statusCache && $this->safeDelay > 0 ) {
339 $path = $this->getMissKey( $lockDb );
340 $misses = $this->statusCache->get( $path );
341 return !$misses;
342 }
343 return true;
344 }
345
346 /**
347 * Log a lock request failure to the cache
348 *
349 * @param $lockDb string
350 * @return bool Success
351 */
352 protected function cacheRecordFailure( $lockDb ) {
353 if ( $this->statusCache && $this->safeDelay > 0 ) {
354 $path = $this->getMissKey( $lockDb );
355 $misses = $this->statusCache->get( $path );
356 if ( $misses ) {
357 return $this->statusCache->incr( $path );
358 } else {
359 return $this->statusCache->add( $path, 1, $this->safeDelay );
360 }
361 }
362 return true;
363 }
364
365 /**
366 * Get a cache key for recent query misses for a DB
367 *
368 * @param $lockDb string
369 * @return string
370 */
371 protected function getMissKey( $lockDb ) {
372 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
373 }
374
375 /**
376 * Get the bucket for resource path.
377 * This should avoid throwing any exceptions.
378 *
379 * @param $path string
380 * @return integer
381 */
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 );
385 }
386
387 /**
388 * Make sure remaining locks get cleared for sanity
389 */
390 function __destruct() {
391 foreach ( $this->conns as $lockDb => $db ) {
392 if ( $db->trxLevel() ) { // in transaction
393 try {
394 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
395 } catch ( DBError $e ) {
396 // oh well
397 }
398 }
399 $db->close();
400 }
401 }
402 }
403
404 /**
405 * MySQL version of DBLockManager that supports shared locks.
406 * All locks are non-blocking, which avoids deadlocks.
407 *
408 * @ingroup LockManager
409 */
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
416 );
417
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;" );
421 }
422
423 protected function doLockingQuery( $lockDb, array $paths, $type ) {
424 $db = $this->getConnection( $lockDb );
425 if ( !$db ) {
426 return false;
427 }
428 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
429 # Build up values for INSERT clause
430 $data = array();
431 foreach ( $keys as $key ) {
432 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
433 }
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 ),
441 __METHOD__
442 );
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" ),
452 __METHOD__
453 );
454 if ( !$blocked ) {
455 # Build up values for INSERT clause
456 $data = array();
457 foreach ( $keys as $key ) {
458 $data[] = array( 'fle_key' => $key );
459 }
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" ),
465 __METHOD__
466 );
467 }
468 }
469 return !$blocked;
470 }
471 }