PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / filebackend / lockmanager / DBLockManager.php
blobc93b4b419586b011e7527d7827a87b435995e8cd
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 * @param array $config Parameters 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 public function __construct( array $config ) {
75 parent::__construct( $config );
77 $this->dbServers = isset( $config['dbServers'] )
78 ? $config['dbServers']
79 : array(); // likely just using 'localDBMaster'
80 // Sanitize srvsByBucket config to prevent PHP errors
81 $this->srvsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
82 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
84 if ( isset( $config['lockExpiry'] ) ) {
85 $this->lockExpiry = $config['lockExpiry'];
86 } else {
87 $met = ini_get( 'max_execution_time' );
88 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
90 $this->safeDelay = ( $this->lockExpiry <= 0 )
91 ? 60 // pick a safe-ish number to match DB timeout default
92 : $this->lockExpiry; // cover worst case
94 foreach ( $this->srvsByBucket as $bucket ) {
95 if ( count( $bucket ) > 1 ) { // multiple peers
96 // Tracks peers that couldn't be queried recently to avoid lengthy
97 // connection timeouts. This is useless if each bucket has one peer.
98 $this->statusCache = ObjectCache::getLocalServerInstance();
99 break;
103 $this->session = wfRandomString( 31 );
106 // @todo change this code to work in one batch
107 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
108 $status = Status::newGood();
109 foreach ( $pathsByType as $type => $paths ) {
110 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
113 return $status;
116 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
117 return Status::newGood();
121 * @see QuorumLockManager::isServerUp()
122 * @param string $lockSrv
123 * @return bool
125 protected function isServerUp( $lockSrv ) {
126 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
127 return false; // recent failure to connect
129 try {
130 $this->getConnection( $lockSrv );
131 } catch ( DBError $e ) {
132 $this->cacheRecordFailure( $lockSrv );
134 return false; // failed to connect
137 return true;
141 * Get (or reuse) a connection to a lock DB
143 * @param string $lockDb
144 * @return IDatabase
145 * @throws DBError
147 protected function getConnection( $lockDb ) {
148 if ( !isset( $this->conns[$lockDb] ) ) {
149 $db = null;
150 if ( $lockDb === 'localDBMaster' ) {
151 $lb = wfGetLBFactory()->getMainLB( $this->domain );
152 $db = $lb->getConnection( DB_MASTER, array(), $this->domain );
153 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
154 $config = $this->dbServers[$lockDb];
155 $db = DatabaseBase::factory( $config['type'], $config );
157 if ( !$db ) {
158 return null; // config error?
160 $this->conns[$lockDb] = $db;
161 $this->conns[$lockDb]->clearFlag( DBO_TRX );
162 # If the connection drops, try to avoid letting the DB rollback
163 # and release the locks before the file operations are finished.
164 # This won't handle the case of DB server restarts however.
165 $options = array();
166 if ( $this->lockExpiry > 0 ) {
167 $options['connTimeout'] = $this->lockExpiry;
169 $this->conns[$lockDb]->setSessionOptions( $options );
170 $this->initConnection( $lockDb, $this->conns[$lockDb] );
172 if ( !$this->conns[$lockDb]->trxLevel() ) {
173 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
176 return $this->conns[$lockDb];
180 * Do additional initialization for new lock DB connection
182 * @param string $lockDb
183 * @param IDatabase $db
184 * @throws DBError
186 protected function initConnection( $lockDb, IDatabase $db ) {
190 * Checks if the DB has not recently had connection/query errors.
191 * This just avoids wasting time on doomed connection attempts.
193 * @param string $lockDb
194 * @return bool
196 protected function cacheCheckFailures( $lockDb ) {
197 return ( $this->statusCache && $this->safeDelay > 0 )
198 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
199 : true;
203 * Log a lock request failure to the cache
205 * @param string $lockDb
206 * @return bool Success
208 protected function cacheRecordFailure( $lockDb ) {
209 return ( $this->statusCache && $this->safeDelay > 0 )
210 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
211 : true;
215 * Get a cache key for recent query misses for a DB
217 * @param string $lockDb
218 * @return string
220 protected function getMissKey( $lockDb ) {
221 $lockDb = ( $lockDb === 'localDBMaster' ) ? wfWikiID() : $lockDb; // non-relative
222 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
226 * Make sure remaining locks get cleared for sanity
228 function __destruct() {
229 $this->releaseAllLocks();
230 foreach ( $this->conns as $db ) {
231 $db->close();
237 * MySQL version of DBLockManager that supports shared locks.
238 * All locks are non-blocking, which avoids deadlocks.
240 * @ingroup LockManager
242 class MySqlLockManager extends DBLockManager {
243 /** @var array Mapping of lock types to the type actually used */
244 protected $lockTypeMap = array(
245 self::LOCK_SH => self::LOCK_SH,
246 self::LOCK_UW => self::LOCK_SH,
247 self::LOCK_EX => self::LOCK_EX
251 * @param string $lockDb
252 * @param IDatabase $db
254 protected function initConnection( $lockDb, IDatabase $db ) {
255 # Let this transaction see lock rows from other transactions
256 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
260 * Get a connection to a lock DB and acquire locks on $paths.
261 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
263 * @see DBLockManager::getLocksOnServer()
264 * @param string $lockSrv
265 * @param array $paths
266 * @param string $type
267 * @return Status
269 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
270 $status = Status::newGood();
272 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
274 $keys = array(); // list of hash keys for the paths
275 $data = array(); // list of rows to insert
276 $checkEXKeys = array(); // list of hash keys that this has no EX lock on
277 # Build up values for INSERT clause
278 foreach ( $paths as $path ) {
279 $key = $this->sha1Base36Absolute( $path );
280 $keys[] = $key;
281 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
282 if ( !isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
283 $checkEXKeys[] = $key;
287 # Block new writers (both EX and SH locks leave entries here)...
288 $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
289 # Actually do the locking queries...
290 if ( $type == self::LOCK_SH ) { // reader locks
291 $blocked = false;
292 # Bail if there are any existing writers...
293 if ( count( $checkEXKeys ) ) {
294 $blocked = $db->selectField( 'filelocks_exclusive', '1',
295 array( 'fle_key' => $checkEXKeys ),
296 __METHOD__
299 # Other prospective writers that haven't yet updated filelocks_exclusive
300 # will recheck filelocks_shared after doing so and bail due to this entry.
301 } else { // writer locks
302 $encSession = $db->addQuotes( $this->session );
303 # Bail if there are any existing writers...
304 # This may detect readers, but the safe check for them is below.
305 # Note: if two writers come at the same time, both bail :)
306 $blocked = $db->selectField( 'filelocks_shared', '1',
307 array( 'fls_key' => $keys, "fls_session != $encSession" ),
308 __METHOD__
310 if ( !$blocked ) {
311 # Build up values for INSERT clause
312 $data = array();
313 foreach ( $keys as $key ) {
314 $data[] = array( 'fle_key' => $key );
316 # Block new readers/writers...
317 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
318 # Bail if there are any existing readers...
319 $blocked = $db->selectField( 'filelocks_shared', '1',
320 array( 'fls_key' => $keys, "fls_session != $encSession" ),
321 __METHOD__
326 if ( $blocked ) {
327 foreach ( $paths as $path ) {
328 $status->fatal( 'lockmanager-fail-acquirelock', $path );
332 return $status;
336 * @see QuorumLockManager::releaseAllLocks()
337 * @return Status
339 protected function releaseAllLocks() {
340 $status = Status::newGood();
342 foreach ( $this->conns as $lockDb => $db ) {
343 if ( $db->trxLevel() ) { // in transaction
344 try {
345 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
346 } catch ( DBError $e ) {
347 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
352 return $status;
357 * PostgreSQL version of DBLockManager that supports shared locks.
358 * All locks are non-blocking, which avoids deadlocks.
360 * @ingroup LockManager
362 class PostgreSqlLockManager extends DBLockManager {
363 /** @var array Mapping of lock types to the type actually used */
364 protected $lockTypeMap = array(
365 self::LOCK_SH => self::LOCK_SH,
366 self::LOCK_UW => self::LOCK_SH,
367 self::LOCK_EX => self::LOCK_EX
370 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
371 $status = Status::newGood();
372 if ( !count( $paths ) ) {
373 return $status; // nothing to lock
376 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
377 $bigints = array_unique( array_map(
378 function ( $key ) {
379 return Wikimedia\base_convert( substr( $key, 0, 15 ), 16, 10 );
381 array_map( array( $this, 'sha1Base16Absolute' ), $paths )
382 ) );
384 // Try to acquire all the locks...
385 $fields = array();
386 foreach ( $bigints as $bigint ) {
387 $fields[] = ( $type == self::LOCK_SH )
388 ? "pg_try_advisory_lock_shared({$db->addQuotes( $bigint )}) AS K$bigint"
389 : "pg_try_advisory_lock({$db->addQuotes( $bigint )}) AS K$bigint";
391 $res = $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
392 $row = $res->fetchRow();
394 if ( in_array( 'f', $row ) ) {
395 // Release any acquired locks if some could not be acquired...
396 $fields = array();
397 foreach ( $row as $kbigint => $ok ) {
398 if ( $ok === 't' ) { // locked
399 $bigint = substr( $kbigint, 1 ); // strip off the "K"
400 $fields[] = ( $type == self::LOCK_SH )
401 ? "pg_advisory_unlock_shared({$db->addQuotes( $bigint )})"
402 : "pg_advisory_unlock({$db->addQuotes( $bigint )})";
405 if ( count( $fields ) ) {
406 $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
408 foreach ( $paths as $path ) {
409 $status->fatal( 'lockmanager-fail-acquirelock', $path );
413 return $status;
417 * @see QuorumLockManager::releaseAllLocks()
418 * @return Status
420 protected function releaseAllLocks() {
421 $status = Status::newGood();
423 foreach ( $this->conns as $lockDb => $db ) {
424 try {
425 $db->query( "SELECT pg_advisory_unlock_all()", __METHOD__ );
426 } catch ( DBError $e ) {
427 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
431 return $status;