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