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