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