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