Merge branch 'master' into Wikidata
[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 parent::__construct( $config );
59
60 $this->dbServers = isset( $config['dbServers'] )
61 ? $config['dbServers']
62 : array(); // likely just using 'localDBMaster'
63 // Sanitize dbsByBucket config to prevent PHP errors
64 $this->dbsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
65 $this->dbsByBucket = array_values( $this->dbsByBucket ); // consecutive
66
67 if ( isset( $config['lockExpiry'] ) ) {
68 $this->lockExpiry = $config['lockExpiry'];
69 } else {
70 $met = ini_get( 'max_execution_time' );
71 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
72 }
73 $this->safeDelay = ( $this->lockExpiry <= 0 )
74 ? 60 // pick a safe-ish number to match DB timeout default
75 : $this->lockExpiry; // cover worst case
76
77 foreach ( $this->dbsByBucket as $bucket ) {
78 if ( count( $bucket ) > 1 ) {
79 // Tracks peers that couldn't be queried recently to avoid lengthy
80 // connection timeouts. This is useless if each bucket has one peer.
81 $this->statusCache = wfGetMainCache();
82 break;
83 }
84 }
85
86 $this->session = '';
87 for ( $i = 0; $i < 5; $i++ ) {
88 $this->session .= mt_rand( 0, 2147483647 );
89 }
90 $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
91 }
92
93 /**
94 * @see LockManager::doLock()
95 * @return Status
96 */
97 protected function doLock( array $paths, $type ) {
98 $status = Status::newGood();
99
100 $pathsToLock = array();
101 // Get locks that need to be acquired (buckets => locks)...
102 foreach ( $paths as $path ) {
103 if ( isset( $this->locksHeld[$path][$type] ) ) {
104 ++$this->locksHeld[$path][$type];
105 } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
106 $this->locksHeld[$path][$type] = 1;
107 } else {
108 $bucket = $this->getBucketFromKey( $path );
109 $pathsToLock[$bucket][] = $path;
110 }
111 }
112
113 $lockedPaths = array(); // files locked in this attempt
114 // Attempt to acquire these locks...
115 foreach ( $pathsToLock as $bucket => $paths ) {
116 // Try to acquire the locks for this bucket
117 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
118 if ( $res === 'cantacquire' ) {
119 // Resources already locked by another process.
120 // Abort and unlock everything we just locked.
121 foreach ( $paths as $path ) {
122 $status->fatal( 'lockmanager-fail-acquirelock', $path );
123 }
124 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
125 return $status;
126 } elseif ( $res !== true ) {
127 // Couldn't contact any DBs for this bucket.
128 // Abort and unlock everything we just locked.
129 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
130 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
131 return $status;
132 }
133 // Record these locks as active
134 foreach ( $paths as $path ) {
135 $this->locksHeld[$path][$type] = 1; // locked
136 }
137 // Keep track of what locks were made in this attempt
138 $lockedPaths = array_merge( $lockedPaths, $paths );
139 }
140
141 return $status;
142 }
143
144 /**
145 * @see LockManager::doUnlock()
146 * @return Status
147 */
148 protected function doUnlock( array $paths, $type ) {
149 $status = Status::newGood();
150
151 foreach ( $paths as $path ) {
152 if ( !isset( $this->locksHeld[$path] ) ) {
153 $status->warning( 'lockmanager-notlocked', $path );
154 } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
155 $status->warning( 'lockmanager-notlocked', $path );
156 } else {
157 --$this->locksHeld[$path][$type];
158 if ( $this->locksHeld[$path][$type] <= 0 ) {
159 unset( $this->locksHeld[$path][$type] );
160 }
161 if ( !count( $this->locksHeld[$path] ) ) {
162 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
163 }
164 }
165 }
166
167 // Reference count the locks held and COMMIT when zero
168 if ( !count( $this->locksHeld ) ) {
169 $status->merge( $this->finishLockTransactions() );
170 }
171
172 return $status;
173 }
174
175 /**
176 * Get a connection to a lock DB and acquire locks on $paths.
177 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
178 *
179 * @param $lockDb string
180 * @param $paths Array
181 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
182 * @return bool Resources able to be locked
183 * @throws DBError
184 */
185 protected function doLockingQuery( $lockDb, array $paths, $type ) {
186 if ( $type == self::LOCK_EX ) { // writer locks
187 $db = $this->getConnection( $lockDb );
188 if ( !$db ) {
189 return false; // bad config
190 }
191 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
192 # Build up values for INSERT clause
193 $data = array();
194 foreach ( $keys as $key ) {
195 $data[] = array( 'fle_key' => $key );
196 }
197 # Wait on any existing writers and block new ones if we get in
198 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
199 }
200 return true;
201 }
202
203 /**
204 * Attempt to acquire locks with the peers for a bucket.
205 * This should avoid throwing any exceptions.
206 *
207 * @param $bucket integer
208 * @param $paths Array List of resource keys to lock
209 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
210 * @return bool|string One of (true, 'cantacquire', 'dberrors')
211 */
212 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
213 $yesVotes = 0; // locks made on trustable DBs
214 $votesLeft = count( $this->dbsByBucket[$bucket] ); // remaining DBs
215 $quorum = floor( $votesLeft/2 + 1 ); // simple majority
216 // Get votes for each DB, in order, until we have enough...
217 foreach ( $this->dbsByBucket[$bucket] as $lockDb ) {
218 // Check that DB is not *known* to be down
219 if ( $this->cacheCheckFailures( $lockDb ) ) {
220 try {
221 // Attempt to acquire the lock on this DB
222 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
223 return 'cantacquire'; // vetoed; resource locked
224 }
225 ++$yesVotes; // success for this peer
226 if ( $yesVotes >= $quorum ) {
227 return true; // lock obtained
228 }
229 } catch ( DBConnectionError $e ) {
230 $this->cacheRecordFailure( $lockDb );
231 } catch ( DBError $e ) {
232 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
233 return 'cantacquire'; // vetoed; resource locked
234 }
235 }
236 }
237 --$votesLeft;
238 $votesNeeded = $quorum - $yesVotes;
239 if ( $votesNeeded > $votesLeft ) {
240 // In "trust cache" mode we don't have to meet the quorum
241 break; // short-circuit
242 }
243 }
244 // At this point, we must not have meet the quorum
245 return 'dberrors'; // not enough votes to ensure correctness
246 }
247
248 /**
249 * Get (or reuse) a connection to a lock DB
250 *
251 * @param $lockDb string
252 * @return DatabaseBase
253 * @throws DBError
254 */
255 protected function getConnection( $lockDb ) {
256 if ( !isset( $this->conns[$lockDb] ) ) {
257 $db = null;
258 if ( $lockDb === 'localDBMaster' ) {
259 $lb = wfGetLBFactory()->newMainLB();
260 $db = $lb->getConnection( DB_MASTER );
261 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
262 $config = $this->dbServers[$lockDb];
263 $db = DatabaseBase::factory( $config['type'], $config );
264 }
265 if ( !$db ) {
266 return null; // config error?
267 }
268 $this->conns[$lockDb] = $db;
269 $this->conns[$lockDb]->clearFlag( DBO_TRX );
270 # If the connection drops, try to avoid letting the DB rollback
271 # and release the locks before the file operations are finished.
272 # This won't handle the case of DB server restarts however.
273 $options = array();
274 if ( $this->lockExpiry > 0 ) {
275 $options['connTimeout'] = $this->lockExpiry;
276 }
277 $this->conns[$lockDb]->setSessionOptions( $options );
278 $this->initConnection( $lockDb, $this->conns[$lockDb] );
279 }
280 if ( !$this->conns[$lockDb]->trxLevel() ) {
281 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
282 }
283 return $this->conns[$lockDb];
284 }
285
286 /**
287 * Do additional initialization for new lock DB connection
288 *
289 * @param $lockDb string
290 * @param $db DatabaseBase
291 * @return void
292 * @throws DBError
293 */
294 protected function initConnection( $lockDb, DatabaseBase $db ) {}
295
296 /**
297 * Commit all changes to lock-active databases.
298 * This should avoid throwing any exceptions.
299 *
300 * @return Status
301 */
302 protected function finishLockTransactions() {
303 $status = Status::newGood();
304 foreach ( $this->conns as $lockDb => $db ) {
305 if ( $db->trxLevel() ) { // in transaction
306 try {
307 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
308 } catch ( DBError $e ) {
309 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
310 }
311 }
312 }
313 return $status;
314 }
315
316 /**
317 * Check if the last DB error for $lockDb indicates
318 * that a requested resource was locked by another process.
319 * This should avoid throwing any exceptions.
320 *
321 * @param $lockDb string
322 * @return bool
323 */
324 protected function lastErrorIndicatesLocked( $lockDb ) {
325 if ( isset( $this->conns[$lockDb] ) ) { // sanity
326 $db = $this->conns[$lockDb];
327 return ( $db->wasDeadlock() || $db->wasLockTimeout() );
328 }
329 return false;
330 }
331
332 /**
333 * Checks if the DB has not recently had connection/query errors.
334 * This just avoids wasting time on doomed connection attempts.
335 *
336 * @param $lockDb string
337 * @return bool
338 */
339 protected function cacheCheckFailures( $lockDb ) {
340 if ( $this->statusCache && $this->safeDelay > 0 ) {
341 $path = $this->getMissKey( $lockDb );
342 $misses = $this->statusCache->get( $path );
343 return !$misses;
344 }
345 return true;
346 }
347
348 /**
349 * Log a lock request failure to the cache
350 *
351 * @param $lockDb string
352 * @return bool Success
353 */
354 protected function cacheRecordFailure( $lockDb ) {
355 if ( $this->statusCache && $this->safeDelay > 0 ) {
356 $path = $this->getMissKey( $lockDb );
357 $misses = $this->statusCache->get( $path );
358 if ( $misses ) {
359 return $this->statusCache->incr( $path );
360 } else {
361 return $this->statusCache->add( $path, 1, $this->safeDelay );
362 }
363 }
364 return true;
365 }
366
367 /**
368 * Get a cache key for recent query misses for a DB
369 *
370 * @param $lockDb string
371 * @return string
372 */
373 protected function getMissKey( $lockDb ) {
374 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
375 }
376
377 /**
378 * Get the bucket for resource path.
379 * This should avoid throwing any exceptions.
380 *
381 * @param $path string
382 * @return integer
383 */
384 protected function getBucketFromKey( $path ) {
385 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
386 return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->dbsByBucket );
387 }
388
389 /**
390 * Make sure remaining locks get cleared for sanity
391 */
392 function __destruct() {
393 foreach ( $this->conns as $lockDb => $db ) {
394 if ( $db->trxLevel() ) { // in transaction
395 try {
396 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
397 } catch ( DBError $e ) {
398 // oh well
399 }
400 }
401 $db->close();
402 }
403 }
404 }
405
406 /**
407 * MySQL version of DBLockManager that supports shared locks.
408 * All locks are non-blocking, which avoids deadlocks.
409 *
410 * @ingroup LockManager
411 */
412 class MySqlLockManager extends DBLockManager {
413 /** @var Array Mapping of lock types to the type actually used */
414 protected $lockTypeMap = array(
415 self::LOCK_SH => self::LOCK_SH,
416 self::LOCK_UW => self::LOCK_SH,
417 self::LOCK_EX => self::LOCK_EX
418 );
419
420 protected function initConnection( $lockDb, DatabaseBase $db ) {
421 # Let this transaction see lock rows from other transactions
422 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
423 }
424
425 protected function doLockingQuery( $lockDb, array $paths, $type ) {
426 $db = $this->getConnection( $lockDb );
427 if ( !$db ) {
428 return false;
429 }
430 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
431 # Build up values for INSERT clause
432 $data = array();
433 foreach ( $keys as $key ) {
434 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
435 }
436 # Block new writers...
437 $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
438 # Actually do the locking queries...
439 if ( $type == self::LOCK_SH ) { // reader locks
440 # Bail if there are any existing writers...
441 $blocked = $db->selectField( 'filelocks_exclusive', '1',
442 array( 'fle_key' => $keys ),
443 __METHOD__
444 );
445 # Prospective writers that haven't yet updated filelocks_exclusive
446 # will recheck filelocks_shared after doing so and bail due to our entry.
447 } else { // writer locks
448 $encSession = $db->addQuotes( $this->session );
449 # Bail if there are any existing writers...
450 # The may detect readers, but the safe check for them is below.
451 # Note: if two writers come at the same time, both bail :)
452 $blocked = $db->selectField( 'filelocks_shared', '1',
453 array( 'fls_key' => $keys, "fls_session != $encSession" ),
454 __METHOD__
455 );
456 if ( !$blocked ) {
457 # Build up values for INSERT clause
458 $data = array();
459 foreach ( $keys as $key ) {
460 $data[] = array( 'fle_key' => $key );
461 }
462 # Block new readers/writers...
463 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
464 # Bail if there are any existing readers...
465 $blocked = $db->selectField( 'filelocks_shared', '1',
466 array( 'fls_key' => $keys, "fls_session != $encSession" ),
467 __METHOD__
468 );
469 }
470 }
471 return !$blocked;
472 }
473 }