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 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.
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.
35 * Caching is used to avoid hitting servers that are down.
37 * @ingroup LockManager
40 class DBLockManager
extends QuorumLockManager
{
41 /** @var Array Map of DB names to server config */
42 protected $dbServers; // (DB name => server config array)
44 protected $statusCache;
46 protected $lockExpiry; // integer number of seconds
47 protected $safeDelay; // integer number of seconds
49 protected $session = 0; // random integer
50 /** @var Array Map Database connections (DB name => Database) */
51 protected $conns = array();
54 * Construct a new instance from configuration.
56 * $config paramaters include:
57 * - dbServers : Associative array of DB names to server configuration.
58 * Configuration is an associative array that includes:
59 * - host : DB server name
61 * - type : DB type (mysql,postgres,...)
63 * - password : DB user password
64 * - tablePrefix : DB table prefix
65 * - flags : DB flags (see DatabaseBase)
66 * - dbsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
67 * each having an odd-numbered list of DB names (peers) as values.
68 * Any DB named 'localDBMaster' will automatically use the DB master
69 * settings for this wiki (without the need for a dbServers entry).
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'];
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.
101 $this->statusCache
= ObjectCache
::newAccelerator( array() );
102 } catch ( MWException
$e ) {
103 trigger_error( __CLASS__
.
104 " using multiple DB peers without apc, xcache, or wincache." );
110 $this->session
= wfRandomString( 31 );
114 * Get a connection to a lock DB and acquire locks on $paths.
115 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
117 * @see QuorumLockManager::getLocksOnServer()
120 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
121 $status = Status
::newGood();
123 if ( $type == self
::LOCK_EX
) { // writer locks
125 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
126 # Build up values for INSERT clause
128 foreach ( $keys as $key ) {
129 $data[] = array( 'fle_key' => $key );
131 # Wait on any existing writers and block new ones if we get in
132 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
133 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
134 } catch ( DBError
$e ) {
135 foreach ( $paths as $path ) {
136 $status->fatal( 'lockmanager-fail-acquirelock', $path );
145 * @see QuorumLockManager::freeLocksOnServer()
148 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
149 return Status
::newGood(); // not supported
153 * @see QuorumLockManager::releaseAllLocks()
156 protected function releaseAllLocks() {
157 $status = Status
::newGood();
159 foreach ( $this->conns
as $lockDb => $db ) {
160 if ( $db->trxLevel() ) { // in transaction
162 $db->rollback( __METHOD__
); // finish transaction and kill any rows
163 } catch ( DBError
$e ) {
164 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
173 * @see QuorumLockManager::isServerUp()
176 protected function isServerUp( $lockSrv ) {
177 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
178 return false; // recent failure to connect
181 $this->getConnection( $lockSrv );
182 } catch ( DBError
$e ) {
183 $this->cacheRecordFailure( $lockSrv );
184 return false; // failed to connect
190 * Get (or reuse) a connection to a lock DB
192 * @param $lockDb string
193 * @return DatabaseBase
196 protected function getConnection( $lockDb ) {
197 if ( !isset( $this->conns
[$lockDb] ) ) {
199 if ( $lockDb === 'localDBMaster' ) {
200 $lb = wfGetLBFactory()->newMainLB();
201 $db = $lb->getConnection( DB_MASTER
);
202 } elseif ( isset( $this->dbServers
[$lockDb] ) ) {
203 $config = $this->dbServers
[$lockDb];
204 $db = DatabaseBase
::factory( $config['type'], $config );
207 return null; // config error?
209 $this->conns
[$lockDb] = $db;
210 $this->conns
[$lockDb]->clearFlag( DBO_TRX
);
211 # If the connection drops, try to avoid letting the DB rollback
212 # and release the locks before the file operations are finished.
213 # This won't handle the case of DB server restarts however.
215 if ( $this->lockExpiry
> 0 ) {
216 $options['connTimeout'] = $this->lockExpiry
;
218 $this->conns
[$lockDb]->setSessionOptions( $options );
219 $this->initConnection( $lockDb, $this->conns
[$lockDb] );
221 if ( !$this->conns
[$lockDb]->trxLevel() ) {
222 $this->conns
[$lockDb]->begin( __METHOD__
); // start transaction
224 return $this->conns
[$lockDb];
228 * Do additional initialization for new lock DB connection
230 * @param $lockDb string
231 * @param $db DatabaseBase
235 protected function initConnection( $lockDb, DatabaseBase
$db ) {}
238 * Checks if the DB has not recently had connection/query errors.
239 * This just avoids wasting time on doomed connection attempts.
241 * @param $lockDb string
244 protected function cacheCheckFailures( $lockDb ) {
245 return ( $this->statusCache
&& $this->safeDelay
> 0 )
246 ?
!$this->statusCache
->get( $this->getMissKey( $lockDb ) )
251 * Log a lock request failure to the cache
253 * @param $lockDb string
254 * @return bool Success
256 protected function cacheRecordFailure( $lockDb ) {
257 return ( $this->statusCache
&& $this->safeDelay
> 0 )
258 ?
$this->statusCache
->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay
)
263 * Get a cache key for recent query misses for a DB
265 * @param $lockDb string
268 protected function getMissKey( $lockDb ) {
269 $lockDb = ( $lockDb === 'localDBMaster' ) ?
wfWikiID() : $lockDb; // non-relative
270 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
274 * Make sure remaining locks get cleared for sanity
276 function __destruct() {
277 foreach ( $this->conns
as $db ) {
278 if ( $db->trxLevel() ) { // in transaction
280 $db->rollback( __METHOD__
); // finish transaction and kill any rows
281 } catch ( DBError
$e ) {
291 * MySQL version of DBLockManager that supports shared locks.
292 * All locks are non-blocking, which avoids deadlocks.
294 * @ingroup LockManager
296 class MySqlLockManager
extends DBLockManager
{
297 /** @var Array Mapping of lock types to the type actually used */
298 protected $lockTypeMap = array(
299 self
::LOCK_SH
=> self
::LOCK_SH
,
300 self
::LOCK_UW
=> self
::LOCK_SH
,
301 self
::LOCK_EX
=> self
::LOCK_EX
305 * @param $lockDb string
306 * @param $db DatabaseBase
308 protected function initConnection( $lockDb, DatabaseBase
$db ) {
309 # Let this transaction see lock rows from other transactions
310 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
314 * Get a connection to a lock DB and acquire locks on $paths.
315 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
317 * @see DBLockManager::getLocksOnServer()
320 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
321 $status = Status
::newGood();
323 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
324 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
325 # Build up values for INSERT clause
327 foreach ( $keys as $key ) {
328 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session
);
330 # Block new writers...
331 $db->insert( 'filelocks_shared', $data, __METHOD__
, array( 'IGNORE' ) );
332 # Actually do the locking queries...
333 if ( $type == self
::LOCK_SH
) { // reader locks
334 # Bail if there are any existing writers...
335 $blocked = $db->selectField( 'filelocks_exclusive', '1',
336 array( 'fle_key' => $keys ),
339 # Prospective writers that haven't yet updated filelocks_exclusive
340 # will recheck filelocks_shared after doing so and bail due to our entry.
341 } else { // writer locks
342 $encSession = $db->addQuotes( $this->session
);
343 # Bail if there are any existing writers...
344 # The may detect readers, but the safe check for them is below.
345 # Note: if two writers come at the same time, both bail :)
346 $blocked = $db->selectField( 'filelocks_shared', '1',
347 array( 'fls_key' => $keys, "fls_session != $encSession" ),
351 # Build up values for INSERT clause
353 foreach ( $keys as $key ) {
354 $data[] = array( 'fle_key' => $key );
356 # Block new readers/writers...
357 $db->insert( 'filelocks_exclusive', $data, __METHOD__
);
358 # Bail if there are any existing readers...
359 $blocked = $db->selectField( 'filelocks_shared', '1',
360 array( 'fls_key' => $keys, "fls_session != $encSession" ),
367 foreach ( $paths as $path ) {
368 $status->fatal( 'lockmanager-fail-acquirelock', $path );