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