Merge "resourceloader: Move queue formatting out of OutputPage"
[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 named/row DB locks.
26 *
27 * This is meant for multi-wiki systems that may share files.
28 *
29 * All lock requests for a resource, identified by a hash string, will map
30 * to one bucket. Each bucket maps to one or several peer DBs, each on their
31 * own server, all having the filelocks.sql tables (with row-level locking).
32 * A majority of peer DBs must agree for a lock to be acquired.
33 *
34 * Caching is used to avoid hitting servers that are down.
35 *
36 * @ingroup LockManager
37 * @since 1.19
38 */
39 abstract class DBLockManager extends QuorumLockManager {
40 /** @var array[] Map of DB names to server config */
41 protected $dbServers; // (DB name => server config array)
42 /** @var BagOStuff */
43 protected $statusCache;
44
45 protected $lockExpiry; // integer number of seconds
46 protected $safeDelay; // integer number of seconds
47
48 protected $session = 0; // random integer
49 /** @var IDatabase[] Map Database connections (DB name => Database) */
50 protected $conns = [];
51
52 /**
53 * Construct a new instance from configuration.
54 *
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
59 * - dbname : DB name
60 * - type : DB type (mysql,postgres,...)
61 * - user : DB user
62 * - password : DB user password
63 * - tablePrefix : DB table prefix
64 * - flags : DB flags (see DatabaseBase)
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 * Any DB named 'localDBMaster' will automatically use the DB master
68 * settings for this wiki (without the need for a dbServers entry).
69 * Only use 'localDBMaster' if the domain is a valid wiki ID.
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.
73 */
74 public function __construct( array $config ) {
75 parent::__construct( $config );
76
77 $this->dbServers = isset( $config['dbServers'] )
78 ? $config['dbServers']
79 : []; // likely just using 'localDBMaster'
80 // Sanitize srvsByBucket config to prevent PHP errors
81 $this->srvsByBucket = array_filter( $config['dbsByBucket'], 'is_array' );
82 $this->srvsByBucket = array_values( $this->srvsByBucket ); // consecutive
83
84 if ( isset( $config['lockExpiry'] ) ) {
85 $this->lockExpiry = $config['lockExpiry'];
86 } else {
87 $met = ini_get( 'max_execution_time' );
88 $this->lockExpiry = $met ? $met : 60; // use some sane amount if 0
89 }
90 $this->safeDelay = ( $this->lockExpiry <= 0 )
91 ? 60 // pick a safe-ish number to match DB timeout default
92 : $this->lockExpiry; // cover worst case
93
94 foreach ( $this->srvsByBucket as $bucket ) {
95 if ( count( $bucket ) > 1 ) { // multiple peers
96 // Tracks peers that couldn't be queried recently to avoid lengthy
97 // connection timeouts. This is useless if each bucket has one peer.
98 $this->statusCache = ObjectCache::getLocalServerInstance();
99 break;
100 }
101 }
102
103 $this->session = wfRandomString( 31 );
104 }
105
106 // @todo change this code to work in one batch
107 protected function getLocksOnServer( $lockSrv, array $pathsByType ) {
108 $status = Status::newGood();
109 foreach ( $pathsByType as $type => $paths ) {
110 $status->merge( $this->doGetLocksOnServer( $lockSrv, $paths, $type ) );
111 }
112
113 return $status;
114 }
115
116 abstract protected function doGetLocksOnServer( $lockSrv, array $paths, $type );
117
118 protected function freeLocksOnServer( $lockSrv, array $pathsByType ) {
119 return Status::newGood();
120 }
121
122 /**
123 * @see QuorumLockManager::isServerUp()
124 * @param string $lockSrv
125 * @return bool
126 */
127 protected function isServerUp( $lockSrv ) {
128 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
129 return false; // recent failure to connect
130 }
131 try {
132 $this->getConnection( $lockSrv );
133 } catch ( DBError $e ) {
134 $this->cacheRecordFailure( $lockSrv );
135
136 return false; // failed to connect
137 }
138
139 return true;
140 }
141
142 /**
143 * Get (or reuse) a connection to a lock DB
144 *
145 * @param string $lockDb
146 * @return IDatabase
147 * @throws DBError
148 */
149 protected function getConnection( $lockDb ) {
150 if ( !isset( $this->conns[$lockDb] ) ) {
151 $db = null;
152 if ( $lockDb === 'localDBMaster' ) {
153 $db = $this->getLocalLB()->getConnection( DB_MASTER, [], $this->domain );
154 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
155 $config = $this->dbServers[$lockDb];
156 $db = DatabaseBase::factory( $config['type'], $config );
157 }
158 if ( !$db ) {
159 return null; // config error?
160 }
161 $this->conns[$lockDb] = $db;
162 $this->conns[$lockDb]->clearFlag( DBO_TRX );
163 # If the connection drops, try to avoid letting the DB rollback
164 # and release the locks before the file operations are finished.
165 # This won't handle the case of DB server restarts however.
166 $options = [];
167 if ( $this->lockExpiry > 0 ) {
168 $options['connTimeout'] = $this->lockExpiry;
169 }
170 $this->conns[$lockDb]->setSessionOptions( $options );
171 $this->initConnection( $lockDb, $this->conns[$lockDb] );
172 }
173 if ( !$this->conns[$lockDb]->trxLevel() ) {
174 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
175 }
176
177 return $this->conns[$lockDb];
178 }
179
180 /**
181 * @return LoadBalancer
182 */
183 protected function getLocalLB() {
184 return wfGetLBFactory()->getMainLB( $this->domain );
185 }
186
187 /**
188 * Do additional initialization for new lock DB connection
189 *
190 * @param string $lockDb
191 * @param IDatabase $db
192 * @throws DBError
193 */
194 protected function initConnection( $lockDb, IDatabase $db ) {
195 }
196
197 /**
198 * Checks if the DB has not recently had connection/query errors.
199 * This just avoids wasting time on doomed connection attempts.
200 *
201 * @param string $lockDb
202 * @return bool
203 */
204 protected function cacheCheckFailures( $lockDb ) {
205 return ( $this->statusCache && $this->safeDelay > 0 )
206 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
207 : true;
208 }
209
210 /**
211 * Log a lock request failure to the cache
212 *
213 * @param string $lockDb
214 * @return bool Success
215 */
216 protected function cacheRecordFailure( $lockDb ) {
217 return ( $this->statusCache && $this->safeDelay > 0 )
218 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
219 : true;
220 }
221
222 /**
223 * Get a cache key for recent query misses for a DB
224 *
225 * @param string $lockDb
226 * @return string
227 */
228 protected function getMissKey( $lockDb ) {
229 $lockDb = ( $lockDb === 'localDBMaster' ) ? wfWikiID() : $lockDb; // non-relative
230 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
231 }
232
233 /**
234 * Make sure remaining locks get cleared for sanity
235 */
236 function __destruct() {
237 $this->releaseAllLocks();
238 foreach ( $this->conns as $db ) {
239 $db->close();
240 }
241 }
242 }
243
244 /**
245 * MySQL version of DBLockManager that supports shared locks.
246 * All locks are non-blocking, which avoids deadlocks.
247 *
248 * @ingroup LockManager
249 */
250 class MySqlLockManager extends DBLockManager {
251 /** @var array Mapping of lock types to the type actually used */
252 protected $lockTypeMap = [
253 self::LOCK_SH => self::LOCK_SH,
254 self::LOCK_UW => self::LOCK_SH,
255 self::LOCK_EX => self::LOCK_EX
256 ];
257
258 protected function getLocalLB() {
259 // Use a separate connection so releaseAllLocks() doesn't rollback the main trx
260 return wfGetLBFactory()->newMainLB( $this->domain );
261 }
262
263 protected function initConnection( $lockDb, IDatabase $db ) {
264 # Let this transaction see lock rows from other transactions
265 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
266 }
267
268 /**
269 * Get a connection to a lock DB and acquire locks on $paths.
270 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
271 *
272 * @see DBLockManager::getLocksOnServer()
273 * @param string $lockSrv
274 * @param array $paths
275 * @param string $type
276 * @return Status
277 */
278 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
279 $status = Status::newGood();
280
281 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
282
283 $keys = []; // list of hash keys for the paths
284 $data = []; // list of rows to insert
285 $checkEXKeys = []; // list of hash keys that this has no EX lock on
286 # Build up values for INSERT clause
287 foreach ( $paths as $path ) {
288 $key = $this->sha1Base36Absolute( $path );
289 $keys[] = $key;
290 $data[] = [ 'fls_key' => $key, 'fls_session' => $this->session ];
291 if ( !isset( $this->locksHeld[$path][self::LOCK_EX] ) ) {
292 $checkEXKeys[] = $key;
293 }
294 }
295
296 # Block new writers (both EX and SH locks leave entries here)...
297 $db->insert( 'filelocks_shared', $data, __METHOD__, [ 'IGNORE' ] );
298 # Actually do the locking queries...
299 if ( $type == self::LOCK_SH ) { // reader locks
300 $blocked = false;
301 # Bail if there are any existing writers...
302 if ( count( $checkEXKeys ) ) {
303 $blocked = $db->selectField( 'filelocks_exclusive', '1',
304 [ 'fle_key' => $checkEXKeys ],
305 __METHOD__
306 );
307 }
308 # Other prospective writers that haven't yet updated filelocks_exclusive
309 # will recheck filelocks_shared after doing so and bail due to this entry.
310 } else { // writer locks
311 $encSession = $db->addQuotes( $this->session );
312 # Bail if there are any existing writers...
313 # This may detect readers, but the safe check for them is below.
314 # Note: if two writers come at the same time, both bail :)
315 $blocked = $db->selectField( 'filelocks_shared', '1',
316 [ 'fls_key' => $keys, "fls_session != $encSession" ],
317 __METHOD__
318 );
319 if ( !$blocked ) {
320 # Build up values for INSERT clause
321 $data = [];
322 foreach ( $keys as $key ) {
323 $data[] = [ 'fle_key' => $key ];
324 }
325 # Block new readers/writers...
326 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
327 # Bail if there are any existing readers...
328 $blocked = $db->selectField( 'filelocks_shared', '1',
329 [ 'fls_key' => $keys, "fls_session != $encSession" ],
330 __METHOD__
331 );
332 }
333 }
334
335 if ( $blocked ) {
336 foreach ( $paths as $path ) {
337 $status->fatal( 'lockmanager-fail-acquirelock', $path );
338 }
339 }
340
341 return $status;
342 }
343
344 /**
345 * @see QuorumLockManager::releaseAllLocks()
346 * @return Status
347 */
348 protected function releaseAllLocks() {
349 $status = Status::newGood();
350
351 foreach ( $this->conns as $lockDb => $db ) {
352 if ( $db->trxLevel() ) { // in transaction
353 try {
354 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
355 } catch ( DBError $e ) {
356 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
357 }
358 }
359 }
360
361 return $status;
362 }
363 }
364
365 /**
366 * PostgreSQL version of DBLockManager that supports shared locks.
367 * All locks are non-blocking, which avoids deadlocks.
368 *
369 * @ingroup LockManager
370 */
371 class PostgreSqlLockManager extends DBLockManager {
372 /** @var array Mapping of lock types to the type actually used */
373 protected $lockTypeMap = [
374 self::LOCK_SH => self::LOCK_SH,
375 self::LOCK_UW => self::LOCK_SH,
376 self::LOCK_EX => self::LOCK_EX
377 ];
378
379 protected function doGetLocksOnServer( $lockSrv, array $paths, $type ) {
380 $status = Status::newGood();
381 if ( !count( $paths ) ) {
382 return $status; // nothing to lock
383 }
384
385 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
386 $bigints = array_unique( array_map(
387 function ( $key ) {
388 return Wikimedia\base_convert( substr( $key, 0, 15 ), 16, 10 );
389 },
390 array_map( [ $this, 'sha1Base16Absolute' ], $paths )
391 ) );
392
393 // Try to acquire all the locks...
394 $fields = [];
395 foreach ( $bigints as $bigint ) {
396 $fields[] = ( $type == self::LOCK_SH )
397 ? "pg_try_advisory_lock_shared({$db->addQuotes( $bigint )}) AS K$bigint"
398 : "pg_try_advisory_lock({$db->addQuotes( $bigint )}) AS K$bigint";
399 }
400 $res = $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
401 $row = $res->fetchRow();
402
403 if ( in_array( 'f', $row ) ) {
404 // Release any acquired locks if some could not be acquired...
405 $fields = [];
406 foreach ( $row as $kbigint => $ok ) {
407 if ( $ok === 't' ) { // locked
408 $bigint = substr( $kbigint, 1 ); // strip off the "K"
409 $fields[] = ( $type == self::LOCK_SH )
410 ? "pg_advisory_unlock_shared({$db->addQuotes( $bigint )})"
411 : "pg_advisory_unlock({$db->addQuotes( $bigint )})";
412 }
413 }
414 if ( count( $fields ) ) {
415 $db->query( 'SELECT ' . implode( ', ', $fields ), __METHOD__ );
416 }
417 foreach ( $paths as $path ) {
418 $status->fatal( 'lockmanager-fail-acquirelock', $path );
419 }
420 }
421
422 return $status;
423 }
424
425 /**
426 * @see QuorumLockManager::releaseAllLocks()
427 * @return Status
428 */
429 protected function releaseAllLocks() {
430 $status = Status::newGood();
431
432 foreach ( $this->conns as $lockDb => $db ) {
433 try {
434 $db->query( "SELECT pg_advisory_unlock_all()", __METHOD__ );
435 } catch ( DBError $e ) {
436 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
437 }
438 }
439
440 return $status;
441 }
442 }