Kill "* @return void"
[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 * @throws DBError
285 */
286 protected function initConnection( $lockDb, DatabaseBase $db ) {}
287
288 /**
289 * Commit all changes to lock-active databases.
290 * This should avoid throwing any exceptions.
291 *
292 * @return Status
293 */
294 protected function finishLockTransactions() {
295 $status = Status::newGood();
296 foreach ( $this->conns as $lockDb => $db ) {
297 if ( $db->trxLevel() ) { // in transaction
298 try {
299 $db->rollback(); // finish transaction and kill any rows
300 } catch ( DBError $e ) {
301 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
302 }
303 }
304 }
305 return $status;
306 }
307
308 /**
309 * Check if the last DB error for $lockDb indicates
310 * that a requested resource was locked by another process.
311 * This should avoid throwing any exceptions.
312 *
313 * @param $lockDb string
314 * @return bool
315 */
316 protected function lastErrorIndicatesLocked( $lockDb ) {
317 if ( isset( $this->conns[$lockDb] ) ) { // sanity
318 $db = $this->conns[$lockDb];
319 return ( $db->wasDeadlock() || $db->wasLockTimeout() );
320 }
321 return false;
322 }
323
324 /**
325 * Checks if the DB has not recently had connection/query errors.
326 * This just avoids wasting time on doomed connection attempts.
327 *
328 * @param $lockDb string
329 * @return bool
330 */
331 protected function cacheCheckFailures( $lockDb ) {
332 if ( $this->statusCache && $this->safeDelay > 0 ) {
333 $path = $this->getMissKey( $lockDb );
334 $misses = $this->statusCache->get( $path );
335 return !$misses;
336 }
337 return true;
338 }
339
340 /**
341 * Log a lock request failure to the cache
342 *
343 * @param $lockDb string
344 * @return bool Success
345 */
346 protected function cacheRecordFailure( $lockDb ) {
347 if ( $this->statusCache && $this->safeDelay > 0 ) {
348 $path = $this->getMissKey( $lockDb );
349 $misses = $this->statusCache->get( $path );
350 if ( $misses ) {
351 return $this->statusCache->incr( $path );
352 } else {
353 return $this->statusCache->add( $path, 1, $this->safeDelay );
354 }
355 }
356 return true;
357 }
358
359 /**
360 * Get a cache key for recent query misses for a DB
361 *
362 * @param $lockDb string
363 * @return string
364 */
365 protected function getMissKey( $lockDb ) {
366 return 'lockmanager:querymisses:' . str_replace( ' ', '_', $lockDb );
367 }
368
369 /**
370 * Get the bucket for resource path.
371 * This should avoid throwing any exceptions.
372 *
373 * @param $path string
374 * @return integer
375 */
376 protected function getBucketFromKey( $path ) {
377 $prefix = substr( sha1( $path ), 0, 2 ); // first 2 hex chars (8 bits)
378 return intval( base_convert( $prefix, 16, 10 ) ) % count( $this->dbsByBucket );
379 }
380
381 /**
382 * Make sure remaining locks get cleared for sanity
383 */
384 function __destruct() {
385 foreach ( $this->conns as $lockDb => $db ) {
386 if ( $db->trxLevel() ) { // in transaction
387 try {
388 $db->rollback(); // finish transaction and kill any rows
389 } catch ( DBError $e ) {
390 // oh well
391 }
392 }
393 $db->close();
394 }
395 }
396 }
397
398 /**
399 * MySQL version of DBLockManager that supports shared locks.
400 * All locks are non-blocking, which avoids deadlocks.
401 *
402 * @ingroup LockManager
403 */
404 class MySqlLockManager extends DBLockManager {
405 /** @var Array Mapping of lock types to the type actually used */
406 protected $lockTypeMap = array(
407 self::LOCK_SH => self::LOCK_SH,
408 self::LOCK_UW => self::LOCK_SH,
409 self::LOCK_EX => self::LOCK_EX
410 );
411
412 protected function initConnection( $lockDb, DatabaseBase $db ) {
413 # Let this transaction see lock rows from other transactions
414 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
415 }
416
417 protected function doLockingQuery( $lockDb, array $paths, $type ) {
418 $db = $this->getConnection( $lockDb );
419 if ( !$db ) {
420 return false;
421 }
422 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
423 # Build up values for INSERT clause
424 $data = array();
425 foreach ( $keys as $key ) {
426 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
427 }
428 # Block new writers...
429 $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
430 # Actually do the locking queries...
431 if ( $type == self::LOCK_SH ) { // reader locks
432 # Bail if there are any existing writers...
433 $blocked = $db->selectField( 'filelocks_exclusive', '1',
434 array( 'fle_key' => $keys ),
435 __METHOD__
436 );
437 # Prospective writers that haven't yet updated filelocks_exclusive
438 # will recheck filelocks_shared after doing so and bail due to our entry.
439 } else { // writer locks
440 $encSession = $db->addQuotes( $this->session );
441 # Bail if there are any existing writers...
442 # The may detect readers, but the safe check for them is below.
443 # Note: if two writers come at the same time, both bail :)
444 $blocked = $db->selectField( 'filelocks_shared', '1',
445 array( 'fls_key' => $keys, "fls_session != $encSession" ),
446 __METHOD__
447 );
448 if ( !$blocked ) {
449 # Build up values for INSERT clause
450 $data = array();
451 foreach ( $keys as $key ) {
452 $data[] = array( 'fle_key' => $key );
453 }
454 # Block new readers/writers...
455 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
456 # Bail if there are any existing readers...
457 $blocked = $db->selectField( 'filelocks_shared', '1',
458 array( 'fls_key' => $keys, "fls_session != $encSession" ),
459 __METHOD__
460 );
461 }
462 }
463 return !$blocked;
464 }
465 }