Merge "Adding tests for dumps"
[lhc/web/wiklou.git] / includes / filerepo / backend / lockmanager / DBLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using DB table locks.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup LockManager
22 */
23
24 /**
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.
29 *
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.
34 *
35 * Caching is used to avoid hitting servers that are down.
36 *
37 * @ingroup LockManager
38 * @since 1.19
39 */
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, ...))
45 /** @var BagOStuff */
46 protected $statusCache;
47
48 protected $lockExpiry; // integer number of seconds
49 protected $safeDelay; // integer number of seconds
50
51 protected $session = 0; // random integer
52 /** @var Array Map Database connections (DB name => Database) */
53 protected $conns = array();
54
55 /**
56 * Construct a new instance from configuration.
57 *
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
62 * 'dbname' - DB name
63 * 'type' - DB type (mysql,postgres,...)
64 * 'user' - DB user
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.
75 *
76 * @param Array $config
77 */
78 public function __construct( array $config ) {
79 parent::__construct( $config );
80
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
87
88 if ( isset( $config['lockExpiry'] ) ) {
89 $this->lockExpiry = $config['lockExpiry'];
90 } else {
91 $met = ini_get( 'max_execution_time' );
92 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
93 }
94 $this->safeDelay = ( $this->lockExpiry <= 0 )
95 ? 60 // pick a safe-ish number to match DB timeout default
96 : $this->lockExpiry; // cover worst case
97
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();
103 break;
104 }
105 }
106
107 $this->session = '';
108 for ( $i = 0; $i < 5; $i++ ) {
109 $this->session .= mt_rand( 0, 2147483647 );
110 }
111 $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
112 }
113
114 /**
115 * @see LockManager::doLock()
116 * @return Status
117 */
118 protected function doLock( array $paths, $type ) {
119 $status = Status::newGood();
120
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;
128 } else {
129 $bucket = $this->getBucketFromKey( $path );
130 $pathsToLock[$bucket][] = $path;
131 }
132 }
133
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 );
144 }
145 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
146 return $status;
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 ) );
152 return $status;
153 }
154 // Record these locks as active
155 foreach ( $paths as $path ) {
156 $this->locksHeld[$path][$type] = 1; // locked
157 }
158 // Keep track of what locks were made in this attempt
159 $lockedPaths = array_merge( $lockedPaths, $paths );
160 }
161
162 return $status;
163 }
164
165 /**
166 * @see LockManager::doUnlock()
167 * @return Status
168 */
169 protected function doUnlock( array $paths, $type ) {
170 $status = Status::newGood();
171
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 );
177 } else {
178 --$this->locksHeld[$path][$type];
179 if ( $this->locksHeld[$path][$type] <= 0 ) {
180 unset( $this->locksHeld[$path][$type] );
181 }
182 if ( !count( $this->locksHeld[$path] ) ) {
183 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
184 }
185 }
186 }
187
188 // Reference count the locks held and COMMIT when zero
189 if ( !count( $this->locksHeld ) ) {
190 $status->merge( $this->finishLockTransactions() );
191 }
192
193 return $status;
194 }
195
196 /**
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.
199 *
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
204 * @throws DBError
205 */
206 protected function doLockingQuery( $lockDb, array $paths, $type ) {
207 if ( $type == self::LOCK_EX ) { // writer locks
208 $db = $this->getConnection( $lockDb );
209 if ( !$db ) {
210 return false; // bad config
211 }
212 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
213 # Build up values for INSERT clause
214 $data = array();
215 foreach ( $keys as $key ) {
216 $data[] = array( 'fle_key' => $key );
217 }
218 # Wait on any existing writers and block new ones if we get in
219 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
220 }
221 return true;
222 }
223
224 /**
225 * Attempt to acquire locks with the peers for a bucket.
226 * This should avoid throwing any exceptions.
227 *
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')
232 */
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 ) ) {
241 try {
242 // Attempt to acquire the lock on this DB
243 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
244 return 'cantacquire'; // vetoed; resource locked
245 }
246 ++$yesVotes; // success for this peer
247 if ( $yesVotes >= $quorum ) {
248 return true; // lock obtained
249 }
250 } catch ( DBConnectionError $e ) {
251 $this->cacheRecordFailure( $lockDb );
252 } catch ( DBError $e ) {
253 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
254 return 'cantacquire'; // vetoed; resource locked
255 }
256 }
257 }
258 --$votesLeft;
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
263 }
264 }
265 // At this point, we must not have meet the quorum
266 return 'dberrors'; // not enough votes to ensure correctness
267 }
268
269 /**
270 * Get (or reuse) a connection to a lock DB
271 *
272 * @param $lockDb string
273 * @return DatabaseBase
274 * @throws DBError
275 */
276 protected function getConnection( $lockDb ) {
277 if ( !isset( $this->conns[$lockDb] ) ) {
278 $db = null;
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 );
285 }
286 if ( !$db ) {
287 return null; // config error?
288 }
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.
294 $options = array();
295 if ( $this->lockExpiry > 0 ) {
296 $options['connTimeout'] = $this->lockExpiry;
297 }
298 $this->conns[$lockDb]->setSessionOptions( $options );
299 $this->initConnection( $lockDb, $this->conns[$lockDb] );
300 }
301 if ( !$this->conns[$lockDb]->trxLevel() ) {
302 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
303 }
304 return $this->conns[$lockDb];
305 }
306
307 /**
308 * Do additional initialization for new lock DB connection
309 *
310 * @param $lockDb string
311 * @param $db DatabaseBase
312 * @return void
313 * @throws DBError
314 */
315 protected function initConnection( $lockDb, DatabaseBase $db ) {}
316
317 /**
318 * Commit all changes to lock-active databases.
319 * This should avoid throwing any exceptions.
320 *
321 * @return Status
322 */
323 protected function finishLockTransactions() {
324 $status = Status::newGood();
325 foreach ( $this->conns as $lockDb => $db ) {
326 if ( $db->trxLevel() ) { // in transaction
327 try {
328 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
329 } catch ( DBError $e ) {
330 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
331 }
332 }
333 }
334 return $status;
335 }
336
337 /**
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.
341 *
342 * @param $lockDb string
343 * @return bool
344 */
345 protected function lastErrorIndicatesLocked( $lockDb ) {
346 if ( isset( $this->conns[$lockDb] ) ) { // sanity
347 $db = $this->conns[$lockDb];
348 return ( $db->wasDeadlock() || $db->wasLockTimeout() );
349 }
350 return false;
351 }
352
353 /**
354 * Checks if the DB has not recently had connection/query errors.
355 * This just avoids wasting time on doomed connection attempts.
356 *
357 * @param $lockDb string
358 * @return bool
359 */
360 protected function cacheCheckFailures( $lockDb ) {
361 if ( $this->statusCache && $this->safeDelay > 0 ) {
362 $path = $this->getMissKey( $lockDb );
363 $misses = $this->statusCache->get( $path );
364 return !$misses;
365 }
366 return true;
367 }
368
369 /**
370 * Log a lock request failure to the cache
371 *
372 * @param $lockDb string
373 * @return bool Success
374 */
375 protected function cacheRecordFailure( $lockDb ) {
376 if ( $this->statusCache && $this->safeDelay > 0 ) {
377 $path = $this->getMissKey( $lockDb );
378 $misses = $this->statusCache->get( $path );
379 if ( $misses ) {
380 return $this->statusCache->incr( $path );
381 } else {
382 return $this->statusCache->add( $path, 1, $this->safeDelay );
383 }
384 }
385 return true;
386 }
387
388 /**
389 * Get a cache key for recent query misses for a DB
390 *
391 * @param $lockDb string
392 * @return string
393 */
394 protected function getMissKey( $lockDb ) {
395 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
396 }
397
398 /**
399 * Get the bucket for resource path.
400 * This should avoid throwing any exceptions.
401 *
402 * @param $path string
403 * @return integer
404 */
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 );
408 }
409
410 /**
411 * Make sure remaining locks get cleared for sanity
412 */
413 function __destruct() {
414 foreach ( $this->conns as $lockDb => $db ) {
415 if ( $db->trxLevel() ) { // in transaction
416 try {
417 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
418 } catch ( DBError $e ) {
419 // oh well
420 }
421 }
422 $db->close();
423 }
424 }
425 }
426
427 /**
428 * MySQL version of DBLockManager that supports shared locks.
429 * All locks are non-blocking, which avoids deadlocks.
430 *
431 * @ingroup LockManager
432 */
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
439 );
440
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;" );
444 }
445
446 protected function doLockingQuery( $lockDb, array $paths, $type ) {
447 $db = $this->getConnection( $lockDb );
448 if ( !$db ) {
449 return false;
450 }
451 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
452 # Build up values for INSERT clause
453 $data = array();
454 foreach ( $keys as $key ) {
455 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
456 }
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 ),
464 __METHOD__
465 );
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" ),
475 __METHOD__
476 );
477 if ( !$blocked ) {
478 # Build up values for INSERT clause
479 $data = array();
480 foreach ( $keys as $key ) {
481 $data[] = array( 'fle_key' => $key );
482 }
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" ),
488 __METHOD__
489 );
490 }
491 }
492 return !$blocked;
493 }
494 }