3 * Database load balancing.
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.
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.
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
25 * Database load balancing object
31 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
35 /** @var array Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
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 */
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
52 /** @var WANObjectCache */
54 /** @var TransactionProfiler */
55 protected $trxProfiler;
57 /** @var bool|DatabaseBase Database connection that caused a problem */
58 private $mErrorConnection;
59 /** @var integer The generic (not query grouped) slave index (of $mServers) */
61 /** @var bool|DBMasterPos False if not set */
63 /** @var bool Whether the generic reader fell back to a lagged slave */
64 private $laggedSlaveMode = false;
65 /** @var bool Whether the generic reader fell back to a lagged slave */
66 private $slavesDownMode = false;
67 /** @var string The last DB selection or connection error */
68 private $mLastError = 'Unknown error';
69 /** @var string|bool Reason the LB is read-only or false if not */
70 private $readOnlyReason = false;
71 /** @var integer Total connections opened */
72 private $connsOpened = 0;
73 /** @var string|bool String if a requested DBO_TRX transaction round is active */
74 private $trxRoundId = false;
76 /** @var integer Warn when this many connection are held */
77 const CONN_HELD_WARN_THRESHOLD
= 10;
78 /** @var integer Default 'max lag' when unspecified */
80 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
81 const POS_WAIT_TIMEOUT
= 10;
82 /** @var integer Seconds to cache master server read-only status */
83 const TTL_CACHE_READONLY
= 5;
88 private $disabled = false;
91 * @param array $params Array with keys:
92 * - servers : Required. Array of server info structures.
93 * - loadMonitor : Name of a class used to fetch server lag and load.
94 * - readOnlyReason : Reason the master DB is read-only if so [optional]
95 * - srvCache : BagOStuff object [optional]
96 * - wanCache : WANObjectCache object [optional]
99 public function __construct( array $params ) {
100 if ( !isset( $params['servers'] ) ) {
101 throw new MWException( __CLASS__
. ': missing servers parameter' );
103 $this->mServers
= $params['servers'];
104 $this->mWaitTimeout
= self
::POS_WAIT_TIMEOUT
;
106 $this->mReadIndex
= -1;
107 $this->mWriteIndex
= -1;
111 'foreignFree' => [] ];
113 $this->mWaitForPos
= false;
114 $this->mErrorConnection
= false;
115 $this->mAllowLagged
= false;
117 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
118 $this->readOnlyReason
= $params['readOnlyReason'];
121 if ( isset( $params['loadMonitor'] ) ) {
122 $this->mLoadMonitorClass
= $params['loadMonitor'];
124 $master = reset( $params['servers'] );
125 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
126 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
128 $this->mLoadMonitorClass
= 'LoadMonitorNull';
132 foreach ( $params['servers'] as $i => $server ) {
133 $this->mLoads
[$i] = $server['load'];
134 if ( isset( $server['groupLoads'] ) ) {
135 foreach ( $server['groupLoads'] as $group => $ratio ) {
136 if ( !isset( $this->mGroupLoads
[$group] ) ) {
137 $this->mGroupLoads
[$group] = [];
139 $this->mGroupLoads
[$group][$i] = $ratio;
144 if ( isset( $params['srvCache'] ) ) {
145 $this->srvCache
= $params['srvCache'];
147 $this->srvCache
= new EmptyBagOStuff();
149 if ( isset( $params['wanCache'] ) ) {
150 $this->wanCache
= $params['wanCache'];
152 $this->wanCache
= WANObjectCache
::newEmpty();
154 if ( isset( $params['trxProfiler'] ) ) {
155 $this->trxProfiler
= $params['trxProfiler'];
157 $this->trxProfiler
= new TransactionProfiler();
162 * Get a LoadMonitor instance
164 * @return LoadMonitor
166 private function getLoadMonitor() {
167 if ( !isset( $this->mLoadMonitor
) ) {
168 $class = $this->mLoadMonitorClass
;
169 $this->mLoadMonitor
= new $class( $this );
172 return $this->mLoadMonitor
;
176 * Get or set arbitrary data used by the parent object, usually an LBFactory
180 public function parentInfo( $x = null ) {
181 return wfSetVar( $this->mParentInfo
, $x );
185 * @param array $loads
186 * @param bool|string $wiki Wiki to get non-lagged for
187 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
188 * @return bool|int|string
190 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self
::MAX_LAG
) {
191 $lags = $this->getLagTimes( $wiki );
193 # Unset excessively lagged servers
194 foreach ( $lags as $i => $lag ) {
196 $maxServerLag = $maxLag;
197 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
198 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
201 $host = $this->getServerName( $i );
202 if ( $lag === false ) {
203 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
205 } elseif ( $lag > $maxServerLag ) {
206 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
212 # Find out if all the slaves with non-zero load are lagged
214 foreach ( $loads as $load ) {
218 # No appropriate DB servers except maybe the master and some slaves with zero load
219 # Do NOT use the master
220 # Instead, this function will return false, triggering read-only mode,
221 # and a lagged slave will be used instead.
225 if ( count( $loads ) == 0 ) {
229 # Return a random representative of the remainder
230 return ArrayUtils
::pickRandom( $loads );
234 * Get the index of the reader connection, which may be a slave
235 * This takes into account load ratios and lag times. It should
236 * always return a consistent index during a given invocation
238 * Side effect: opens connections to databases
239 * @param string|bool $group Query group, or false for the generic reader
240 * @param string|bool $wiki Wiki ID, or false for the current wiki
241 * @throws MWException
242 * @return bool|int|string
244 public function getReaderIndex( $group = false, $wiki = false ) {
247 # @todo FIXME: For now, only go through all this for mysql databases
248 if ( $wgDBtype != 'mysql' ) {
249 return $this->getWriterIndex();
252 if ( count( $this->mServers
) == 1 ) {
253 # Skip the load balancing if there's only one server
255 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
256 # Shortcut if generic reader exists already
257 return $this->mReadIndex
;
260 # Find the relevant load array
261 if ( $group !== false ) {
262 if ( isset( $this->mGroupLoads
[$group] ) ) {
263 $nonErrorLoads = $this->mGroupLoads
[$group];
265 # No loads for this group, return false and the caller can use some other group
266 wfDebugLog( 'connect', __METHOD__
. ": no loads for group $group\n" );
271 $nonErrorLoads = $this->mLoads
;
274 if ( !count( $nonErrorLoads ) ) {
275 throw new MWException( "Empty server array given to LoadBalancer" );
278 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
279 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
281 $laggedSlaveMode = false;
283 # No server found yet
286 # First try quickly looking through the available servers for a server that
288 $currentLoads = $nonErrorLoads;
289 while ( count( $currentLoads ) ) {
290 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
291 $i = ArrayUtils
::pickRandom( $currentLoads );
294 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
295 # ChronologyProtecter causes mWaitForPos to be set via sessions.
296 # This triggers doWait() after connect, so it's especially good to
297 # avoid lagged servers so as to avoid just blocking in that method.
298 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
299 # Aim for <= 1 second of waiting (being too picky can backfire)
300 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
302 if ( $i === false ) {
303 # Any server with less lag than it's 'max lag' param is preferable
304 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
306 if ( $i === false && count( $currentLoads ) != 0 ) {
307 # All slaves lagged. Switch to read-only mode
308 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
309 $i = ArrayUtils
::pickRandom( $currentLoads );
310 $laggedSlaveMode = true;
314 if ( $i === false ) {
315 # pickRandom() returned false
316 # This is permanent and means the configuration or the load monitor
317 # wants us to return false.
318 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
323 $serverName = $this->getServerName( $i );
324 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
326 $conn = $this->openConnection( $i, $wiki );
328 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
329 unset( $nonErrorLoads[$i] );
330 unset( $currentLoads[$i] );
335 // Decrement reference counter, we are finished with this connection.
336 // It will be incremented for the caller later.
337 if ( $wiki !== false ) {
338 $this->reuseConnection( $conn );
345 # If all servers were down, quit now
346 if ( !count( $nonErrorLoads ) ) {
347 wfDebugLog( 'connect', "All servers down" );
350 if ( $i !== false ) {
351 # Slave connection successful
352 # Wait for the session master pos for a short time
353 if ( $this->mWaitForPos
&& $i > 0 ) {
354 if ( !$this->doWait( $i ) ) {
355 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
358 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
359 $this->mReadIndex
= $i;
360 # Record if the generic reader index is in "lagged slave" mode
361 if ( $laggedSlaveMode ) {
362 $this->laggedSlaveMode
= true;
365 $serverName = $this->getServerName( $i );
366 wfDebugLog( 'connect', __METHOD__
.
367 ": using server $serverName for group '$group'\n" );
374 * Set the master wait position
375 * If a DB_SLAVE connection has been opened already, waits
376 * Otherwise sets a variable telling it to wait if such a connection is opened
377 * @param DBMasterPos $pos
379 public function waitFor( $pos ) {
380 $this->mWaitForPos
= $pos;
381 $i = $this->mReadIndex
;
384 if ( !$this->doWait( $i ) ) {
385 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
386 $this->laggedSlaveMode
= true;
392 * Set the master wait position and wait for a "generic" slave to catch up to it
394 * This can be used a faster proxy for waitForAll()
396 * @param DBMasterPos $pos
397 * @param int $timeout Max seconds to wait; default is mWaitTimeout
398 * @return bool Success (able to connect and no timeouts reached)
401 public function waitForOne( $pos, $timeout = null ) {
402 $this->mWaitForPos
= $pos;
404 $i = $this->mReadIndex
;
406 // Pick a generic slave if there isn't one yet
407 $readLoads = $this->mLoads
;
408 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
409 $readLoads = array_filter( $readLoads ); // with non-zero load
410 $i = ArrayUtils
::pickRandom( $readLoads );
414 $ok = $this->doWait( $i, true, $timeout );
416 $ok = true; // no applicable loads
423 * Set the master wait position and wait for ALL slaves to catch up to it
424 * @param DBMasterPos $pos
425 * @param int $timeout Max seconds to wait; default is mWaitTimeout
426 * @return bool Success (able to connect and no timeouts reached)
428 public function waitForAll( $pos, $timeout = null ) {
429 $this->mWaitForPos
= $pos;
430 $serverCount = count( $this->mServers
);
433 for ( $i = 1; $i < $serverCount; $i++
) {
434 if ( $this->mLoads
[$i] > 0 ) {
435 $ok = $this->doWait( $i, true, $timeout ) && $ok;
443 * Get any open connection to a given server index, local or foreign
444 * Returns false if there is no connection open
447 * @return DatabaseBase|bool False on failure
449 public function getAnyOpenConnection( $i ) {
450 foreach ( $this->mConns
as $conns ) {
451 if ( !empty( $conns[$i] ) ) {
452 return reset( $conns[$i] );
460 * Wait for a given slave to catch up to the master pos stored in $this
461 * @param int $index Server index
462 * @param bool $open Check the server even if a new connection has to be made
463 * @param int $timeout Max seconds to wait; default is mWaitTimeout
466 protected function doWait( $index, $open = false, $timeout = null ) {
467 $close = false; // close the connection afterwards
469 // Check if we already know that the DB has reached this point
470 $server = $this->getServerName( $index );
471 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
472 /** @var DBMasterPos $knownReachedPos */
473 $knownReachedPos = $this->srvCache
->get( $key );
474 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
475 wfDebugLog( 'replication', __METHOD__
.
476 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
480 // Find a connection to wait on, creating one if needed and allowed
481 $conn = $this->getAnyOpenConnection( $index );
484 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
488 $conn = $this->openConnection( $index, '' );
490 wfDebugLog( 'replication', __METHOD__
. ": failed to connect to $server\n" );
494 // Avoid connection spam in waitForAll() when connections
495 // are made just for the sake of doing this lag check.
500 wfDebugLog( 'replication', __METHOD__
. ": Waiting for slave $server to catch up...\n" );
501 $timeout = $timeout ?
: $this->mWaitTimeout
;
502 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
504 if ( $result == -1 ||
is_null( $result ) ) {
505 // Timed out waiting for slave, use master instead
506 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
507 wfDebugLog( 'replication', "$msg\n" );
508 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
511 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
513 // Remember that the DB reached this point
514 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
518 $this->closeConnection( $conn );
525 * Get a connection by index
526 * This is the main entry point for this class.
528 * @param int $i Server index
529 * @param array|string|bool $groups Query group(s), or false for the generic reader
530 * @param string|bool $wiki Wiki ID, or false for the current wiki
532 * @throws MWException
533 * @return DatabaseBase
535 public function getConnection( $i, $groups = [], $wiki = false ) {
536 if ( $i === null ||
$i === false ) {
537 throw new MWException( 'Attempt to call ' . __METHOD__
.
538 ' with invalid server index' );
541 if ( $wiki === wfWikiID() ) {
545 $groups = ( $groups === false ||
$groups === [] )
546 ?
[ false ] // check one "group": the generic pool
549 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
550 $oldConnsOpened = $this->connsOpened
; // connections open now
552 if ( $i == DB_MASTER
) {
553 $i = $this->getWriterIndex();
555 # Try to find an available server in any the query groups (in order)
556 foreach ( $groups as $group ) {
557 $groupIndex = $this->getReaderIndex( $group, $wiki );
558 if ( $groupIndex !== false ) {
565 # Operation-based index
566 if ( $i == DB_SLAVE
) {
567 $this->mLastError
= 'Unknown error'; // reset error string
568 # Try the general server pool if $groups are unavailable.
569 $i = in_array( false, $groups, true )
570 ?
false // don't bother with this if that is what was tried above
571 : $this->getReaderIndex( false, $wiki );
572 # Couldn't find a working server in getReaderIndex()?
573 if ( $i === false ) {
574 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
576 return $this->reportConnectionError();
580 # Now we have an explicit index into the servers array
581 $conn = $this->openConnection( $i, $wiki );
583 return $this->reportConnectionError();
586 # Profile any new connections that happen
587 if ( $this->connsOpened
> $oldConnsOpened ) {
588 $host = $conn->getServer();
589 $dbname = $conn->getDBname();
590 $trxProf = Profiler
::instance()->getTransactionProfiler();
591 $trxProf->recordConnection( $host, $dbname, $masterOnly );
595 # Make master-requested DB handles inherit any read-only mode setting
596 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki, $conn ) );
603 * Mark a foreign connection as being available for reuse under a different
604 * DB name or prefix. This mechanism is reference-counted, and must be called
605 * the same number of times as getConnection() to work.
607 * @param DatabaseBase $conn
608 * @throws MWException
610 public function reuseConnection( $conn ) {
611 $serverIndex = $conn->getLBInfo( 'serverIndex' );
612 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
613 if ( $serverIndex === null ||
$refCount === null ) {
614 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
616 * This can happen in code like:
617 * foreach ( $dbs as $db ) {
618 * $conn = $lb->getConnection( DB_SLAVE, [], $db );
620 * $lb->reuseConnection( $conn );
622 * When a connection to the local DB is opened in this way, reuseConnection()
628 $dbName = $conn->getDBname();
629 $prefix = $conn->tablePrefix();
630 if ( strval( $prefix ) !== '' ) {
631 $wiki = "$dbName-$prefix";
635 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
636 throw new MWException( __METHOD__
. ": connection not found, has " .
637 "the connection been freed already?" );
639 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
640 if ( $refCount <= 0 ) {
641 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
642 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
643 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
645 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
650 * Get a database connection handle reference
652 * The handle's methods wrap simply wrap those of a DatabaseBase handle
654 * @see LoadBalancer::getConnection() for parameter information
657 * @param array|string|bool $groups Query group(s), or false for the generic reader
658 * @param string|bool $wiki Wiki ID, or false for the current wiki
661 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
662 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
666 * Get a database connection handle reference without connecting yet
668 * The handle's methods wrap simply wrap those of a DatabaseBase handle
670 * @see LoadBalancer::getConnection() for parameter information
673 * @param array|string|bool $groups Query group(s), or false for the generic reader
674 * @param string|bool $wiki Wiki ID, or false for the current wiki
677 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
678 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
682 * Open a connection to the server given by the specified index
683 * Index must be an actual index into the array.
684 * If the server is already open, returns it.
686 * On error, returns false, and the connection which caused the
687 * error will be available via $this->mErrorConnection.
689 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
691 * @param int $i Server index
692 * @param string|bool $wiki Wiki ID, or false for the current wiki
693 * @return DatabaseBase|bool Returns false on errors
695 public function openConnection( $i, $wiki = false ) {
696 if ( $wiki !== false ) {
697 $conn = $this->openForeignConnection( $i, $wiki );
698 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
699 $conn = $this->mConns
['local'][$i][0];
701 $server = $this->mServers
[$i];
702 $server['serverIndex'] = $i;
703 $conn = $this->reallyOpenConnection( $server, false );
704 $serverName = $this->getServerName( $i );
705 if ( $conn->isOpen() ) {
706 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
707 $this->mConns
['local'][$i][0] = $conn;
709 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
710 $this->mErrorConnection
= $conn;
715 if ( $conn && !$conn->isOpen() ) {
716 // Connection was made but later unrecoverably lost for some reason.
717 // Do not return a handle that will just throw exceptions on use,
718 // but let the calling code (e.g. getReaderIndex) try another server.
719 // See DatabaseMyslBase::ping() for how this can happen.
720 $this->mErrorConnection
= $conn;
728 * Open a connection to a foreign DB, or return one if it is already open.
730 * Increments a reference count on the returned connection which locks the
731 * connection to the requested wiki. This reference count can be
732 * decremented by calling reuseConnection().
734 * If a connection is open to the appropriate server already, but with the wrong
735 * database, it will be switched to the right database and returned, as long as
736 * it has been freed first with reuseConnection().
738 * On error, returns false, and the connection which caused the
739 * error will be available via $this->mErrorConnection.
741 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
743 * @param int $i Server index
744 * @param string $wiki Wiki ID to open
745 * @return DatabaseBase
747 private function openForeignConnection( $i, $wiki ) {
748 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
749 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
750 // Reuse an already-used connection
751 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
752 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
753 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
754 // Reuse a free connection for the same wiki
755 $conn = $this->mConns
['foreignFree'][$i][$wiki];
756 unset( $this->mConns
['foreignFree'][$i][$wiki] );
757 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
758 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
759 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
760 // Reuse a connection from another wiki
761 $conn = reset( $this->mConns
['foreignFree'][$i] );
762 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
764 // The empty string as a DB name means "don't care".
765 // DatabaseMysqlBase::open() already handle this on connection.
766 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
767 $this->mLastError
= "Error selecting database $dbName on server " .
768 $conn->getServer() . " from client host " . wfHostname() . "\n";
769 $this->mErrorConnection
= $conn;
772 $conn->tablePrefix( $prefix );
773 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
774 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
775 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
778 // Open a new connection
779 $server = $this->mServers
[$i];
780 $server['serverIndex'] = $i;
781 $server['foreignPoolRefCount'] = 0;
782 $server['foreign'] = true;
783 $conn = $this->reallyOpenConnection( $server, $dbName );
784 if ( !$conn->isOpen() ) {
785 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
786 $this->mErrorConnection
= $conn;
789 $conn->tablePrefix( $prefix );
790 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
791 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
795 // Increment reference count
797 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
798 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
805 * Test if the specified index represents an open connection
807 * @param int $index Server index
811 private function isOpen( $index ) {
812 if ( !is_integer( $index ) ) {
816 return (bool)$this->getAnyOpenConnection( $index );
820 * Really opens a connection. Uncached.
821 * Returns a Database object whether or not the connection was successful.
824 * @param array $server
825 * @param bool $dbNameOverride
826 * @throws MWException
827 * @return DatabaseBase
829 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
830 if ( $this->disabled
) {
831 throw new DBAccessError();
834 if ( !is_array( $server ) ) {
835 throw new MWException( 'You must update your load-balancing configuration. ' .
836 'See DefaultSettings.php entry for $wgDBservers.' );
839 if ( $dbNameOverride !== false ) {
840 $server['dbname'] = $dbNameOverride;
843 // Let the handle know what the cluster master is (e.g. "db1052")
844 $masterName = $this->getServerName( 0 );
845 $server['clusterMasterHost'] = $masterName;
847 // Log when many connection are made on requests
848 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
849 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
850 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
851 wfBacktrace( true ) );
856 $db = DatabaseBase
::factory( $server['type'], $server );
857 } catch ( DBConnectionError
$e ) {
858 // FIXME: This is probably the ugliest thing I have ever done to
859 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
863 $db->setLBInfo( $server );
864 $db->setLazyMasterHandle(
865 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
867 $db->setTransactionProfiler( $this->trxProfiler
);
868 if ( $this->trxRoundId
!== false ) {
869 $this->applyTransactionRoundFlags( $db );
876 * @throws DBConnectionError
879 private function reportConnectionError() {
880 $conn = $this->mErrorConnection
; // The connection which caused the error
882 'method' => __METHOD__
,
883 'last_error' => $this->mLastError
,
886 if ( !is_object( $conn ) ) {
887 // No last connection, probably due to all servers being too busy
889 "LB failure with no last connection. Connection error: {last_error}",
893 // If all servers were busy, mLastError will contain something sensible
894 throw new DBConnectionError( null, $this->mLastError
);
896 $context['db_server'] = $conn->getProperty( 'mServer' );
898 "Connection error: {last_error} ({db_server})",
902 // throws DBConnectionError
903 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
906 return false; /* not reached */
913 public function getWriterIndex() {
918 * Returns true if the specified index is a valid server index
923 public function haveIndex( $i ) {
924 return array_key_exists( $i, $this->mServers
);
928 * Returns true if the specified index is valid and has non-zero load
933 public function isNonZeroLoad( $i ) {
934 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
938 * Get the number of defined servers (not the number of open connections)
942 public function getServerCount() {
943 return count( $this->mServers
);
947 * Get the host name or IP address of the server with the specified index
948 * Prefer a readable name if available.
952 public function getServerName( $i ) {
953 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
954 $name = $this->mServers
[$i]['hostName'];
955 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
956 $name = $this->mServers
[$i]['host'];
961 return ( $name != '' ) ?
$name : 'localhost';
965 * Return the server info structure for a given index, or false if the index is invalid.
969 public function getServerInfo( $i ) {
970 if ( isset( $this->mServers
[$i] ) ) {
971 return $this->mServers
[$i];
978 * Sets the server info structure for the given index. Entry at index $i
979 * is created if it doesn't exist
981 * @param array $serverInfo
983 public function setServerInfo( $i, array $serverInfo ) {
984 $this->mServers
[$i] = $serverInfo;
988 * Get the current master position for chronology control purposes
991 public function getMasterPos() {
992 # If this entire request was served from a slave without opening a connection to the
993 # master (however unlikely that may be), then we can fetch the position from the slave.
994 $masterConn = $this->getAnyOpenConnection( 0 );
995 if ( !$masterConn ) {
996 $serverCount = count( $this->mServers
);
997 for ( $i = 1; $i < $serverCount; $i++
) {
998 $conn = $this->getAnyOpenConnection( $i );
1000 return $conn->getSlavePos();
1004 return $masterConn->getMasterPos();
1011 * Disable this load balancer. All connections are closed, and any attempt to
1012 * open a new connection will result in a DBAccessError.
1016 public function disable() {
1018 $this->disabled
= true;
1022 * Close all open connections
1024 public function closeAll() {
1025 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) {
1031 'foreignFree' => [],
1032 'foreignUsed' => [],
1034 $this->connsOpened
= 0;
1038 * Close a connection
1039 * Using this function makes sure the LoadBalancer knows the connection is closed.
1040 * If you use $conn->close() directly, the load balancer won't update its state.
1041 * @param DatabaseBase $conn
1043 public function closeConnection( $conn ) {
1045 foreach ( $this->mConns
as $i1 => $conns2 ) {
1046 foreach ( $conns2 as $i2 => $conns3 ) {
1047 foreach ( $conns3 as $i3 => $candidateConn ) {
1048 if ( $conn === $candidateConn ) {
1050 unset( $this->mConns
[$i1][$i2][$i3] );
1051 --$this->connsOpened
;
1064 * Commit transactions on all open connections
1065 * @param string $fname Caller name
1066 * @throws DBExpectedError
1068 public function commitAll( $fname = __METHOD__
) {
1071 $restore = ( $this->trxRoundId
!== false );
1072 $this->trxRoundId
= false;
1073 $this->forEachOpenConnection(
1074 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1076 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1077 } catch ( DBError
$e ) {
1078 MWExceptionHandler
::logException( $e );
1079 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1081 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1082 $this->undoTransactionRoundFlags( $conn );
1088 throw new DBExpectedError(
1090 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1096 * Perform all pre-commit callbacks that remain part of the atomic transactions
1097 * and disable any post-commit callbacks until runMasterPostTrxCallbacks()
1100 public function finalizeMasterChanges() {
1101 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1102 // Any error should cause all DB transactions to be rolled back together
1103 $conn->setTrxEndCallbackSuppression( false );
1104 $conn->runOnTransactionPreCommitCallbacks();
1105 // Defer post-commit callbacks until COMMIT finishes for all DBs
1106 $conn->setTrxEndCallbackSuppression( true );
1111 * Perform all pre-commit checks for things like replication safety
1112 * @param array $options Includes:
1113 * - maxWriteDuration : max write query duration time in seconds
1114 * @throws DBTransactionError
1117 public function approveMasterChanges( array $options ) {
1118 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1119 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $limit ) {
1120 // If atomic sections or explicit transactions are still open, some caller must have
1121 // caught an exception but failed to properly rollback any changes. Detect that and
1122 // throw and error (causing rollback).
1123 if ( $conn->explicitTrxActive() ) {
1124 throw new DBTransactionError(
1126 "Explicit transaction still active. A caller may have caught an error."
1129 // Assert that the time to replicate the transaction will be sane.
1130 // If this fails, then all DB transactions will be rollback back together.
1131 $time = $conn->pendingWriteQueryDuration();
1132 if ( $limit > 0 && $time > $limit ) {
1133 throw new DBTransactionError(
1135 wfMessage( 'transaction-duration-limit-exceeded', $time, $limit )->text()
1138 // If a connection sits idle while slow queries execute on another, that connection
1139 // may end up dropped before the commit round is reached. Ping servers to detect this.
1140 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1141 throw new DBTransactionError(
1143 "A connection to the {$conn->getDBname()} database was lost before commit."
1150 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
1152 * The DBO_TRX setting will be reverted to the default in each of these methods:
1153 * - commitMasterChanges()
1154 * - rollbackMasterChanges()
1156 * This allows for custom transaction rounds from any outer transaction scope.
1158 * @param string $fname
1159 * @throws DBExpectedError
1162 public function beginMasterChanges( $fname = __METHOD__
) {
1163 if ( $this->trxRoundId
!== false ) {
1164 throw new DBTransactionError(
1166 "$fname: Transaction round '{$this->trxRoundId}' already started."
1169 $this->trxRoundId
= $fname;
1172 $this->forEachOpenMasterConnection(
1173 function ( DatabaseBase
$conn ) use ( $fname, &$failures ) {
1174 $conn->setTrxEndCallbackSuppression( true );
1176 $conn->clearSnapshot( $fname );
1177 } catch ( DBError
$e ) {
1178 MWExceptionHandler
::logException( $e );
1179 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1181 $conn->setTrxEndCallbackSuppression( false );
1182 $this->applyTransactionRoundFlags( $conn );
1187 throw new DBExpectedError(
1189 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1195 * Issue COMMIT on all master connections where writes where done
1196 * @param string $fname Caller name
1197 * @throws DBExpectedError
1199 public function commitMasterChanges( $fname = __METHOD__
) {
1202 $restore = ( $this->trxRoundId
!== false );
1203 $this->trxRoundId
= false;
1204 $this->forEachOpenMasterConnection(
1205 function ( DatabaseBase
$conn ) use ( $fname, $restore, &$failures ) {
1207 if ( $conn->writesOrCallbacksPending() ) {
1208 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1209 } elseif ( $restore ) {
1210 $conn->clearSnapshot( $fname );
1212 } catch ( DBError
$e ) {
1213 MWExceptionHandler
::logException( $e );
1214 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1217 $this->undoTransactionRoundFlags( $conn );
1223 throw new DBExpectedError(
1225 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1231 * Issue all pending post-COMMIT/ROLLBACK callbacks
1232 * @param integer $type IDatabase::TRIGGER_* constant
1233 * @return Exception|null The first exception or null if there were none
1236 public function runMasterPostTrxCallbacks( $type ) {
1237 $e = null; // first exception
1238 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $type, &$e ) {
1239 $conn->clearSnapshot( __METHOD__
); // clear no-op transactions
1241 $conn->setTrxEndCallbackSuppression( false );
1243 $conn->runOnTransactionIdleCallbacks( $type );
1244 } catch ( Exception
$ex ) {
1248 $conn->runTransactionListenerCallbacks( $type );
1249 } catch ( Exception
$ex ) {
1258 * Issue ROLLBACK only on master, only if queries were done on connection
1259 * @param string $fname Caller name
1260 * @throws DBExpectedError
1263 public function rollbackMasterChanges( $fname = __METHOD__
) {
1264 $restore = ( $this->trxRoundId
!== false );
1265 $this->trxRoundId
= false;
1266 $this->forEachOpenMasterConnection(
1267 function ( DatabaseBase
$conn ) use ( $fname, $restore ) {
1268 if ( $conn->writesOrCallbacksPending() ) {
1269 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1272 $this->undoTransactionRoundFlags( $conn );
1279 * Suppress all pending post-COMMIT/ROLLBACK callbacks
1280 * @return Exception|null The first exception or null if there were none
1283 public function suppressTransactionEndCallbacks() {
1284 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1285 $conn->setTrxEndCallbackSuppression( true );
1290 * @param DatabaseBase $conn
1292 private function applyTransactionRoundFlags( DatabaseBase
$conn ) {
1293 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1294 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1295 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1296 $conn->setFlag( DBO_TRX
, $conn::REMEMBER_PRIOR
);
1297 // If config has explicitly requested DBO_TRX be either on or off by not
1298 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1299 // for things like blob stores (ExternalStore) which want auto-commit mode.
1304 * @param DatabaseBase $conn
1306 private function undoTransactionRoundFlags( DatabaseBase
$conn ) {
1307 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1308 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1313 * @return bool Whether a master connection is already open
1316 public function hasMasterConnection() {
1317 return $this->isOpen( $this->getWriterIndex() );
1321 * Determine if there are pending changes in a transaction by this thread
1325 public function hasMasterChanges() {
1326 $masterIndex = $this->getWriterIndex();
1327 foreach ( $this->mConns
as $conns2 ) {
1328 if ( empty( $conns2[$masterIndex] ) ) {
1331 /** @var DatabaseBase $conn */
1332 foreach ( $conns2[$masterIndex] as $conn ) {
1333 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1342 * Get the timestamp of the latest write query done by this thread
1344 * @return float|bool UNIX timestamp or false
1346 public function lastMasterChangeTimestamp() {
1348 $masterIndex = $this->getWriterIndex();
1349 foreach ( $this->mConns
as $conns2 ) {
1350 if ( empty( $conns2[$masterIndex] ) ) {
1353 /** @var DatabaseBase $conn */
1354 foreach ( $conns2[$masterIndex] as $conn ) {
1355 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1362 * Check if this load balancer object had any recent or still
1363 * pending writes issued against it by this PHP thread
1365 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1369 public function hasOrMadeRecentMasterChanges( $age = null ) {
1370 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1372 return ( $this->hasMasterChanges()
1373 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1377 * Get the list of callers that have pending master changes
1382 public function pendingMasterChangeCallers() {
1385 $masterIndex = $this->getWriterIndex();
1386 foreach ( $this->mConns
as $conns2 ) {
1387 if ( empty( $conns2[$masterIndex] ) ) {
1390 /** @var DatabaseBase $conn */
1391 foreach ( $conns2[$masterIndex] as $conn ) {
1392 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1400 * @param mixed $value
1403 public function waitTimeout( $value = null ) {
1404 return wfSetVar( $this->mWaitTimeout
, $value );
1408 * @note This method will trigger a DB connection if not yet done
1410 * @param string|bool $wiki Wiki ID, or false for the current wiki
1411 * @return bool Whether the generic connection for reads is highly "lagged"
1413 public function getLaggedSlaveMode( $wiki = false ) {
1414 // No-op if there is only one DB (also avoids recursion)
1415 if ( !$this->laggedSlaveMode
&& $this->getServerCount() > 1 ) {
1417 // See if laggedSlaveMode gets set
1418 $conn = $this->getConnection( DB_SLAVE
, false, $wiki );
1419 $this->reuseConnection( $conn );
1420 } catch ( DBConnectionError
$e ) {
1421 // Avoid expensive re-connect attempts and failures
1422 $this->slavesDownMode
= true;
1423 $this->laggedSlaveMode
= true;
1427 return $this->laggedSlaveMode
;
1431 * @note This method will never cause a new DB connection
1432 * @return bool Whether any generic connection used for reads was highly "lagged"
1435 public function laggedSlaveUsed() {
1436 return $this->laggedSlaveMode
;
1440 * @note This method may trigger a DB connection if not yet done
1441 * @param string|bool $wiki Wiki ID, or false for the current wiki
1442 * @param DatabaseBase|null DB master connection; used to avoid loops [optional]
1443 * @return string|bool Reason the master is read-only or false if it is not
1446 public function getReadOnlyReason( $wiki = false, DatabaseBase
$conn = null ) {
1447 if ( $this->readOnlyReason
!== false ) {
1448 return $this->readOnlyReason
;
1449 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1450 if ( $this->slavesDownMode
) {
1451 return 'The database has been automatically locked ' .
1452 'until the slave database servers become available';
1454 return 'The database has been automatically locked ' .
1455 'while the slave database servers catch up to the master.';
1457 } elseif ( $this->masterRunningReadOnly( $wiki, $conn ) ) {
1458 return 'The database master is running in read-only mode.';
1465 * @param string $wiki Wiki ID, or false for the current wiki
1466 * @param DatabaseBase|null DB master connectionl used to avoid loops [optional]
1469 private function masterRunningReadOnly( $wiki, DatabaseBase
$conn = null ) {
1470 $cache = $this->wanCache
;
1471 $masterServer = $this->getServerName( $this->getWriterIndex() );
1473 return (bool)$cache->getWithSetCallback(
1474 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1475 self
::TTL_CACHE_READONLY
,
1476 function () use ( $wiki, $conn ) {
1477 $this->trxProfiler
->setSilenced( true );
1479 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $wiki );
1480 $readOnly = (int)$dbw->serverIsReadOnly();
1481 } catch ( DBError
$e ) {
1484 $this->trxProfiler
->setSilenced( false );
1487 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1492 * Disables/enables lag checks
1493 * @param null|bool $mode
1496 public function allowLagged( $mode = null ) {
1497 if ( $mode === null ) {
1498 return $this->mAllowLagged
;
1500 $this->mAllowLagged
= $mode;
1502 return $this->mAllowLagged
;
1508 public function pingAll() {
1510 $this->forEachOpenConnection( function ( DatabaseBase
$conn ) use ( &$success ) {
1511 if ( !$conn->ping() ) {
1520 * Call a function with each open connection object
1521 * @param callable $callback
1522 * @param array $params
1524 public function forEachOpenConnection( $callback, array $params = [] ) {
1525 foreach ( $this->mConns
as $connsByServer ) {
1526 foreach ( $connsByServer as $serverConns ) {
1527 foreach ( $serverConns as $conn ) {
1528 $mergedParams = array_merge( [ $conn ], $params );
1529 call_user_func_array( $callback, $mergedParams );
1536 * Call a function with each open connection object to a master
1537 * @param callable $callback
1538 * @param array $params
1541 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1542 $masterIndex = $this->getWriterIndex();
1543 foreach ( $this->mConns
as $connsByServer ) {
1544 if ( isset( $connsByServer[$masterIndex] ) ) {
1545 /** @var DatabaseBase $conn */
1546 foreach ( $connsByServer[$masterIndex] as $conn ) {
1547 $mergedParams = array_merge( [ $conn ], $params );
1548 call_user_func_array( $callback, $mergedParams );
1555 * Get the hostname and lag time of the most-lagged slave
1557 * This is useful for maintenance scripts that need to throttle their updates.
1558 * May attempt to open connections to slaves on the default DB. If there is
1559 * no lag, the maximum lag will be reported as -1.
1561 * @param bool|string $wiki Wiki ID, or false for the default database
1562 * @return array ( host, max lag, index of max lagged host )
1564 public function getMaxLag( $wiki = false ) {
1569 if ( $this->getServerCount() <= 1 ) {
1570 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1573 $lagTimes = $this->getLagTimes( $wiki );
1574 foreach ( $lagTimes as $i => $lag ) {
1575 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1577 $host = $this->mServers
[$i]['host'];
1582 return [ $host, $maxLag, $maxIndex ];
1586 * Get an estimate of replication lag (in seconds) for each server
1588 * Results are cached for a short time in memcached/process cache
1590 * Values may be "false" if replication is too broken to estimate
1592 * @param string|bool $wiki
1593 * @return int[] Map of (server index => float|int|bool)
1595 public function getLagTimes( $wiki = false ) {
1596 if ( $this->getServerCount() <= 1 ) {
1597 return [ 0 => 0 ]; // no replication = no lag
1600 # Send the request to the load monitor
1601 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1605 * Get the lag in seconds for a given connection, or zero if this load
1606 * balancer does not have replication enabled.
1608 * This should be used in preference to Database::getLag() in cases where
1609 * replication may not be in use, since there is no way to determine if
1610 * replication is in use at the connection level without running
1611 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1612 * function instead of Database::getLag() avoids a fatal error in this
1613 * case on many installations.
1615 * @param IDatabase $conn
1616 * @return int|bool Returns false on error
1618 public function safeGetLag( IDatabase
$conn ) {
1619 if ( $this->getServerCount() == 1 ) {
1622 return $conn->getLag();
1627 * Wait for a slave DB to reach a specified master position
1629 * This will connect to the master to get an accurate position if $pos is not given
1631 * @param IDatabase $conn Slave DB
1632 * @param DBMasterPos|bool $pos Master position; default: current position
1633 * @param integer $timeout Timeout in seconds
1634 * @return bool Success
1637 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1638 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'slave' ) ) {
1639 return true; // server is not a slave DB
1642 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1643 if ( !( $pos instanceof DBMasterPos
) ) {
1644 return false; // something is misconfigured
1647 $result = $conn->masterPosWait( $pos, $timeout );
1648 if ( $result == -1 ||
is_null( $result ) ) {
1649 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1650 wfDebugLog( 'replication', "$msg\n" );
1651 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1654 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1662 * Clear the cache for slag lag delay times
1664 * This is only used for testing
1666 public function clearLagTimeCache() {
1667 $this->getLoadMonitor()->clearCaches();