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