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
21 * @ingroup LockManager
25 * Version of LockManager based on using DB table row locks.
27 * This is meant for multi-wiki systems that may share files.
28 * All locks are blocking, so it might be useful to set a small
29 * lock-wait timeout via server config to curtail deadlocks.
31 * All lock requests for a resource, identified by a hash string, will map
32 * to one bucket. Each bucket maps to one or several peer DBs, each on their
33 * own server, all having the filelocks.sql tables (with row-level locking).
34 * A majority of peer DBs must agree for a lock to be acquired.
36 * Caching is used to avoid hitting servers that are down.
38 * @ingroup LockManager
41 class DBLockManager
extends QuorumLockManager
{
42 /** @var Array Map of DB names to server config */
43 protected $dbServers; // (DB name => server config array)
45 protected $statusCache;
47 protected $lockExpiry; // integer number of seconds
48 protected $safeDelay; // integer number of seconds
50 protected $session = 0; // random integer
51 /** @var Array Map Database connections (DB name => Database) */
52 protected $conns = array();
55 * Construct a new instance from configuration.
57 * $config paramaters include:
58 * - dbServers : Associative array of DB names to server configuration.
59 * Configuration is an associative array that includes:
60 * - host : DB server name
62 * - type : DB type (mysql,postgres,...)
64 * - password : DB user password
65 * - tablePrefix : DB table prefix
66 * - flags : DB flags (see DatabaseBase)
67 * - dbsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
68 * each having an odd-numbered list of DB names (peers) as values.
69 * Any DB named 'localDBMaster' will automatically use the DB master
70 * settings for this wiki (without the need for a dbServers entry).
71 * Only use 'localDBMaster' if the domain is a valid wiki ID.
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.
76 * @param Array $config
78 public function __construct( array $config ) {
79 parent
::__construct( $config );
81 $this->dbServers
= isset( $config['dbServers'] )
82 ?
$config['dbServers']
83 : array(); // likely just using 'localDBMaster'
84 // Sanitize srvsByBucket config to prevent PHP errors
85 $this->srvsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
86 $this->srvsByBucket
= array_values( $this->srvsByBucket
); // consecutive
88 if ( isset( $config['lockExpiry'] ) ) {
89 $this->lockExpiry
= $config['lockExpiry'];
91 $met = ini_get( 'max_execution_time' );
92 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
94 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
95 ?
60 // pick a safe-ish number to match DB timeout default
96 : $this->lockExpiry
; // cover worst case
98 foreach ( $this->srvsByBucket
as $bucket ) {
99 if ( count( $bucket ) > 1 ) { // multiple peers
100 // Tracks peers that couldn't be queried recently to avoid lengthy
101 // connection timeouts. This is useless if each bucket has one peer.
103 $this->statusCache
= ObjectCache
::newAccelerator( array() );
104 } catch ( MWException
$e ) {
105 trigger_error( __CLASS__
.
106 " using multiple DB peers without apc, xcache, or wincache." );
112 $this->session
= wfRandomString( 31 );
116 * Get a connection to a lock DB and acquire locks on $paths.
117 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
119 * @see QuorumLockManager::getLocksOnServer()
122 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
123 $status = Status
::newGood();
125 if ( $type == self
::LOCK_EX
) { // writer locks
127 $keys = array_unique( array_map( array( $this, 'sha1Base36Absolute' ), $paths ) );
128 # Build up values for INSERT clause
130 foreach ( $keys as $key ) {
131 $data[] = array( 'fle_key' => $key );
133 # Wait on any existing writers and block new ones if we get in
134 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
135 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
136 } catch ( DBError
$e ) {
137 foreach ( $paths as $path ) {
138 $status->fatal( 'lockmanager-fail-acquirelock', $path );
147 * @see QuorumLockManager::freeLocksOnServer()
150 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
151 return Status
::newGood(); // not supported
155 * @see QuorumLockManager::releaseAllLocks()
158 protected function releaseAllLocks() {
159 $status = Status
::newGood();
161 foreach ( $this->conns
as $lockDb => $db ) {
162 if ( $db->trxLevel() ) { // in transaction
164 $db->rollback( __METHOD__
); // finish transaction and kill any rows
165 } catch ( DBError
$e ) {
166 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
175 * @see QuorumLockManager::isServerUp()
178 protected function isServerUp( $lockSrv ) {
179 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
180 return false; // recent failure to connect
183 $this->getConnection( $lockSrv );
184 } catch ( DBError
$e ) {
185 $this->cacheRecordFailure( $lockSrv );
186 return false; // failed to connect
192 * Get (or reuse) a connection to a lock DB
194 * @param $lockDb string
195 * @return DatabaseBase
198 protected function getConnection( $lockDb ) {
199 if ( !isset( $this->conns
[$lockDb] ) ) {
201 if ( $lockDb === 'localDBMaster' ) {
202 $lb = wfGetLBFactory()->getMainLB( $this->domain
);
203 $db = $lb->getConnection( DB_MASTER
, array(), $this->domain
);
204 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
205 $config = $this->dbServers
[$lockDb];
206 $db = DatabaseBase
::factory( $config['type'], $config );
209 return null; // config error?
211 $this->conns
[$lockDb] = $db;
212 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
213 # If the connection drops, try to avoid letting the DB rollback
214 # and release the locks before the file operations are finished.
215 # This won't handle the case of DB server restarts however.
217 if ( $this->lockExpiry
> 0 ) {
218 $options['connTimeout'] = $this->lockExpiry
;
220 $this->conns
[$lockDb]->setSessionOptions( $options );
221 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
223 if ( !$this->conns
[$lockDb]->trxLevel() ) {
224 $this->conns
[$lockDb]->begin( __METHOD__
); // start transaction
226 return $this->conns
[$lockDb];
230 * Do additional initialization for new lock DB connection
232 * @param $lockDb string
233 * @param $db DatabaseBase
237 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
240 * Checks if the DB has not recently had connection/query errors.
241 * This just avoids wasting time on doomed connection attempts.
243 * @param $lockDb string
246 protected function cacheCheckFailures( $lockDb ) {
247 return ( $this->statusCache
&& $this->safeDelay
> 0 )
248 ?
!$this->statusCache
->get( $this->getMissKey( $lockDb ) )
253 * Log a lock request failure to the cache
255 * @param $lockDb string
256 * @return bool Success
258 protected function cacheRecordFailure( $lockDb ) {
259 return ( $this->statusCache
&& $this->safeDelay
> 0 )
260 ?
$this->statusCache
->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay
)
265 * Get a cache key for recent query misses for a DB
267 * @param $lockDb string
270 protected function getMissKey( $lockDb ) {
271 $lockDb = ( $lockDb === 'localDBMaster' ) ?
wfWikiID() : $lockDb; // non-relative
272 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
276 * Make sure remaining locks get cleared for sanity
278 function __destruct() {
279 foreach ( $this->conns
as $db ) {
280 if ( $db->trxLevel() ) { // in transaction
282 $db->rollback( __METHOD__
); // finish transaction and kill any rows
283 } catch ( DBError
$e ) {
293 * MySQL version of DBLockManager that supports shared locks.
294 * All locks are non-blocking, which avoids deadlocks.
296 * @ingroup LockManager
298 class MySqlLockManager
extends DBLockManager
{
299 /** @var Array Mapping of lock types to the type actually used */
300 protected $lockTypeMap = array(
301 self
::LOCK_SH
=> self
::LOCK_SH
,
302 self
::LOCK_UW
=> self
::LOCK_SH
,
303 self
::LOCK_EX
=> self
::LOCK_EX
307 * @param $lockDb string
308 * @param $db DatabaseBase
310 protected function initConnection( $lockDb, DatabaseBase
$db ) {
311 # Let this transaction see lock rows from other transactions
312 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
316 * Get a connection to a lock DB and acquire locks on $paths.
317 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
319 * @see DBLockManager::getLocksOnServer()
322 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
323 $status = Status
::newGood();
325 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
326 $keys = array_unique( array_map( array( $this, 'sha1Base36Absolute' ), $paths ) );
327 # Build up values for INSERT clause
329 foreach ( $keys as $key ) {
330 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
332 # Block new writers...
333 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
334 # Actually do the locking queries...
335 if ( $type == self
::LOCK_SH
) { // reader locks
336 # Bail if there are any existing writers...
337 $blocked = $db->selectField( 'filelocks_exclusive', '1',
338 array( 'fle_key' => $keys ),
341 # Prospective writers that haven't yet updated filelocks_exclusive
342 # will recheck filelocks_shared after doing so and bail due to our entry.
343 } else { // writer locks
344 $encSession = $db->addQuotes( $this->session
);
345 # Bail if there are any existing writers...
346 # The may detect readers, but the safe check for them is below.
347 # Note: if two writers come at the same time, both bail :)
348 $blocked = $db->selectField( 'filelocks_shared', '1',
349 array( 'fls_key' => $keys, "fls_session != $encSession" ),
353 # Build up values for INSERT clause
355 foreach ( $keys as $key ) {
356 $data[] = array( 'fle_key' => $key );
358 # Block new readers/writers...
359 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
360 # Bail if there are any existing readers...
361 $blocked = $db->selectField( 'filelocks_shared', '1',
362 array( 'fls_key' => $keys, "fls_session != $encSession" ),
369 foreach ( $paths as $path ) {
370 $status->fatal( 'lockmanager-fail-acquirelock', $path );