phpcs: Normalize methods declarations to "[final abstract] [visibility]".
[lhc/web/wiklou.git] / includes / filebackend / lockmanager / DBLockManager.php
1 <?php
2 /**
3 * Version of LockManager based on using DB table locks.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup LockManager
22 */
23
24 /**
25 * Version of LockManager based on using DB table row locks.
26 *
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.
30 *
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.
35 *
36 * Caching is used to avoid hitting servers that are down.
37 *
38 * @ingroup LockManager
39 * @since 1.19
40 */
41 class DBLockManager extends QuorumLockManager {
42 /** @var Array Map of DB names to server config */
43 protected $dbServers; // (DB name => server config array)
44 /** @var BagOStuff */
45 protected $statusCache;
46
47 protected $lockExpiry; // integer number of seconds
48 protected $safeDelay; // integer number of seconds
49
50 protected $session = 0; // random integer
51 /** @var Array Map Database connections (DB name => Database) */
52 protected $conns = array();
53
54 /**
55 * Construct a new instance from configuration.
56 *
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
61 * - dbname : DB name
62 * - type : DB type (mysql,postgres,...)
63 * - user : DB user
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.
75 *
76 * @param Array $config
77 */
78 public function __construct( array $config ) {
79 parent::__construct( $config );
80
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
87
88 if ( isset( $config['lockExpiry'] ) ) {
89 $this->lockExpiry = $config['lockExpiry'];
90 } else {
91 $met = ini_get( 'max_execution_time' );
92 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
93 }
94 $this->safeDelay = ( $this->lockExpiry <= 0 )
95 ? 60 // pick a safe-ish number to match DB timeout default
96 : $this->lockExpiry; // cover worst case
97
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.
102 try {
103 $this->statusCache = ObjectCache::newAccelerator( array() );
104 } catch ( MWException $e ) {
105 trigger_error( __CLASS__ .
106 " using multiple DB peers without apc, xcache, or wincache." );
107 }
108 break;
109 }
110 }
111
112 $this->session = wfRandomString( 31 );
113 }
114
115 /**
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.
118 *
119 * @see QuorumLockManager::getLocksOnServer()
120 * @return Status
121 */
122 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
123 $status = Status::newGood();
124
125 if ( $type == self::LOCK_EX ) { // writer locks
126 try {
127 $keys = array_unique( array_map( array( $this, 'sha1Base36Absolute' ), $paths ) );
128 # Build up values for INSERT clause
129 $data = array();
130 foreach ( $keys as $key ) {
131 $data[] = array( 'fle_key' => $key );
132 }
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 );
139 }
140 }
141 }
142
143 return $status;
144 }
145
146 /**
147 * @see QuorumLockManager::freeLocksOnServer()
148 * @return Status
149 */
150 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
151 return Status::newGood(); // not supported
152 }
153
154 /**
155 * @see QuorumLockManager::releaseAllLocks()
156 * @return Status
157 */
158 protected function releaseAllLocks() {
159 $status = Status::newGood();
160
161 foreach ( $this->conns as $lockDb => $db ) {
162 if ( $db->trxLevel() ) { // in transaction
163 try {
164 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
165 } catch ( DBError $e ) {
166 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
167 }
168 }
169 }
170
171 return $status;
172 }
173
174 /**
175 * @see QuorumLockManager::isServerUp()
176 * @return bool
177 */
178 protected function isServerUp( $lockSrv ) {
179 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
180 return false; // recent failure to connect
181 }
182 try {
183 $this->getConnection( $lockSrv );
184 } catch ( DBError $e ) {
185 $this->cacheRecordFailure( $lockSrv );
186 return false; // failed to connect
187 }
188 return true;
189 }
190
191 /**
192 * Get (or reuse) a connection to a lock DB
193 *
194 * @param $lockDb string
195 * @return DatabaseBase
196 * @throws DBError
197 */
198 protected function getConnection( $lockDb ) {
199 if ( !isset( $this->conns[$lockDb] ) ) {
200 $db = null;
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 );
207 }
208 if ( !$db ) {
209 return null; // config error?
210 }
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.
216 $options = array();
217 if ( $this->lockExpiry > 0 ) {
218 $options['connTimeout'] = $this->lockExpiry;
219 }
220 $this->conns[$lockDb]->setSessionOptions( $options );
221 $this->initConnection( $lockDb, $this->conns[$lockDb] );
222 }
223 if ( !$this->conns[$lockDb]->trxLevel() ) {
224 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
225 }
226 return $this->conns[$lockDb];
227 }
228
229 /**
230 * Do additional initialization for new lock DB connection
231 *
232 * @param $lockDb string
233 * @param $db DatabaseBase
234 * @return void
235 * @throws DBError
236 */
237 protected function initConnection( $lockDb, DatabaseBase $db ) {}
238
239 /**
240 * Checks if the DB has not recently had connection/query errors.
241 * This just avoids wasting time on doomed connection attempts.
242 *
243 * @param $lockDb string
244 * @return bool
245 */
246 protected function cacheCheckFailures( $lockDb ) {
247 return ( $this->statusCache && $this->safeDelay > 0 )
248 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
249 : true;
250 }
251
252 /**
253 * Log a lock request failure to the cache
254 *
255 * @param $lockDb string
256 * @return bool Success
257 */
258 protected function cacheRecordFailure( $lockDb ) {
259 return ( $this->statusCache && $this->safeDelay > 0 )
260 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
261 : true;
262 }
263
264 /**
265 * Get a cache key for recent query misses for a DB
266 *
267 * @param $lockDb string
268 * @return string
269 */
270 protected function getMissKey( $lockDb ) {
271 $lockDb = ( $lockDb === 'localDBMaster' ) ? wfWikiID() : $lockDb; // non-relative
272 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
273 }
274
275 /**
276 * Make sure remaining locks get cleared for sanity
277 */
278 function __destruct() {
279 foreach ( $this->conns as $db ) {
280 if ( $db->trxLevel() ) { // in transaction
281 try {
282 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
283 } catch ( DBError $e ) {
284 // oh well
285 }
286 }
287 $db->close();
288 }
289 }
290 }
291
292 /**
293 * MySQL version of DBLockManager that supports shared locks.
294 * All locks are non-blocking, which avoids deadlocks.
295 *
296 * @ingroup LockManager
297 */
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
304 );
305
306 /**
307 * @param $lockDb string
308 * @param $db DatabaseBase
309 */
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;" );
313 }
314
315 /**
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.
318 *
319 * @see DBLockManager::getLocksOnServer()
320 * @return Status
321 */
322 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
323 $status = Status::newGood();
324
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
328 $data = array();
329 foreach ( $keys as $key ) {
330 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
331 }
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 ),
339 __METHOD__
340 );
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" ),
350 __METHOD__
351 );
352 if ( !$blocked ) {
353 # Build up values for INSERT clause
354 $data = array();
355 foreach ( $keys as $key ) {
356 $data[] = array( 'fle_key' => $key );
357 }
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" ),
363 __METHOD__
364 );
365 }
366 }
367
368 if ( $blocked ) {
369 foreach ( $paths as $path ) {
370 $status->fatal( 'lockmanager-fail-acquirelock', $path );
371 }
372 }
373
374 return $status;
375 }
376 }