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