Merge "Allow easy suppression of multiple deleted revs"
[lhc/web/wiklou.git] / includes / db / loadbalancer / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing.
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 Database
22 */
23
24 /**
25 * Database load balancing object
26 *
27 * @todo document
28 * @ingroup Database
29 */
30 class LoadBalancer {
31 /** @var array[] Map of (server index => server config array) */
32 private $mServers;
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
34 private $mConns;
35 /** @var array Map of (server index => weight) */
36 private $mLoads;
37 /** @var array[] Map of (group => server index => weight) */
38 private $mGroupLoads;
39 /** @var bool Whether to disregard slave lag as a factor in slave selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on slave lag to resolve */
42 private $mWaitTimeout;
43 /** @var array LBFactory information */
44 private $mParentInfo;
45
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
50 /** @var BagOStuff */
51 private $srvCache;
52
53 /** @var bool|DatabaseBase Database connection that caused a problem */
54 private $mErrorConnection;
55 /** @var integer The generic (not query grouped) slave index (of $mServers) */
56 private $mReadIndex;
57 /** @var bool|DBMasterPos False if not set */
58 private $mWaitForPos;
59 /** @var bool Whether the generic reader fell back to a lagged slave */
60 private $laggedSlaveMode = false;
61 /** @var bool Whether the generic reader fell back to a lagged slave */
62 private $slavesDownMode = false;
63 /** @var string The last DB selection or connection error */
64 private $mLastError = 'Unknown error';
65 /** @var string|bool Reason the LB is read-only or false if not */
66 private $readOnlyReason = false;
67 /** @var integer Total connections opened */
68 private $connsOpened = 0;
69
70 /** @var TransactionProfiler */
71 protected $trxProfiler;
72
73 /** @var integer Warn when this many connection are held */
74 const CONN_HELD_WARN_THRESHOLD = 10;
75 /** @var integer Default 'max lag' when unspecified */
76 const MAX_LAG = 10;
77 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
78 const POS_WAIT_TIMEOUT = 10;
79
80 /**
81 * @param array $params Array with keys:
82 * - servers : Required. Array of server info structures.
83 * - loadMonitor : Name of a class used to fetch server lag and load.
84 * - readOnlyReason : Reason the master DB is read-only if so [optional]
85 * @throws MWException
86 */
87 public function __construct( array $params ) {
88 if ( !isset( $params['servers'] ) ) {
89 throw new MWException( __CLASS__ . ': missing servers parameter' );
90 }
91 $this->mServers = $params['servers'];
92 $this->mWaitTimeout = self::POS_WAIT_TIMEOUT;
93
94 $this->mReadIndex = -1;
95 $this->mWriteIndex = -1;
96 $this->mConns = array(
97 'local' => array(),
98 'foreignUsed' => array(),
99 'foreignFree' => array() );
100 $this->mLoads = array();
101 $this->mWaitForPos = false;
102 $this->mErrorConnection = false;
103 $this->mAllowLagged = false;
104
105 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
106 $this->readOnlyReason = $params['readOnlyReason'];
107 }
108
109 if ( isset( $params['loadMonitor'] ) ) {
110 $this->mLoadMonitorClass = $params['loadMonitor'];
111 } else {
112 $master = reset( $params['servers'] );
113 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
114 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
115 } else {
116 $this->mLoadMonitorClass = 'LoadMonitorNull';
117 }
118 }
119
120 foreach ( $params['servers'] as $i => $server ) {
121 $this->mLoads[$i] = $server['load'];
122 if ( isset( $server['groupLoads'] ) ) {
123 foreach ( $server['groupLoads'] as $group => $ratio ) {
124 if ( !isset( $this->mGroupLoads[$group] ) ) {
125 $this->mGroupLoads[$group] = array();
126 }
127 $this->mGroupLoads[$group][$i] = $ratio;
128 }
129 }
130 }
131
132 $this->srvCache = ObjectCache::getLocalServerInstance();
133
134 if ( isset( $params['trxProfiler'] ) ) {
135 $this->trxProfiler = $params['trxProfiler'];
136 } else {
137 $this->trxProfiler = new TransactionProfiler();
138 }
139 }
140
141 /**
142 * Get a LoadMonitor instance
143 *
144 * @return LoadMonitor
145 */
146 private function getLoadMonitor() {
147 if ( !isset( $this->mLoadMonitor ) ) {
148 $class = $this->mLoadMonitorClass;
149 $this->mLoadMonitor = new $class( $this );
150 }
151
152 return $this->mLoadMonitor;
153 }
154
155 /**
156 * Get or set arbitrary data used by the parent object, usually an LBFactory
157 * @param mixed $x
158 * @return mixed
159 */
160 public function parentInfo( $x = null ) {
161 return wfSetVar( $this->mParentInfo, $x );
162 }
163
164 /**
165 * Given an array of non-normalised probabilities, this function will select
166 * an element and return the appropriate key
167 *
168 * @deprecated since 1.21, use ArrayUtils::pickRandom()
169 *
170 * @param array $weights
171 * @return bool|int|string
172 */
173 public function pickRandom( array $weights ) {
174 return ArrayUtils::pickRandom( $weights );
175 }
176
177 /**
178 * @param array $loads
179 * @param bool|string $wiki Wiki to get non-lagged for
180 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
181 * @return bool|int|string
182 */
183 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self::MAX_LAG ) {
184 $lags = $this->getLagTimes( $wiki );
185
186 # Unset excessively lagged servers
187 foreach ( $lags as $i => $lag ) {
188 if ( $i != 0 ) {
189 $maxServerLag = $maxLag;
190 if ( isset( $this->mServers[$i]['max lag'] ) ) {
191 $maxServerLag = min( $maxServerLag, $this->mServers[$i]['max lag'] );
192 }
193
194 $host = $this->getServerName( $i );
195 if ( $lag === false ) {
196 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
197 unset( $loads[$i] );
198 } elseif ( $lag > $maxServerLag ) {
199 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
200 unset( $loads[$i] );
201 }
202 }
203 }
204
205 # Find out if all the slaves with non-zero load are lagged
206 $sum = 0;
207 foreach ( $loads as $load ) {
208 $sum += $load;
209 }
210 if ( $sum == 0 ) {
211 # No appropriate DB servers except maybe the master and some slaves with zero load
212 # Do NOT use the master
213 # Instead, this function will return false, triggering read-only mode,
214 # and a lagged slave will be used instead.
215 return false;
216 }
217
218 if ( count( $loads ) == 0 ) {
219 return false;
220 }
221
222 # Return a random representative of the remainder
223 return ArrayUtils::pickRandom( $loads );
224 }
225
226 /**
227 * Get the index of the reader connection, which may be a slave
228 * This takes into account load ratios and lag times. It should
229 * always return a consistent index during a given invocation
230 *
231 * Side effect: opens connections to databases
232 * @param string|bool $group Query group, or false for the generic reader
233 * @param string|bool $wiki Wiki ID, or false for the current wiki
234 * @throws MWException
235 * @return bool|int|string
236 */
237 public function getReaderIndex( $group = false, $wiki = false ) {
238 global $wgDBtype;
239
240 # @todo FIXME: For now, only go through all this for mysql databases
241 if ( $wgDBtype != 'mysql' ) {
242 return $this->getWriterIndex();
243 }
244
245 if ( count( $this->mServers ) == 1 ) {
246 # Skip the load balancing if there's only one server
247 return 0;
248 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
249 # Shortcut if generic reader exists already
250 return $this->mReadIndex;
251 }
252
253 # Find the relevant load array
254 if ( $group !== false ) {
255 if ( isset( $this->mGroupLoads[$group] ) ) {
256 $nonErrorLoads = $this->mGroupLoads[$group];
257 } else {
258 # No loads for this group, return false and the caller can use some other group
259 wfDebugLog( 'connect', __METHOD__ . ": no loads for group $group\n" );
260
261 return false;
262 }
263 } else {
264 $nonErrorLoads = $this->mLoads;
265 }
266
267 if ( !count( $nonErrorLoads ) ) {
268 throw new MWException( "Empty server array given to LoadBalancer" );
269 }
270
271 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
272 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
273
274 $laggedSlaveMode = false;
275
276 # No server found yet
277 $i = false;
278 $conn = false;
279 # First try quickly looking through the available servers for a server that
280 # meets our criteria
281 $currentLoads = $nonErrorLoads;
282 while ( count( $currentLoads ) ) {
283 if ( $this->mAllowLagged || $laggedSlaveMode ) {
284 $i = ArrayUtils::pickRandom( $currentLoads );
285 } else {
286 $i = false;
287 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
288 # ChronologyProtecter causes mWaitForPos to be set via sessions.
289 # This triggers doWait() after connect, so it's especially good to
290 # avoid lagged servers so as to avoid just blocking in that method.
291 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
292 # Aim for <= 1 second of waiting (being too picky can backfire)
293 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
294 }
295 if ( $i === false ) {
296 # Any server with less lag than it's 'max lag' param is preferable
297 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
298 }
299 if ( $i === false && count( $currentLoads ) != 0 ) {
300 # All slaves lagged. Switch to read-only mode
301 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
302 $i = ArrayUtils::pickRandom( $currentLoads );
303 $laggedSlaveMode = true;
304 }
305 }
306
307 if ( $i === false ) {
308 # pickRandom() returned false
309 # This is permanent and means the configuration or the load monitor
310 # wants us to return false.
311 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
312
313 return false;
314 }
315
316 $serverName = $this->getServerName( $i );
317 wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: $serverName..." );
318
319 $conn = $this->openConnection( $i, $wiki );
320 if ( !$conn ) {
321 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
322 unset( $nonErrorLoads[$i] );
323 unset( $currentLoads[$i] );
324 $i = false;
325 continue;
326 }
327
328 // Decrement reference counter, we are finished with this connection.
329 // It will be incremented for the caller later.
330 if ( $wiki !== false ) {
331 $this->reuseConnection( $conn );
332 }
333
334 # Return this server
335 break;
336 }
337
338 # If all servers were down, quit now
339 if ( !count( $nonErrorLoads ) ) {
340 wfDebugLog( 'connect', "All servers down" );
341 }
342
343 if ( $i !== false ) {
344 # Slave connection successful
345 # Wait for the session master pos for a short time
346 if ( $this->mWaitForPos && $i > 0 ) {
347 if ( !$this->doWait( $i ) ) {
348 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
349 }
350 }
351 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
352 $this->mReadIndex = $i;
353 # Record if the generic reader index is in "lagged slave" mode
354 if ( $laggedSlaveMode ) {
355 $this->laggedSlaveMode = true;
356 }
357 }
358 $serverName = $this->getServerName( $i );
359 wfDebugLog( 'connect', __METHOD__ .
360 ": using server $serverName for group '$group'\n" );
361 }
362
363 return $i;
364 }
365
366 /**
367 * Set the master wait position
368 * If a DB_SLAVE connection has been opened already, waits
369 * Otherwise sets a variable telling it to wait if such a connection is opened
370 * @param DBMasterPos $pos
371 */
372 public function waitFor( $pos ) {
373 $this->mWaitForPos = $pos;
374 $i = $this->mReadIndex;
375
376 if ( $i > 0 ) {
377 if ( !$this->doWait( $i ) ) {
378 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
379 $this->laggedSlaveMode = true;
380 }
381 }
382 }
383
384 /**
385 * Set the master wait position and wait for a "generic" slave to catch up to it
386 *
387 * This can be used a faster proxy for waitForAll()
388 *
389 * @param DBMasterPos $pos
390 * @param int $timeout Max seconds to wait; default is mWaitTimeout
391 * @return bool Success (able to connect and no timeouts reached)
392 * @since 1.26
393 */
394 public function waitForOne( $pos, $timeout = null ) {
395 $this->mWaitForPos = $pos;
396
397 $i = $this->mReadIndex;
398 if ( $i <= 0 ) {
399 // Pick a generic slave if there isn't one yet
400 $readLoads = $this->mLoads;
401 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
402 $readLoads = array_filter( $readLoads ); // with non-zero load
403 $i = ArrayUtils::pickRandom( $readLoads );
404 }
405
406 if ( $i > 0 ) {
407 $ok = $this->doWait( $i, true, $timeout );
408 } else {
409 $ok = true; // no applicable loads
410 }
411
412 return $ok;
413 }
414
415 /**
416 * Set the master wait position and wait for ALL slaves to catch up to it
417 * @param DBMasterPos $pos
418 * @param int $timeout Max seconds to wait; default is mWaitTimeout
419 * @return bool Success (able to connect and no timeouts reached)
420 */
421 public function waitForAll( $pos, $timeout = null ) {
422 $this->mWaitForPos = $pos;
423 $serverCount = count( $this->mServers );
424
425 $ok = true;
426 for ( $i = 1; $i < $serverCount; $i++ ) {
427 if ( $this->mLoads[$i] > 0 ) {
428 $ok = $this->doWait( $i, true, $timeout ) && $ok;
429 }
430 }
431
432 return $ok;
433 }
434
435 /**
436 * Get any open connection to a given server index, local or foreign
437 * Returns false if there is no connection open
438 *
439 * @param int $i
440 * @return DatabaseBase|bool False on failure
441 */
442 public function getAnyOpenConnection( $i ) {
443 foreach ( $this->mConns as $conns ) {
444 if ( !empty( $conns[$i] ) ) {
445 return reset( $conns[$i] );
446 }
447 }
448
449 return false;
450 }
451
452 /**
453 * Wait for a given slave to catch up to the master pos stored in $this
454 * @param int $index Server index
455 * @param bool $open Check the server even if a new connection has to be made
456 * @param int $timeout Max seconds to wait; default is mWaitTimeout
457 * @return bool
458 */
459 protected function doWait( $index, $open = false, $timeout = null ) {
460 $close = false; // close the connection afterwards
461
462 // Check if we already know that the DB has reached this point
463 $server = $this->getServerName( $index );
464 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
465 /** @var DBMasterPos $knownReachedPos */
466 $knownReachedPos = $this->srvCache->get( $key );
467 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
468 wfDebugLog( 'replication', __METHOD__ .
469 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
470 return true;
471 }
472
473 // Find a connection to wait on, creating one if needed and allowed
474 $conn = $this->getAnyOpenConnection( $index );
475 if ( !$conn ) {
476 if ( !$open ) {
477 wfDebugLog( 'replication', __METHOD__ . ": no connection open for $server\n" );
478
479 return false;
480 } else {
481 $conn = $this->openConnection( $index, '' );
482 if ( !$conn ) {
483 wfDebugLog( 'replication', __METHOD__ . ": failed to connect to $server\n" );
484
485 return false;
486 }
487 // Avoid connection spam in waitForAll() when connections
488 // are made just for the sake of doing this lag check.
489 $close = true;
490 }
491 }
492
493 wfDebugLog( 'replication', __METHOD__ . ": Waiting for slave $server to catch up...\n" );
494 $timeout = $timeout ?: $this->mWaitTimeout;
495 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
496
497 if ( $result == -1 || is_null( $result ) ) {
498 // Timed out waiting for slave, use master instead
499 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
500 wfDebugLog( 'replication', "$msg\n" );
501 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
502 $ok = false;
503 } else {
504 wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
505 $ok = true;
506 // Remember that the DB reached this point
507 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
508 }
509
510 if ( $close ) {
511 $this->closeConnection( $conn );
512 }
513
514 return $ok;
515 }
516
517 /**
518 * Get a connection by index
519 * This is the main entry point for this class.
520 *
521 * @param int $i Server index
522 * @param array|string|bool $groups Query group(s), or false for the generic reader
523 * @param string|bool $wiki Wiki ID, or false for the current wiki
524 *
525 * @throws MWException
526 * @return DatabaseBase
527 */
528 public function getConnection( $i, $groups = array(), $wiki = false ) {
529 if ( $i === null || $i === false ) {
530 throw new MWException( 'Attempt to call ' . __METHOD__ .
531 ' with invalid server index' );
532 }
533
534 if ( $wiki === wfWikiID() ) {
535 $wiki = false;
536 }
537
538 $groups = ( $groups === false || $groups === array() )
539 ? array( false ) // check one "group": the generic pool
540 : (array)$groups;
541
542 $masterOnly = ( $i == DB_MASTER || $i == $this->getWriterIndex() );
543 $oldConnsOpened = $this->connsOpened; // connections open now
544
545 if ( $i == DB_MASTER ) {
546 $i = $this->getWriterIndex();
547 } else {
548 # Try to find an available server in any the query groups (in order)
549 foreach ( $groups as $group ) {
550 $groupIndex = $this->getReaderIndex( $group, $wiki );
551 if ( $groupIndex !== false ) {
552 $i = $groupIndex;
553 break;
554 }
555 }
556 }
557
558 # Operation-based index
559 if ( $i == DB_SLAVE ) {
560 $this->mLastError = 'Unknown error'; // reset error string
561 # Try the general server pool if $groups are unavailable.
562 $i = in_array( false, $groups, true )
563 ? false // don't bother with this if that is what was tried above
564 : $this->getReaderIndex( false, $wiki );
565 # Couldn't find a working server in getReaderIndex()?
566 if ( $i === false ) {
567 $this->mLastError = 'No working slave server: ' . $this->mLastError;
568
569 return $this->reportConnectionError();
570 }
571 }
572
573 # Now we have an explicit index into the servers array
574 $conn = $this->openConnection( $i, $wiki );
575 if ( !$conn ) {
576 return $this->reportConnectionError();
577 }
578
579 # Profile any new connections that happen
580 if ( $this->connsOpened > $oldConnsOpened ) {
581 $host = $conn->getServer();
582 $dbname = $conn->getDBname();
583 $trxProf = Profiler::instance()->getTransactionProfiler();
584 $trxProf->recordConnection( $host, $dbname, $masterOnly );
585 }
586
587 if ( $masterOnly ) {
588 # Make master-requested DB handles inherit any read-only mode setting
589 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
590 }
591
592 return $conn;
593 }
594
595 /**
596 * Mark a foreign connection as being available for reuse under a different
597 * DB name or prefix. This mechanism is reference-counted, and must be called
598 * the same number of times as getConnection() to work.
599 *
600 * @param DatabaseBase $conn
601 * @throws MWException
602 */
603 public function reuseConnection( $conn ) {
604 $serverIndex = $conn->getLBInfo( 'serverIndex' );
605 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
606 if ( $serverIndex === null || $refCount === null ) {
607 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
608 /**
609 * This can happen in code like:
610 * foreach ( $dbs as $db ) {
611 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
612 * ...
613 * $lb->reuseConnection( $conn );
614 * }
615 * When a connection to the local DB is opened in this way, reuseConnection()
616 * should be ignored
617 */
618 return;
619 }
620
621 $dbName = $conn->getDBname();
622 $prefix = $conn->tablePrefix();
623 if ( strval( $prefix ) !== '' ) {
624 $wiki = "$dbName-$prefix";
625 } else {
626 $wiki = $dbName;
627 }
628 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
629 throw new MWException( __METHOD__ . ": connection not found, has " .
630 "the connection been freed already?" );
631 }
632 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
633 if ( $refCount <= 0 ) {
634 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
635 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
636 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
637 } else {
638 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
639 }
640 }
641
642 /**
643 * Get a database connection handle reference
644 *
645 * The handle's methods wrap simply wrap those of a DatabaseBase handle
646 *
647 * @see LoadBalancer::getConnection() for parameter information
648 *
649 * @param int $db
650 * @param array|string|bool $groups Query group(s), or false for the generic reader
651 * @param string|bool $wiki Wiki ID, or false for the current wiki
652 * @return DBConnRef
653 */
654 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
655 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
656 }
657
658 /**
659 * Get a database connection handle reference without connecting yet
660 *
661 * The handle's methods wrap simply wrap those of a DatabaseBase handle
662 *
663 * @see LoadBalancer::getConnection() for parameter information
664 *
665 * @param int $db
666 * @param array|string|bool $groups Query group(s), or false for the generic reader
667 * @param string|bool $wiki Wiki ID, or false for the current wiki
668 * @return DBConnRef
669 */
670 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
671 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
672 }
673
674 /**
675 * Open a connection to the server given by the specified index
676 * Index must be an actual index into the array.
677 * If the server is already open, returns it.
678 *
679 * On error, returns false, and the connection which caused the
680 * error will be available via $this->mErrorConnection.
681 *
682 * @param int $i Server index
683 * @param string|bool $wiki Wiki ID, or false for the current wiki
684 * @return DatabaseBase|bool Returns false on errors
685 */
686 public function openConnection( $i, $wiki = false ) {
687 if ( $wiki !== false ) {
688 $conn = $this->openForeignConnection( $i, $wiki );
689 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
690 $conn = $this->mConns['local'][$i][0];
691 } else {
692 $server = $this->mServers[$i];
693 $server['serverIndex'] = $i;
694 $conn = $this->reallyOpenConnection( $server, false );
695 $serverName = $this->getServerName( $i );
696 if ( $conn->isOpen() ) {
697 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
698 $this->mConns['local'][$i][0] = $conn;
699 } else {
700 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
701 $this->mErrorConnection = $conn;
702 $conn = false;
703 }
704 }
705
706 if ( $conn && !$conn->isOpen() ) {
707 // Connection was made but later unrecoverably lost for some reason.
708 // Do not return a handle that will just throw exceptions on use,
709 // but let the calling code (e.g. getReaderIndex) try another server.
710 // See DatabaseMyslBase::ping() for how this can happen.
711 $this->mErrorConnection = $conn;
712 $conn = false;
713 }
714
715 return $conn;
716 }
717
718 /**
719 * Open a connection to a foreign DB, or return one if it is already open.
720 *
721 * Increments a reference count on the returned connection which locks the
722 * connection to the requested wiki. This reference count can be
723 * decremented by calling reuseConnection().
724 *
725 * If a connection is open to the appropriate server already, but with the wrong
726 * database, it will be switched to the right database and returned, as long as
727 * it has been freed first with reuseConnection().
728 *
729 * On error, returns false, and the connection which caused the
730 * error will be available via $this->mErrorConnection.
731 *
732 * @param int $i Server index
733 * @param string $wiki Wiki ID to open
734 * @return DatabaseBase
735 */
736 private function openForeignConnection( $i, $wiki ) {
737 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
738 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
739 // Reuse an already-used connection
740 $conn = $this->mConns['foreignUsed'][$i][$wiki];
741 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
742 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
743 // Reuse a free connection for the same wiki
744 $conn = $this->mConns['foreignFree'][$i][$wiki];
745 unset( $this->mConns['foreignFree'][$i][$wiki] );
746 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
747 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
748 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
749 // Reuse a connection from another wiki
750 $conn = reset( $this->mConns['foreignFree'][$i] );
751 $oldWiki = key( $this->mConns['foreignFree'][$i] );
752
753 // The empty string as a DB name means "don't care".
754 // DatabaseMysqlBase::open() already handle this on connection.
755 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
756 $this->mLastError = "Error selecting database $dbName on server " .
757 $conn->getServer() . " from client host " . wfHostname() . "\n";
758 $this->mErrorConnection = $conn;
759 $conn = false;
760 } else {
761 $conn->tablePrefix( $prefix );
762 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
763 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
764 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
765 }
766 } else {
767 // Open a new connection
768 $server = $this->mServers[$i];
769 $server['serverIndex'] = $i;
770 $server['foreignPoolRefCount'] = 0;
771 $server['foreign'] = true;
772 $conn = $this->reallyOpenConnection( $server, $dbName );
773 if ( !$conn->isOpen() ) {
774 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
775 $this->mErrorConnection = $conn;
776 $conn = false;
777 } else {
778 $conn->tablePrefix( $prefix );
779 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
780 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
781 }
782 }
783
784 // Increment reference count
785 if ( $conn ) {
786 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
787 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
788 }
789
790 return $conn;
791 }
792
793 /**
794 * Test if the specified index represents an open connection
795 *
796 * @param int $index Server index
797 * @access private
798 * @return bool
799 */
800 private function isOpen( $index ) {
801 if ( !is_integer( $index ) ) {
802 return false;
803 }
804
805 return (bool)$this->getAnyOpenConnection( $index );
806 }
807
808 /**
809 * Really opens a connection. Uncached.
810 * Returns a Database object whether or not the connection was successful.
811 * @access private
812 *
813 * @param array $server
814 * @param bool $dbNameOverride
815 * @throws MWException
816 * @return DatabaseBase
817 */
818 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
819 if ( !is_array( $server ) ) {
820 throw new MWException( 'You must update your load-balancing configuration. ' .
821 'See DefaultSettings.php entry for $wgDBservers.' );
822 }
823
824 if ( $dbNameOverride !== false ) {
825 $server['dbname'] = $dbNameOverride;
826 }
827
828 // Let the handle know what the cluster master is (e.g. "db1052")
829 $masterName = $this->getServerName( 0 );
830 $server['clusterMasterHost'] = $masterName;
831
832 // Log when many connection are made on requests
833 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
834 wfDebugLog( 'DBPerformance', __METHOD__ . ": " .
835 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
836 wfBacktrace( true ) );
837 }
838
839 # Create object
840 try {
841 $db = DatabaseBase::factory( $server['type'], $server );
842 } catch ( DBConnectionError $e ) {
843 // FIXME: This is probably the ugliest thing I have ever done to
844 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
845 $db = $e->db;
846 }
847
848 $db->setLBInfo( $server );
849 $db->setLazyMasterHandle(
850 $this->getLazyConnectionRef( DB_MASTER, array(), $db->getWikiID() )
851 );
852 $db->setTransactionProfiler( $this->trxProfiler );
853
854 return $db;
855 }
856
857 /**
858 * @throws DBConnectionError
859 * @return bool
860 */
861 private function reportConnectionError() {
862 $conn = $this->mErrorConnection; // The connection which caused the error
863 $context = array(
864 'method' => __METHOD__,
865 'last_error' => $this->mLastError,
866 );
867
868 if ( !is_object( $conn ) ) {
869 // No last connection, probably due to all servers being too busy
870 wfLogDBError(
871 "LB failure with no last connection. Connection error: {last_error}",
872 $context
873 );
874
875 // If all servers were busy, mLastError will contain something sensible
876 throw new DBConnectionError( null, $this->mLastError );
877 } else {
878 $context['db_server'] = $conn->getProperty( 'mServer' );
879 wfLogDBError(
880 "Connection error: {last_error} ({db_server})",
881 $context
882 );
883
884 // throws DBConnectionError
885 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
886 }
887
888 return false; /* not reached */
889 }
890
891 /**
892 * @return int
893 * @since 1.26
894 */
895 public function getWriterIndex() {
896 return 0;
897 }
898
899 /**
900 * Returns true if the specified index is a valid server index
901 *
902 * @param string $i
903 * @return bool
904 */
905 public function haveIndex( $i ) {
906 return array_key_exists( $i, $this->mServers );
907 }
908
909 /**
910 * Returns true if the specified index is valid and has non-zero load
911 *
912 * @param string $i
913 * @return bool
914 */
915 public function isNonZeroLoad( $i ) {
916 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
917 }
918
919 /**
920 * Get the number of defined servers (not the number of open connections)
921 *
922 * @return int
923 */
924 public function getServerCount() {
925 return count( $this->mServers );
926 }
927
928 /**
929 * Get the host name or IP address of the server with the specified index
930 * Prefer a readable name if available.
931 * @param string $i
932 * @return string
933 */
934 public function getServerName( $i ) {
935 if ( isset( $this->mServers[$i]['hostName'] ) ) {
936 $name = $this->mServers[$i]['hostName'];
937 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
938 $name = $this->mServers[$i]['host'];
939 } else {
940 $name = '';
941 }
942
943 return ( $name != '' ) ? $name : 'localhost';
944 }
945
946 /**
947 * Return the server info structure for a given index, or false if the index is invalid.
948 * @param int $i
949 * @return array|bool
950 */
951 public function getServerInfo( $i ) {
952 if ( isset( $this->mServers[$i] ) ) {
953 return $this->mServers[$i];
954 } else {
955 return false;
956 }
957 }
958
959 /**
960 * Sets the server info structure for the given index. Entry at index $i
961 * is created if it doesn't exist
962 * @param int $i
963 * @param array $serverInfo
964 */
965 public function setServerInfo( $i, array $serverInfo ) {
966 $this->mServers[$i] = $serverInfo;
967 }
968
969 /**
970 * Get the current master position for chronology control purposes
971 * @return mixed
972 */
973 public function getMasterPos() {
974 # If this entire request was served from a slave without opening a connection to the
975 # master (however unlikely that may be), then we can fetch the position from the slave.
976 $masterConn = $this->getAnyOpenConnection( 0 );
977 if ( !$masterConn ) {
978 $serverCount = count( $this->mServers );
979 for ( $i = 1; $i < $serverCount; $i++ ) {
980 $conn = $this->getAnyOpenConnection( $i );
981 if ( $conn ) {
982 return $conn->getSlavePos();
983 }
984 }
985 } else {
986 return $masterConn->getMasterPos();
987 }
988
989 return false;
990 }
991
992 /**
993 * Close all open connections
994 */
995 public function closeAll() {
996 foreach ( $this->mConns as $conns2 ) {
997 foreach ( $conns2 as $conns3 ) {
998 /** @var DatabaseBase $conn */
999 foreach ( $conns3 as $conn ) {
1000 $conn->close();
1001 }
1002 }
1003 }
1004 $this->mConns = array(
1005 'local' => array(),
1006 'foreignFree' => array(),
1007 'foreignUsed' => array(),
1008 );
1009 $this->connsOpened = 0;
1010 }
1011
1012 /**
1013 * Close a connection
1014 * Using this function makes sure the LoadBalancer knows the connection is closed.
1015 * If you use $conn->close() directly, the load balancer won't update its state.
1016 * @param DatabaseBase $conn
1017 */
1018 public function closeConnection( $conn ) {
1019 $done = false;
1020 foreach ( $this->mConns as $i1 => $conns2 ) {
1021 foreach ( $conns2 as $i2 => $conns3 ) {
1022 foreach ( $conns3 as $i3 => $candidateConn ) {
1023 if ( $conn === $candidateConn ) {
1024 $conn->close();
1025 unset( $this->mConns[$i1][$i2][$i3] );
1026 --$this->connsOpened;
1027 $done = true;
1028 break;
1029 }
1030 }
1031 }
1032 }
1033 if ( !$done ) {
1034 $conn->close();
1035 }
1036 }
1037
1038 /**
1039 * Commit transactions on all open connections
1040 * @param string $fname Caller name
1041 */
1042 public function commitAll( $fname = __METHOD__ ) {
1043 foreach ( $this->mConns as $conns2 ) {
1044 foreach ( $conns2 as $conns3 ) {
1045 /** @var DatabaseBase[] $conns3 */
1046 foreach ( $conns3 as $conn ) {
1047 if ( $conn->trxLevel() ) {
1048 $conn->commit( $fname, 'flush' );
1049 }
1050 }
1051 }
1052 }
1053 }
1054
1055 /**
1056 * Issue COMMIT only on master, only if queries were done on connection
1057 * @param string $fname Caller name
1058 */
1059 public function commitMasterChanges( $fname = __METHOD__ ) {
1060 $masterIndex = $this->getWriterIndex();
1061 foreach ( $this->mConns as $conns2 ) {
1062 if ( empty( $conns2[$masterIndex] ) ) {
1063 continue;
1064 }
1065 /** @var DatabaseBase $conn */
1066 foreach ( $conns2[$masterIndex] as $conn ) {
1067 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1068 $conn->commit( $fname, 'flush' );
1069 }
1070 }
1071 }
1072 }
1073
1074 /**
1075 * Issue ROLLBACK only on master, only if queries were done on connection
1076 * @param string $fname Caller name
1077 * @throws DBExpectedError
1078 * @since 1.23
1079 */
1080 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1081 $failedServers = array();
1082
1083 $masterIndex = $this->getWriterIndex();
1084 foreach ( $this->mConns as $conns2 ) {
1085 if ( empty( $conns2[$masterIndex] ) ) {
1086 continue;
1087 }
1088 /** @var DatabaseBase $conn */
1089 foreach ( $conns2[$masterIndex] as $conn ) {
1090 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1091 try {
1092 $conn->rollback( $fname, 'flush' );
1093 } catch ( DBError $e ) {
1094 MWExceptionHandler::logException( $e );
1095 $failedServers[] = $conn->getServer();
1096 }
1097 }
1098 }
1099 }
1100
1101 if ( $failedServers ) {
1102 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1103 implode( ', ', array_unique( $failedServers ) ) );
1104 }
1105 }
1106
1107 /**
1108 * @return bool Whether a master connection is already open
1109 * @since 1.24
1110 */
1111 public function hasMasterConnection() {
1112 return $this->isOpen( $this->getWriterIndex() );
1113 }
1114
1115 /**
1116 * Determine if there are pending changes in a transaction by this thread
1117 * @since 1.23
1118 * @return bool
1119 */
1120 public function hasMasterChanges() {
1121 $masterIndex = $this->getWriterIndex();
1122 foreach ( $this->mConns as $conns2 ) {
1123 if ( empty( $conns2[$masterIndex] ) ) {
1124 continue;
1125 }
1126 /** @var DatabaseBase $conn */
1127 foreach ( $conns2[$masterIndex] as $conn ) {
1128 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1129 return true;
1130 }
1131 }
1132 }
1133 return false;
1134 }
1135
1136 /**
1137 * Get the timestamp of the latest write query done by this thread
1138 * @since 1.25
1139 * @return float|bool UNIX timestamp or false
1140 */
1141 public function lastMasterChangeTimestamp() {
1142 $lastTime = false;
1143 $masterIndex = $this->getWriterIndex();
1144 foreach ( $this->mConns as $conns2 ) {
1145 if ( empty( $conns2[$masterIndex] ) ) {
1146 continue;
1147 }
1148 /** @var DatabaseBase $conn */
1149 foreach ( $conns2[$masterIndex] as $conn ) {
1150 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1151 }
1152 }
1153 return $lastTime;
1154 }
1155
1156 /**
1157 * Check if this load balancer object had any recent or still
1158 * pending writes issued against it by this PHP thread
1159 *
1160 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1161 * @return bool
1162 * @since 1.25
1163 */
1164 public function hasOrMadeRecentMasterChanges( $age = null ) {
1165 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1166
1167 return ( $this->hasMasterChanges()
1168 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1169 }
1170
1171 /**
1172 * Get the list of callers that have pending master changes
1173 *
1174 * @return array
1175 * @since 1.27
1176 */
1177 public function pendingMasterChangeCallers() {
1178 $fnames = array();
1179
1180 $masterIndex = $this->getWriterIndex();
1181 foreach ( $this->mConns as $conns2 ) {
1182 if ( empty( $conns2[$masterIndex] ) ) {
1183 continue;
1184 }
1185 /** @var DatabaseBase $conn */
1186 foreach ( $conns2[$masterIndex] as $conn ) {
1187 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1188 }
1189 }
1190
1191 return $fnames;
1192 }
1193
1194 /**
1195 * @param mixed $value
1196 * @return mixed
1197 */
1198 public function waitTimeout( $value = null ) {
1199 return wfSetVar( $this->mWaitTimeout, $value );
1200 }
1201
1202 /**
1203 * @note This method will trigger a DB connection if not yet done
1204 *
1205 * @param string|bool $wiki Wiki ID, or false for the current wiki
1206 * @return bool Whether the generic connection for reads is highly "lagged"
1207 */
1208 public function getLaggedSlaveMode( $wiki = false ) {
1209 // No-op if there is only one DB (also avoids recursion)
1210 if ( !$this->laggedSlaveMode && $this->getServerCount() > 1 ) {
1211 try {
1212 // See if laggedSlaveMode gets set
1213 $conn = $this->getConnection( DB_SLAVE, false, $wiki );
1214 $this->reuseConnection( $conn );
1215 } catch ( DBConnectionError $e ) {
1216 // Avoid expensive re-connect attempts and failures
1217 $this->slavesDownMode = true;
1218 $this->laggedSlaveMode = true;
1219 }
1220 }
1221
1222 return $this->laggedSlaveMode;
1223 }
1224
1225 /**
1226 * @note This method will never cause a new DB connection
1227 * @return bool Whether any generic connection used for reads was highly "lagged"
1228 * @since 1.27
1229 */
1230 public function laggedSlaveUsed() {
1231 return $this->laggedSlaveMode;
1232 }
1233
1234 /**
1235 * @note This method may trigger a DB connection if not yet done
1236 * @param string|bool $wiki Wiki ID, or false for the current wiki
1237 * @return string|bool Reason the master is read-only or false if it is not
1238 * @since 1.27
1239 */
1240 public function getReadOnlyReason( $wiki = false ) {
1241 if ( $this->readOnlyReason !== false ) {
1242 return $this->readOnlyReason;
1243 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1244 if ( $this->slavesDownMode ) {
1245 return 'The database has been automatically locked ' .
1246 'until the slave database servers become available';
1247 } else {
1248 return 'The database has been automatically locked ' .
1249 'while the slave database servers catch up to the master.';
1250 }
1251 }
1252
1253 return false;
1254 }
1255
1256 /**
1257 * Disables/enables lag checks
1258 * @param null|bool $mode
1259 * @return bool
1260 */
1261 public function allowLagged( $mode = null ) {
1262 if ( $mode === null ) {
1263 return $this->mAllowLagged;
1264 }
1265 $this->mAllowLagged = $mode;
1266
1267 return $this->mAllowLagged;
1268 }
1269
1270 /**
1271 * @return bool
1272 */
1273 public function pingAll() {
1274 $success = true;
1275 foreach ( $this->mConns as $conns2 ) {
1276 foreach ( $conns2 as $conns3 ) {
1277 /** @var DatabaseBase[] $conns3 */
1278 foreach ( $conns3 as $conn ) {
1279 if ( !$conn->ping() ) {
1280 $success = false;
1281 }
1282 }
1283 }
1284 }
1285
1286 return $success;
1287 }
1288
1289 /**
1290 * Call a function with each open connection object
1291 * @param callable $callback
1292 * @param array $params
1293 */
1294 public function forEachOpenConnection( $callback, array $params = array() ) {
1295 foreach ( $this->mConns as $conns2 ) {
1296 foreach ( $conns2 as $conns3 ) {
1297 foreach ( $conns3 as $conn ) {
1298 $mergedParams = array_merge( array( $conn ), $params );
1299 call_user_func_array( $callback, $mergedParams );
1300 }
1301 }
1302 }
1303 }
1304
1305 /**
1306 * Get the hostname and lag time of the most-lagged slave
1307 *
1308 * This is useful for maintenance scripts that need to throttle their updates.
1309 * May attempt to open connections to slaves on the default DB. If there is
1310 * no lag, the maximum lag will be reported as -1.
1311 *
1312 * @param bool|string $wiki Wiki ID, or false for the default database
1313 * @return array ( host, max lag, index of max lagged host )
1314 */
1315 public function getMaxLag( $wiki = false ) {
1316 $maxLag = -1;
1317 $host = '';
1318 $maxIndex = 0;
1319
1320 if ( $this->getServerCount() <= 1 ) {
1321 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1322 }
1323
1324 $lagTimes = $this->getLagTimes( $wiki );
1325 foreach ( $lagTimes as $i => $lag ) {
1326 if ( $lag > $maxLag ) {
1327 $maxLag = $lag;
1328 $host = $this->mServers[$i]['host'];
1329 $maxIndex = $i;
1330 }
1331 }
1332
1333 return array( $host, $maxLag, $maxIndex );
1334 }
1335
1336 /**
1337 * Get an estimate of replication lag (in seconds) for each server
1338 *
1339 * Results are cached for a short time in memcached/process cache
1340 *
1341 * Values may be "false" if replication is too broken to estimate
1342 *
1343 * @param string|bool $wiki
1344 * @return int[] Map of (server index => float|int|bool)
1345 */
1346 public function getLagTimes( $wiki = false ) {
1347 if ( $this->getServerCount() <= 1 ) {
1348 return array( 0 => 0 ); // no replication = no lag
1349 }
1350
1351 # Send the request to the load monitor
1352 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1353 }
1354
1355 /**
1356 * Get the lag in seconds for a given connection, or zero if this load
1357 * balancer does not have replication enabled.
1358 *
1359 * This should be used in preference to Database::getLag() in cases where
1360 * replication may not be in use, since there is no way to determine if
1361 * replication is in use at the connection level without running
1362 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1363 * function instead of Database::getLag() avoids a fatal error in this
1364 * case on many installations.
1365 *
1366 * @param IDatabase $conn
1367 * @return int|bool Returns false on error
1368 */
1369 public function safeGetLag( IDatabase $conn ) {
1370 if ( $this->getServerCount() == 1 ) {
1371 return 0;
1372 } else {
1373 return $conn->getLag();
1374 }
1375 }
1376
1377 /**
1378 * Wait for a slave DB to reach a specified master position
1379 *
1380 * This will connect to the master to get an accurate position if $pos is not given
1381 *
1382 * @param IDatabase $conn Slave DB
1383 * @param DBMasterPos|bool $pos Master position; default: current position
1384 * @param integer $timeout Timeout in seconds
1385 * @return bool Success
1386 * @since 1.27
1387 */
1388 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1389 if ( $this->getServerCount() == 1 || !$conn->getLBInfo( 'slave' ) ) {
1390 return true; // server is not a slave DB
1391 }
1392
1393 $pos = $pos ?: $this->getConnection( DB_MASTER )->getMasterPos();
1394 if ( !$pos ) {
1395 return false; // something is misconfigured
1396 }
1397
1398 $result = $conn->masterPosWait( $pos, $timeout );
1399 if ( $result == -1 || is_null( $result ) ) {
1400 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1401 wfDebugLog( 'replication', "$msg\n" );
1402 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1403 $ok = false;
1404 } else {
1405 wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
1406 $ok = true;
1407 }
1408
1409 return $ok;
1410 }
1411
1412 /**
1413 * Clear the cache for slag lag delay times
1414 *
1415 * This is only used for testing
1416 */
1417 public function clearLagTimeCache() {
1418 $this->getLoadMonitor()->clearCaches();
1419 }
1420 }