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
24 use Wikimedia\Rdbms\Database
;
25 use Wikimedia\Rdbms\IDatabase
;
28 * Version of LockManager based on using named/row DB locks.
30 * This is meant for multi-wiki systems that may share files.
32 * All lock requests for a resource, identified by a hash string, will map to one bucket.
33 * Each bucket maps to one or several peer DBs, each on their own server.
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 abstract class DBLockManager
extends QuorumLockManager
{
42 /** @var array[]|IDatabase[] Map of (DB names => server config or IDatabase) */
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
49 /** @var IDatabase[] Map Database connections (DB name => Database) */
50 protected $conns = [];
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
60 * - type : DB type (mysql,postgres,...)
62 * - password : DB user password
63 * - tablePrefix : DB table prefix
64 * - flags : DB flags; bitfield of IDatabase::DBO_* constants
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 * - lockExpiry : Lock timeout (seconds) for dropped connections. [optional]
68 * This tells the DB server how long to wait before assuming
69 * connection failure and releasing all the locks for a session.
70 * - srvCache : A BagOStuff instance using APC or the like.
72 public function __construct( array $config ) {
73 parent
::__construct( $config );
75 $this->dbServers
= $config['dbServers'];
76 // Sanitize srvsByBucket config to prevent PHP errors
77 $this->srvsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
78 $this->srvsByBucket
= array_values( $this->srvsByBucket
); // consecutive
80 if ( isset( $config['lockExpiry'] ) ) {
81 $this->lockExpiry
= $config['lockExpiry'];
83 $met = ini_get( 'max_execution_time' );
84 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
86 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
87 ?
60 // pick a safe-ish number to match DB timeout default
88 : $this->lockExpiry
; // cover worst case
90 // Tracks peers that couldn't be queried recently to avoid lengthy
91 // connection timeouts. This is useless if each bucket has one peer.
92 $this->statusCache
= isset( $config['srvCache'] )
94 : new HashBagOStuff();
98 * @TODO change this code to work in one batch
99 * @param string $lockSrv
100 * @param array $pathsByType
101 * @return StatusValue
103 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
104 $status = StatusValue
::newGood();
105 foreach ( $pathsByType as $type => $paths ) {
106 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
112 abstract protected function doGetLocksOnServer( $lockSrv, array $paths, $type );
114 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
115 return StatusValue
::newGood();
119 * @see QuorumLockManager::isServerUp()
120 * @param string $lockSrv
123 protected function isServerUp( $lockSrv ) {
124 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
125 return false; // recent failure to connect
128 $this->getConnection( $lockSrv );
129 } catch ( DBError
$e ) {
130 $this->cacheRecordFailure( $lockSrv );
132 return false; // failed to connect
139 * Get (or reuse) a connection to a lock DB
141 * @param string $lockDb
144 * @throws UnexpectedValueException
146 protected function getConnection( $lockDb ) {
147 if ( !isset( $this->conns
[$lockDb] ) ) {
148 if ( $this->dbServers
[$lockDb] instanceof IDatabase
) {
149 // Direct injected connection hande for $lockDB
150 $db = $this->dbServers
[$lockDb];
151 } elseif ( is_array( $this->dbServers
[$lockDb] ) ) {
152 // Parameters to construct a new database connection
153 $config = $this->dbServers
[$lockDb];
154 $db = Database
::factory( $config['type'], $config );
156 throw new UnexpectedValueException( "No server called '$lockDb'." );
159 $db->clearFlag( DBO_TRX
);
160 # If the connection drops, try to avoid letting the DB rollback
161 # and release the locks before the file operations are finished.
162 # This won't handle the case of DB server restarts however.
164 if ( $this->lockExpiry
> 0 ) {
165 $options['connTimeout'] = $this->lockExpiry
;
167 $db->setSessionOptions( $options );
168 $this->initConnection( $lockDb, $db );
170 $this->conns
[$lockDb] = $db;
173 return $this->conns
[$lockDb];
177 * Do additional initialization for new lock DB connection
179 * @param string $lockDb
180 * @param IDatabase $db
183 protected function initConnection( $lockDb, IDatabase
$db ) {
187 * Checks if the DB has not recently had connection/query errors.
188 * This just avoids wasting time on doomed connection attempts.
190 * @param string $lockDb
193 protected function cacheCheckFailures( $lockDb ) {
194 return ( $this->safeDelay
> 0 )
195 ?
!$this->statusCache
->get( $this->getMissKey( $lockDb ) )
200 * Log a lock request failure to the cache
202 * @param string $lockDb
203 * @return bool Success
205 protected function cacheRecordFailure( $lockDb ) {
206 return ( $this->safeDelay
> 0 )
207 ?
$this->statusCache
->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay
)
212 * Get a cache key for recent query misses for a DB
214 * @param string $lockDb
217 protected function getMissKey( $lockDb ) {
218 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
222 * Make sure remaining locks get cleared for sanity
224 function __destruct() {
225 $this->releaseAllLocks();
226 foreach ( $this->conns
as $db ) {