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\IDatabase
;
27 * Version of LockManager based on using named/row DB locks.
29 * This is meant for multi-wiki systems that may share files.
31 * All lock requests for a resource, identified by a hash string, will map to one bucket.
32 * Each bucket maps to one or several peer DBs, each on their own server.
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 abstract class DBLockManager
extends QuorumLockManager
{
41 /** @var array[]|IDatabase[] Map of (DB names => server config or IDatabase) */
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
48 /** @var IDatabase[] Map Database connections (DB name => Database) */
49 protected $conns = [];
52 * Construct a new instance from configuration.
54 * @param array $config Parameters include:
55 * - dbServers : Associative array of DB names to server configuration.
56 * Configuration is an associative array that includes:
57 * - host : DB server name
59 * - type : DB type (mysql,postgres,...)
61 * - password : DB user password
62 * - tablePrefix : DB table prefix
63 * - flags : DB flags; bitfield of IDatabase::DBO_* constants
64 * - dbsByBucket : Array of 1-16 consecutive integer keys, starting from 0,
65 * each having an odd-numbered list of DB names (peers) as values.
66 * - lockExpiry : Lock timeout (seconds) for dropped connections. [optional]
67 * This tells the DB server how long to wait before assuming
68 * connection failure and releasing all the locks for a session.
69 * - srvCache : A BagOStuff instance using APC or the like.
71 public function __construct( array $config ) {
72 parent
::__construct( $config );
74 $this->dbServers
= $config['dbServers'];
75 // Sanitize srvsByBucket config to prevent PHP errors
76 $this->srvsByBucket
= array_filter( $config['dbsByBucket'], 'is_array' );
77 $this->srvsByBucket
= array_values( $this->srvsByBucket
); // consecutive
79 if ( isset( $config['lockExpiry'] ) ) {
80 $this->lockExpiry
= $config['lockExpiry'];
82 $met = ini_get( 'max_execution_time' );
83 $this->lockExpiry
= $met ?
$met : 60; // use some sane amount if 0
85 $this->safeDelay
= ( $this->lockExpiry
<= 0 )
86 ?
60 // pick a safe-ish number to match DB timeout default
87 : $this->lockExpiry
; // cover worst case
89 // Tracks peers that couldn't be queried recently to avoid lengthy
90 // connection timeouts. This is useless if each bucket has one peer.
91 $this->statusCache
= isset( $config['srvCache'] )
93 : new HashBagOStuff();
97 * @TODO change this code to work in one batch
98 * @param string $lockSrv
99 * @param array $pathsByType
100 * @return StatusValue
102 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
103 $status = StatusValue
::newGood();
104 foreach ( $pathsByType as $type => $paths ) {
105 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
111 abstract protected function doGetLocksOnServer( $lockSrv, array $paths, $type );
113 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
114 return StatusValue
::newGood();
118 * @see QuorumLockManager::isServerUp()
119 * @param string $lockSrv
122 protected function isServerUp( $lockSrv ) {
123 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
124 return false; // recent failure to connect
127 $this->getConnection( $lockSrv );
128 } catch ( DBError
$e ) {
129 $this->cacheRecordFailure( $lockSrv );
131 return false; // failed to connect
138 * Get (or reuse) a connection to a lock DB
140 * @param string $lockDb
143 * @throws UnexpectedValueException
145 protected function getConnection( $lockDb ) {
146 if ( !isset( $this->conns
[$lockDb] ) ) {
147 if ( $this->dbServers
[$lockDb] instanceof IDatabase
) {
148 // Direct injected connection hande for $lockDB
149 $db = $this->dbServers
[$lockDb];
150 } elseif ( is_array( $this->dbServers
[$lockDb] ) ) {
151 // Parameters to construct a new database connection
152 $config = $this->dbServers
[$lockDb];
153 $db = Database
::factory( $config['type'], $config );
155 throw new UnexpectedValueException( "No server called '$lockDb'." );
158 $db->clearFlag( DBO_TRX
);
159 # If the connection drops, try to avoid letting the DB rollback
160 # and release the locks before the file operations are finished.
161 # This won't handle the case of DB server restarts however.
163 if ( $this->lockExpiry
> 0 ) {
164 $options['connTimeout'] = $this->lockExpiry
;
166 $db->setSessionOptions( $options );
167 $this->initConnection( $lockDb, $db );
169 $this->conns
[$lockDb] = $db;
172 return $this->conns
[$lockDb];
176 * Do additional initialization for new lock DB connection
178 * @param string $lockDb
179 * @param IDatabase $db
182 protected function initConnection( $lockDb, IDatabase
$db ) {
186 * Checks if the DB has not recently had connection/query errors.
187 * This just avoids wasting time on doomed connection attempts.
189 * @param string $lockDb
192 protected function cacheCheckFailures( $lockDb ) {
193 return ( $this->safeDelay
> 0 )
194 ?
!$this->statusCache
->get( $this->getMissKey( $lockDb ) )
199 * Log a lock request failure to the cache
201 * @param string $lockDb
202 * @return bool Success
204 protected function cacheRecordFailure( $lockDb ) {
205 return ( $this->safeDelay
> 0 )
206 ?
$this->statusCache
->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay
)
211 * Get a cache key for recent query misses for a DB
213 * @param string $lockDb
216 protected function getMissKey( $lockDb ) {
217 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
221 * Make sure remaining locks get cleared for sanity
223 function __destruct() {
224 $this->releaseAllLocks();
225 foreach ( $this->conns
as $db ) {