Add braces
[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 * $config paramaters include:
36 * 'dbServers' : Associative array of DB names to server configuration.
37 * Configuration is an associative array that includes:
38 * 'host' - DB server name
39 * 'dbname' - DB name
40 * 'type' - DB type (mysql,postgres,...)
41 * 'user' - DB user
42 * 'password' - DB user password
43 * 'tablePrefix' - DB table prefix
44 * 'flags' - DB flags (see DatabaseBase)
45 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
46 * each having an odd-numbered list of DB names (peers) as values.
47 * Any DB named 'localDBMaster' will automatically use the DB master
48 * settings for this wiki (without the need for a dbServers entry).
49 * 'lockExpiry' : Lock timeout (seconds) for dropped connections. [optional]
50 * This tells the DB server how long to wait before assuming
51 * connection failure and releasing all the locks for a session.
52 *
53 * @param Array $config
54 */
55 public function __construct( array $config ) {
56 $this->dbServers = $config['dbServers'];
57 // Sanitize dbsByBucket config to prevent PHP errors
58 $this->dbsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
59 $this->dbsByBucket = array_values( $this->dbsByBucket ); // consecutive
60
61 if ( isset( $config['lockExpiry'] ) ) {
62 $this->lockExpiry = $config['lockExpiry'];
63 } else {
64 $met = ini_get( 'max_execution_time' );
65 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
66 }
67 $this->safeDelay = ( $this->lockExpiry <= 0 )
68 ? 60 // pick a safe-ish number to match DB timeout default
69 : $this->lockExpiry; // cover worst case
70
71 foreach ( $this->dbsByBucket as $bucket ) {
72 if ( count( $bucket ) > 1 ) {
73 // Tracks peers that couldn't be queried recently to avoid lengthy
74 // connection timeouts. This is useless if each bucket has one peer.
75 $this->statusCache = wfGetMainCache();
76 break;
77 }
78 }
79
80 $this->session = '';
81 for ( $i = 0; $i < 5; $i++ ) {
82 $this->session .= mt_rand( 0, 2147483647 );
83 }
84 $this->session = wfBaseConvert( sha1( $this->session ), 16, 36, 31 );
85 }
86
87 /**
88 * @see LockManager::doLock()
89 */
90 protected function doLock( array $paths, $type ) {
91 $status = Status::newGood();
92
93 $pathsToLock = array();
94 // Get locks that need to be acquired (buckets => locks)...
95 foreach ( $paths as $path ) {
96 if ( isset( $this->locksHeld[$path][$type] ) ) {
97 ++$this->locksHeld[$path][$type];
98 } elseif ( isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
99 $this->locksHeld[$path][$type] = 1;
100 } else {
101 $bucket = $this->getBucketFromKey( $path );
102 $pathsToLock[$bucket][] = $path;
103 }
104 }
105
106 $lockedPaths = array(); // files locked in this attempt
107 // Attempt to acquire these locks...
108 foreach ( $pathsToLock as $bucket => $paths ) {
109 // Try to acquire the locks for this bucket
110 $res = $this->doLockingQueryAll( $bucket, $paths, $type );
111 if ( $res === 'cantacquire' ) {
112 // Resources already locked by another process.
113 // Abort and unlock everything we just locked.
114 foreach ( $paths as $path ) {
115 $status->fatal( 'lockmanager-fail-acquirelock', $path );
116 }
117 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
118 return $status;
119 } elseif ( $res !== true ) {
120 // Couldn't contact any DBs for this bucket.
121 // Abort and unlock everything we just locked.
122 $status->fatal( 'lockmanager-fail-db-bucket', $bucket );
123 $status->merge( $this->doUnlock( $lockedPaths, $type ) );
124 return $status;
125 }
126 // Record these locks as active
127 foreach ( $paths as $path ) {
128 $this->locksHeld[$path][$type] = 1; // locked
129 }
130 // Keep track of what locks were made in this attempt
131 $lockedPaths = array_merge( $lockedPaths, $paths );
132 }
133
134 return $status;
135 }
136
137 /**
138 * @see LockManager::doUnlock()
139 */
140 protected function doUnlock( array $paths, $type ) {
141 $status = Status::newGood();
142
143 foreach ( $paths as $path ) {
144 if ( !isset( $this->locksHeld[$path] ) ) {
145 $status->warning( 'lockmanager-notlocked', $path );
146 } elseif ( !isset( $this->locksHeld[$path][$type] ) ) {
147 $status->warning( 'lockmanager-notlocked', $path );
148 } else {
149 --$this->locksHeld[$path][$type];
150 if ( $this->locksHeld[$path][$type] <= 0 ) {
151 unset( $this->locksHeld[$path][$type] );
152 }
153 if ( !count( $this->locksHeld[$path] ) ) {
154 unset( $this->locksHeld[$path] ); // no SH or EX locks left for key
155 }
156 }
157 }
158
159 // Reference count the locks held and COMMIT when zero
160 if ( !count( $this->locksHeld ) ) {
161 $status->merge( $this->finishLockTransactions() );
162 }
163
164 return $status;
165 }
166
167 /**
168 * Get a connection to a lock DB and acquire locks on $paths.
169 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
170 *
171 * @param $lockDb string
172 * @param $paths Array
173 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
174 * @return bool Resources able to be locked
175 * @throws DBError
176 */
177 protected function doLockingQuery( $lockDb, array $paths, $type ) {
178 if ( $type == self::LOCK_EX ) { // writer locks
179 $db = $this->getConnection( $lockDb );
180 if ( !$db ) {
181 return false; // bad config
182 }
183 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
184 # Build up values for INSERT clause
185 $data = array();
186 foreach ( $keys as $key ) {
187 $data[] = array( 'fle_key' => $key );
188 }
189 # Wait on any existing writers and block new ones if we get in
190 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
191 }
192 return true;
193 }
194
195 /**
196 * Attempt to acquire locks with the peers for a bucket.
197 * This should avoid throwing any exceptions.
198 *
199 * @param $bucket integer
200 * @param $paths Array List of resource keys to lock
201 * @param $type integer LockManager::LOCK_EX or LockManager::LOCK_SH
202 * @return bool|string One of (true, 'cantacquire', 'dberrors')
203 */
204 protected function doLockingQueryAll( $bucket, array $paths, $type ) {
205 $yesVotes = 0; // locks made on trustable DBs
206 $votesLeft = count( $this->dbsByBucket[$bucket] ); // remaining DBs
207 $quorum = floor( $votesLeft/2 + 1 ); // simple majority
208 // Get votes for each DB, in order, until we have enough...
209 foreach ( $this->dbsByBucket[$bucket] as $lockDb ) {
210 // Check that DB is not *known* to be down
211 if ( $this->cacheCheckFailures( $lockDb ) ) {
212 try {
213 // Attempt to acquire the lock on this DB
214 if ( !$this->doLockingQuery( $lockDb, $paths, $type ) ) {
215 return 'cantacquire'; // vetoed; resource locked
216 }
217 ++$yesVotes; // success for this peer
218 if ( $yesVotes >= $quorum ) {
219 return true; // lock obtained
220 }
221 } catch ( DBConnectionError $e ) {
222 $this->cacheRecordFailure( $lockDb );
223 } catch ( DBError $e ) {
224 if ( $this->lastErrorIndicatesLocked( $lockDb ) ) {
225 return 'cantacquire'; // vetoed; resource locked
226 }
227 }
228 }
229 --$votesLeft;
230 $votesNeeded = $quorum - $yesVotes;
231 if ( $votesNeeded > $votesLeft ) {
232 // In "trust cache" mode we don't have to meet the quorum
233 break; // short-circuit
234 }
235 }
236 // At this point, we must not have meet the quorum
237 return 'dberrors'; // not enough votes to ensure correctness
238 }
239
240 /**
241 * Get (or reuse) a connection to a lock DB
242 *
243 * @param $lockDb string
244 * @return Database
245 * @throws DBError
246 */
247 protected function getConnection( $lockDb ) {
248 if ( !isset( $this->conns[$lockDb] ) ) {
249 $db = null;
250 if ( $lockDb === 'localDBMaster' ) {
251 $lb = wfGetLBFactory()->newMainLB();
252 $db = $lb->getConnection( DB_MASTER );
253 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
254 $config = $this->dbServers[$lockDb];
255 $db = DatabaseBase::factory( $config['type'], $config );
256 }
257 if ( !$db ) {
258 return null; // config error?
259 }
260 $this->conns[$lockDb] = $db;
261 $this->conns[$lockDb]->clearFlag( DBO_TRX );
262 # If the connection drops, try to avoid letting the DB rollback
263 # and release the locks before the file operations are finished.
264 # This won't handle the case of DB server restarts however.
265 $options = array();
266 if ( $this->lockExpiry > 0 ) {
267 $options['connTimeout'] = $this->lockExpiry;
268 }
269 $this->conns[$lockDb]->setSessionOptions( $options );
270 $this->initConnection( $lockDb, $this->conns[$lockDb] );
271 }
272 if ( !$this->conns[$lockDb]->trxLevel() ) {
273 $this->conns[$lockDb]->begin(); // start transaction
274 }
275 return $this->conns[$lockDb];
276 }
277
278 /**
279 * Do additional initialization for new lock DB connection
280 *
281 * @param $lockDb string
282 * @param $db DatabaseBase
283 * @return void
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 }