thumb_handler.php doesn't seem to extract path_info correctly
[mediawiki.git] / includes / filebackend / lockmanager / DBLockManager.php
blobe081987851a8cc7142dc48f37e0f4bc72aaec833
1 <?php
2 /**
3 * Version of LockManager based on using DB table locks.
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.
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.
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
20 * @file
21 * @ingroup LockManager
24 /**
25 * Version of LockManager based on using named/row DB locks.
27 * This is meant for multi-wiki systems that may share files.
29 * All lock requests for a resource, identified by a hash string, will map
30 * to one bucket. Each bucket maps to one or several peer DBs, each on their
31 * own server, all having the filelocks.sql tables (with row-level locking).
32 * A majority of peer DBs must agree for a lock to be acquired.
34 * Caching is used to avoid hitting servers that are down.
36 * @ingroup LockManager
37 * @since 1.19
39 abstract class DBLockManager extends QuorumLockManager {
40 /** @var Array Map of DB names to server config */
41 protected $dbServers; // (DB name => server config array)
42 /** @var BagOStuff */
43 protected $statusCache;
45 protected $lockExpiry; // integer number of seconds
46 protected $safeDelay; // integer number of seconds
48 protected $session = 0; // random integer
49 /** @var Array Map Database connections (DB name => Database) */
50 protected $conns = array();
52 /**
53 * Construct a new instance from configuration.
55 * $config paramaters include:
56 * - dbServers : Associative array of DB names to server configuration.
57 * Configuration is an associative array that includes:
58 * - host : DB server name
59 * - dbname : DB name
60 * - type : DB type (mysql,postgres,...)
61 * - user : DB user
62 * - password : DB user password
63 * - tablePrefix : DB table prefix
64 * - flags : DB flags (see DatabaseBase)
65 * - dbsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
66 * each having an odd-numbered list of DB names (peers) as values.
67 * Any DB named 'localDBMaster' will automatically use the DB master
68 * settings for this wiki (without the need for a dbServers entry).
69 * Only use 'localDBMaster' if the domain is a valid wiki ID.
70 * - lockExpiry : Lock timeout (seconds) for dropped connections. [optional]
71 * This tells the DB server how long to wait before assuming
72 * connection failure and releasing all the locks for a session.
74 * @param array $config
76 public function __construct( array $config ) {
77 parent::__construct( $config );
79 $this->dbServers = isset( $config['dbServers'] )
80 ? $config['dbServers']
81 : array(); // likely just using 'localDBMaster'
82 // Sanitize srvsByBucket config to prevent PHP errors
83 $this->srvsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
84 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
86 if ( isset( $config['lockExpiry'] ) ) {
87 $this->lockExpiry = $config['lockExpiry'];
88 } else {
89 $met = ini_get( 'max_execution_time' );
90 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
92 $this->safeDelay = ( $this->lockExpiry <= 0 )
93 ? 60 // pick a safe-ish number to match DB timeout default
94 : $this->lockExpiry; // cover worst case
96 foreach ( $this->srvsByBucket as $bucket ) {
97 if ( count( $bucket ) > 1 ) { // multiple peers
98 // Tracks peers that couldn't be queried recently to avoid lengthy
99 // connection timeouts. This is useless if each bucket has one peer.
100 try {
101 $this->statusCache = ObjectCache::newAccelerator( array() );
102 } catch ( MWException $e ) {
103 trigger_error( __CLASS__ .
104 " using multiple DB peers without apc, xcache, or wincache." );
106 break;
110 $this->session = wfRandomString( 31 );
114 * @see QuorumLockManager::isServerUp()
115 * @return bool
117 protected function isServerUp( $lockSrv ) {
118 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
119 return false; // recent failure to connect
121 try {
122 $this->getConnection( $lockSrv );
123 } catch ( DBError $e ) {
124 $this->cacheRecordFailure( $lockSrv );
125 return false; // failed to connect
127 return true;
131 * Get (or reuse) a connection to a lock DB
133 * @param $lockDb string
134 * @return DatabaseBase
135 * @throws DBError
137 protected function getConnection( $lockDb ) {
138 if ( !isset( $this->conns[$lockDb] ) ) {
139 $db = null;
140 if ( $lockDb === 'localDBMaster' ) {
141 $lb = wfGetLBFactory()->getMainLB( $this->domain );
142 $db = $lb->getConnection( DB_MASTER, array(), $this->domain );
143 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
144 $config = $this->dbServers[$lockDb];
145 $db = DatabaseBase::factory( $config['type'], $config );
147 if ( !$db ) {
148 return null; // config error?
150 $this->conns[$lockDb] = $db;
151 $this->conns[$lockDb]->clearFlag( DBO_TRX );
152 # If the connection drops, try to avoid letting the DB rollback
153 # and release the locks before the file operations are finished.
154 # This won't handle the case of DB server restarts however.
155 $options = array();
156 if ( $this->lockExpiry > 0 ) {
157 $options['connTimeout'] = $this->lockExpiry;
159 $this->conns[$lockDb]->setSessionOptions( $options );
160 $this->initConnection( $lockDb, $this->conns[$lockDb] );
162 if ( !$this->conns[$lockDb]->trxLevel() ) {
163 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
165 return $this->conns[$lockDb];
169 * Do additional initialization for new lock DB connection
171 * @param $lockDb string
172 * @param $db DatabaseBase
173 * @return void
174 * @throws DBError
176 protected function initConnection( $lockDb, DatabaseBase $db ) {}
179 * Checks if the DB has not recently had connection/query errors.
180 * This just avoids wasting time on doomed connection attempts.
182 * @param $lockDb string
183 * @return bool
185 protected function cacheCheckFailures( $lockDb ) {
186 return ( $this->statusCache && $this->safeDelay > 0 )
187 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
188 : true;
192 * Log a lock request failure to the cache
194 * @param $lockDb string
195 * @return bool Success
197 protected function cacheRecordFailure( $lockDb ) {
198 return ( $this->statusCache && $this->safeDelay > 0 )
199 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
200 : true;
204 * Get a cache key for recent query misses for a DB
206 * @param $lockDb string
207 * @return string
209 protected function getMissKey( $lockDb ) {
210 $lockDb = ( $lockDb === 'localDBMaster' ) ? wfWikiID() : $lockDb; // non-relative
211 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
215 * Make sure remaining locks get cleared for sanity
217 function __destruct() {
218 $this->releaseAllLocks();
219 foreach ( $this->conns as $db ) {
220 $db->close();
226 * MySQL version of DBLockManager that supports shared locks.
227 * All locks are non-blocking, which avoids deadlocks.
229 * @ingroup LockManager
231 class MySqlLockManager extends DBLockManager {
232 /** @var Array Mapping of lock types to the type actually used */
233 protected $lockTypeMap = array(
234 self::LOCK_SH => self::LOCK_SH,
235 self::LOCK_UW => self::LOCK_SH,
236 self::LOCK_EX => self::LOCK_EX
240 * @param $lockDb string
241 * @param $db DatabaseBase
243 protected function initConnection( $lockDb, DatabaseBase $db ) {
244 # Let this transaction see lock rows from other transactions
245 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
249 * Get a connection to a lock DB and acquire locks on $paths.
250 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
252 * @see DBLockManager::getLocksOnServer()
253 * @return Status
255 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
256 $status = Status::newGood();
258 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
260 $keys = array(); // list of hash keys for the paths
261 $data = array(); // list of rows to insert
262 $checkEXKeys = array(); // list of hash keys that this has no EX lock on
263 # Build up values for INSERT clause
264 foreach ( $paths as $path ) {
265 $key = $this->sha1Base36Absolute( $path );
266 $keys[] = $key;
267 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
268 if ( !isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
269 $checkEXKeys[] = $key;
273 # Block new writers (both EX and SH locks leave entries here)...
274 $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
275 # Actually do the locking queries...
276 if ( $type == self::LOCK_SH ) { // reader locks
277 $blocked = false;
278 # Bail if there are any existing writers...
279 if ( count( $checkEXKeys ) ) {
280 $blocked = $db->selectField( 'filelocks_exclusive', '1',
281 array( 'fle_key' => $checkEXKeys ),
282 __METHOD__
285 # Other prospective writers that haven't yet updated filelocks_exclusive
286 # will recheck filelocks_shared after doing so and bail due to this entry.
287 } else { // writer locks
288 $encSession = $db->addQuotes( $this->session );
289 # Bail if there are any existing writers...
290 # This may detect readers, but the safe check for them is below.
291 # Note: if two writers come at the same time, both bail :)
292 $blocked = $db->selectField( 'filelocks_shared', '1',
293 array( 'fls_key' => $keys, "fls_session != $encSession" ),
294 __METHOD__
296 if ( !$blocked ) {
297 # Build up values for INSERT clause
298 $data = array();
299 foreach ( $keys as $key ) {
300 $data[] = array( 'fle_key' => $key );
302 # Block new readers/writers...
303 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
304 # Bail if there are any existing readers...
305 $blocked = $db->selectField( 'filelocks_shared', '1',
306 array( 'fls_key' => $keys, "fls_session != $encSession" ),
307 __METHOD__
312 if ( $blocked ) {
313 foreach ( $paths as $path ) {
314 $status->fatal( 'lockmanager-fail-acquirelock', $path );
318 return $status;
322 * @see QuorumLockManager::freeLocksOnServer()
323 * @return Status
325 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
326 return Status::newGood(); // not supported
330 * @see QuorumLockManager::releaseAllLocks()
331 * @return Status
333 protected function releaseAllLocks() {
334 $status = Status::newGood();
336 foreach ( $this->conns as $lockDb => $db ) {
337 if ( $db->trxLevel() ) { // in transaction
338 try {
339 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
340 } catch ( DBError $e ) {
341 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
346 return $status;
351 * PostgreSQL version of DBLockManager that supports shared locks.
352 * All locks are non-blocking, which avoids deadlocks.
354 * @ingroup LockManager
356 class PostgreSqlLockManager extends DBLockManager {
357 /** @var Array Mapping of lock types to the type actually used */
358 protected $lockTypeMap = array(
359 self::LOCK_SH => self::LOCK_SH,
360 self::LOCK_UW => self::LOCK_SH,
361 self::LOCK_EX => self::LOCK_EX
364 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
365 $status = Status::newGood();
366 if ( !count( $paths ) ) {
367 return $status; // nothing to lock
370 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
371 $bigints = array_unique( array_map(
372 function( $key ) {
373 return wfBaseConvert( substr( $key, 0, 15 ), 16, 10 );
375 array_map( array( $this, 'sha1Base16Absolute' ), $paths )
376 ) );
378 // Try to acquire all the locks...
379 $fields = array();
380 foreach ( $bigints as $bigint ) {
381 $fields[] = ( $type == self::LOCK_SH )
382 ? "pg_try_advisory_lock_shared({$db->addQuotes( $bigint )}) AS K$bigint"
383 : "pg_try_advisory_lock({$db->addQuotes( $bigint )}) AS K$bigint";
385 $res = $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
386 $row = (array)$res->fetchObject();
388 if ( in_array( 'f', $row ) ) {
389 // Release any acquired locks if some could not be acquired...
390 $fields = array();
391 foreach ( $row as $kbigint => $ok ) {
392 if ( $ok === 't' ) { // locked
393 $bigint = substr( $kbigint, 1 ); // strip off the "K"
394 $fields[] = ( $type == self::LOCK_SH )
395 ? "pg_advisory_unlock_shared({$db->addQuotes( $bigint )})"
396 : "pg_advisory_unlock({$db->addQuotes( $bigint )})";
399 if ( count( $fields ) ) {
400 $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
402 foreach ( $paths as $path ) {
403 $status->fatal( 'lockmanager-fail-acquirelock', $path );
407 return $status;
411 * @see QuorumLockManager::freeLocksOnServer()
412 * @return Status
414 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
415 return Status::newGood(); // not supported
419 * @see QuorumLockManager::releaseAllLocks()
420 * @return Status
422 protected function releaseAllLocks() {
423 $status = Status::newGood();
425 foreach ( $this->conns as $lockDb => $db ) {
426 try {
427 $db->query( "SELECT pg_advisory_unlock_all()", __METHOD__ );
428 } catch ( DBError $e ) {
429 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
433 return $status;