Merge "Added another parser test for headings."
[lhc/web/wiklou.git] / includes / filerepo / backend / 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 locks.
26 * This is meant for multi-wiki systems that may share files.
27 * All locks are blocking, so it might be useful to set a small
28 * lock-wait timeout via server config to curtail deadlocks.
29 *
30 * All lock requests for a resource, identified by a hash string, will map
31 * to one bucket. Each bucket maps to one or several peer DBs, each on their
32 * own server, all having the filelocks.sql tables (with row-level locking).
33 * A majority of peer DBs must agree for a lock to be acquired.
34 *
35 * Caching is used to avoid hitting servers that are down.
36 *
37 * @ingroup LockManager
38 * @since 1.19
39 */
40 class DBLockManager extends QuorumLockManager {
41 /** @var Array Map of DB names to server config */
42 protected $dbServers; // (DB name => server config array)
43 /** @var BagOStuff */
44 protected $statusCache;
45
46 protected $lockExpiry; // integer number of seconds
47 protected $safeDelay; // integer number of seconds
48
49 protected $session = 0; // random integer
50 /** @var Array Map Database connections (DB name => Database) */
51 protected $conns = array();
52
53 /**
54 * Construct a new instance from configuration.
55 *
56 * $config paramaters include:
57 * 'dbServers' : Associative array of DB names to server configuration.
58 * Configuration is an associative array that includes:
59 * 'host' - DB server name
60 * 'dbname' - DB name
61 * 'type' - DB type (mysql,postgres,...)
62 * 'user' - DB user
63 * 'password' - DB user password
64 * 'tablePrefix' - DB table prefix
65 * 'flags' - DB flags (see DatabaseBase)
66 * 'dbsByBucket' : Array of 1-16 consecutive integer keys, starting from 0,
67 * each having an odd-numbered list of DB names (peers) as values.
68 * Any DB named 'localDBMaster' will automatically use the DB master
69 * settings for this wiki (without the need for a dbServers entry).
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 /**
114 * Get a connection to a lock DB and acquire locks on $paths.
115 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
116 *
117 * @see QuorumLockManager::getLocksOnServer()
118 * @return Status
119 */
120 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
121 $status = Status::newGood();
122
123 if ( $type == self::LOCK_EX ) { // writer locks
124 try {
125 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
126 # Build up values for INSERT clause
127 $data = array();
128 foreach ( $keys as $key ) {
129 $data[] = array( 'fle_key' => $key );
130 }
131 # Wait on any existing writers and block new ones if we get in
132 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
133 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
134 } catch ( DBError $e ) {
135 foreach ( $paths as $path ) {
136 $status->fatal( 'lockmanager-fail-acquirelock', $path );
137 }
138 }
139 }
140
141 return $status;
142 }
143
144 /**
145 * @see QuorumLockManager::freeLocksOnServer()
146 * @return Status
147 */
148 protected function freeLocksOnServer( $lockSrv, array $paths, $type ) {
149 return Status::newGood(); // not supported
150 }
151
152 /**
153 * @see QuorumLockManager::releaseAllLocks()
154 * @return Status
155 */
156 protected function releaseAllLocks() {
157 $status = Status::newGood();
158
159 foreach ( $this->conns as $lockDb => $db ) {
160 if ( $db->trxLevel() ) { // in transaction
161 try {
162 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
163 } catch ( DBError $e ) {
164 $status->fatal( 'lockmanager-fail-db-release', $lockDb );
165 }
166 }
167 }
168
169 return $status;
170 }
171
172 /**
173 * @see QuorumLockManager::isServerUp()
174 * @return bool
175 */
176 protected function isServerUp( $lockSrv ) {
177 if ( !$this->cacheCheckFailures( $lockSrv ) ) {
178 return false; // recent failure to connect
179 }
180 try {
181 $this->getConnection( $lockSrv );
182 } catch ( DBError $e ) {
183 $this->cacheRecordFailure( $lockSrv );
184 return false; // failed to connect
185 }
186 return true;
187 }
188
189 /**
190 * Get (or reuse) a connection to a lock DB
191 *
192 * @param $lockDb string
193 * @return DatabaseBase
194 * @throws DBError
195 */
196 protected function getConnection( $lockDb ) {
197 if ( !isset( $this->conns[$lockDb] ) ) {
198 $db = null;
199 if ( $lockDb === 'localDBMaster' ) {
200 $lb = wfGetLBFactory()->newMainLB();
201 $db = $lb->getConnection( DB_MASTER );
202 } elseif ( isset( $this->dbServers[$lockDb] ) ) {
203 $config = $this->dbServers[$lockDb];
204 $db = DatabaseBase::factory( $config['type'], $config );
205 }
206 if ( !$db ) {
207 return null; // config error?
208 }
209 $this->conns[$lockDb] = $db;
210 $this->conns[$lockDb]->clearFlag( DBO_TRX );
211 # If the connection drops, try to avoid letting the DB rollback
212 # and release the locks before the file operations are finished.
213 # This won't handle the case of DB server restarts however.
214 $options = array();
215 if ( $this->lockExpiry > 0 ) {
216 $options['connTimeout'] = $this->lockExpiry;
217 }
218 $this->conns[$lockDb]->setSessionOptions( $options );
219 $this->initConnection( $lockDb, $this->conns[$lockDb] );
220 }
221 if ( !$this->conns[$lockDb]->trxLevel() ) {
222 $this->conns[$lockDb]->begin( __METHOD__ ); // start transaction
223 }
224 return $this->conns[$lockDb];
225 }
226
227 /**
228 * Do additional initialization for new lock DB connection
229 *
230 * @param $lockDb string
231 * @param $db DatabaseBase
232 * @return void
233 * @throws DBError
234 */
235 protected function initConnection( $lockDb, DatabaseBase $db ) {}
236
237 /**
238 * Checks if the DB has not recently had connection/query errors.
239 * This just avoids wasting time on doomed connection attempts.
240 *
241 * @param $lockDb string
242 * @return bool
243 */
244 protected function cacheCheckFailures( $lockDb ) {
245 return ( $this->statusCache && $this->safeDelay > 0 )
246 ? !$this->statusCache->get( $this->getMissKey( $lockDb ) )
247 : true;
248 }
249
250 /**
251 * Log a lock request failure to the cache
252 *
253 * @param $lockDb string
254 * @return bool Success
255 */
256 protected function cacheRecordFailure( $lockDb ) {
257 return ( $this->statusCache && $this->safeDelay > 0 )
258 ? $this->statusCache->set( $this->getMissKey( $lockDb ), 1, $this->safeDelay )
259 : true;
260 }
261
262 /**
263 * Get a cache key for recent query misses for a DB
264 *
265 * @param $lockDb string
266 * @return string
267 */
268 protected function getMissKey( $lockDb ) {
269 $lockDb = ( $lockDb === 'localDBMaster' ) ? wfWikiID() : $lockDb; // non-relative
270 return 'dblockmanager:downservers:' . str_replace( ' ', '_', $lockDb );
271 }
272
273 /**
274 * Make sure remaining locks get cleared for sanity
275 */
276 function __destruct() {
277 foreach ( $this->conns as $db ) {
278 if ( $db->trxLevel() ) { // in transaction
279 try {
280 $db->rollback( __METHOD__ ); // finish transaction and kill any rows
281 } catch ( DBError $e ) {
282 // oh well
283 }
284 }
285 $db->close();
286 }
287 }
288 }
289
290 /**
291 * MySQL version of DBLockManager that supports shared locks.
292 * All locks are non-blocking, which avoids deadlocks.
293 *
294 * @ingroup LockManager
295 */
296 class MySqlLockManager extends DBLockManager {
297 /** @var Array Mapping of lock types to the type actually used */
298 protected $lockTypeMap = array(
299 self::LOCK_SH => self::LOCK_SH,
300 self::LOCK_UW => self::LOCK_SH,
301 self::LOCK_EX => self::LOCK_EX
302 );
303
304 /**
305 * @param $lockDb string
306 * @param $db DatabaseBase
307 */
308 protected function initConnection( $lockDb, DatabaseBase $db ) {
309 # Let this transaction see lock rows from other transactions
310 $db->query( "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;" );
311 }
312
313 /**
314 * Get a connection to a lock DB and acquire locks on $paths.
315 * This does not use GET_LOCK() per http://bugs.mysql.com/bug.php?id=1118.
316 *
317 * @see DBLockManager::getLocksOnServer()
318 * @return Status
319 */
320 protected function getLocksOnServer( $lockSrv, array $paths, $type ) {
321 $status = Status::newGood();
322
323 $db = $this->getConnection( $lockSrv ); // checked in isServerUp()
324 $keys = array_unique( array_map( 'LockManager::sha1Base36', $paths ) );
325 # Build up values for INSERT clause
326 $data = array();
327 foreach ( $keys as $key ) {
328 $data[] = array( 'fls_key' => $key, 'fls_session' => $this->session );
329 }
330 # Block new writers...
331 $db->insert( 'filelocks_shared', $data, __METHOD__, array( 'IGNORE' ) );
332 # Actually do the locking queries...
333 if ( $type == self::LOCK_SH ) { // reader locks
334 # Bail if there are any existing writers...
335 $blocked = $db->selectField( 'filelocks_exclusive', '1',
336 array( 'fle_key' => $keys ),
337 __METHOD__
338 );
339 # Prospective writers that haven't yet updated filelocks_exclusive
340 # will recheck filelocks_shared after doing so and bail due to our entry.
341 } else { // writer locks
342 $encSession = $db->addQuotes( $this->session );
343 # Bail if there are any existing writers...
344 # The may detect readers, but the safe check for them is below.
345 # Note: if two writers come at the same time, both bail :)
346 $blocked = $db->selectField( 'filelocks_shared', '1',
347 array( 'fls_key' => $keys, "fls_session != $encSession" ),
348 __METHOD__
349 );
350 if ( !$blocked ) {
351 # Build up values for INSERT clause
352 $data = array();
353 foreach ( $keys as $key ) {
354 $data[] = array( 'fle_key' => $key );
355 }
356 # Block new readers/writers...
357 $db->insert( 'filelocks_exclusive', $data, __METHOD__ );
358 # Bail if there are any existing readers...
359 $blocked = $db->selectField( 'filelocks_shared', '1',
360 array( 'fls_key' => $keys, "fls_session != $encSession" ),
361 __METHOD__
362 );
363 }
364 }
365
366 if ( $blocked ) {
367 foreach ( $paths as $path ) {
368 $status->fatal( 'lockmanager-fail-acquirelock', $path );
369 }
370 }
371
372 return $status;
373 }
374 }