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;
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) */
57 /** @var bool|DBMasterPos False if not set */
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;
70 /** @var TransactionProfiler */
71 protected $trxProfiler;
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 */
77 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
78 const POS_WAIT_TIMEOUT
= 10;
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]
87 public function __construct( array $params ) {
88 if ( !isset( $params['servers'] ) ) {
89 throw new MWException( __CLASS__
. ': missing servers parameter' );
91 $this->mServers
= $params['servers'];
92 $this->mWaitTimeout
= self
::POS_WAIT_TIMEOUT
;
94 $this->mReadIndex
= -1;
95 $this->mWriteIndex
= -1;
99 'foreignFree' => [] ];
101 $this->mWaitForPos
= false;
102 $this->mErrorConnection
= false;
103 $this->mAllowLagged
= false;
105 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
106 $this->readOnlyReason
= $params['readOnlyReason'];
109 if ( isset( $params['loadMonitor'] ) ) {
110 $this->mLoadMonitorClass
= $params['loadMonitor'];
112 $master = reset( $params['servers'] );
113 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
114 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
116 $this->mLoadMonitorClass
= 'LoadMonitorNull';
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] = [];
127 $this->mGroupLoads
[$group][$i] = $ratio;
132 $this->srvCache
= ObjectCache
::getLocalServerInstance();
134 if ( isset( $params['trxProfiler'] ) ) {
135 $this->trxProfiler
= $params['trxProfiler'];
137 $this->trxProfiler
= new TransactionProfiler();
142 * Get a LoadMonitor instance
144 * @return LoadMonitor
146 private function getLoadMonitor() {
147 if ( !isset( $this->mLoadMonitor
) ) {
148 $class = $this->mLoadMonitorClass
;
149 $this->mLoadMonitor
= new $class( $this );
152 return $this->mLoadMonitor
;
156 * Get or set arbitrary data used by the parent object, usually an LBFactory
160 public function parentInfo( $x = null ) {
161 return wfSetVar( $this->mParentInfo
, $x );
165 * @param array $loads
166 * @param bool|string $wiki Wiki to get non-lagged for
167 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
168 * @return bool|int|string
170 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self
::MAX_LAG
) {
171 $lags = $this->getLagTimes( $wiki );
173 # Unset excessively lagged servers
174 foreach ( $lags as $i => $lag ) {
176 $maxServerLag = $maxLag;
177 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
178 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
181 $host = $this->getServerName( $i );
182 if ( $lag === false ) {
183 wfDebugLog( 'replication', "Server $host (#$i) is not replicating?" );
185 } elseif ( $lag > $maxServerLag ) {
186 wfDebugLog( 'replication', "Server $host (#$i) has >= $lag seconds of lag" );
192 # Find out if all the slaves with non-zero load are lagged
194 foreach ( $loads as $load ) {
198 # No appropriate DB servers except maybe the master and some slaves with zero load
199 # Do NOT use the master
200 # Instead, this function will return false, triggering read-only mode,
201 # and a lagged slave will be used instead.
205 if ( count( $loads ) == 0 ) {
209 # Return a random representative of the remainder
210 return ArrayUtils
::pickRandom( $loads );
214 * Get the index of the reader connection, which may be a slave
215 * This takes into account load ratios and lag times. It should
216 * always return a consistent index during a given invocation
218 * Side effect: opens connections to databases
219 * @param string|bool $group Query group, or false for the generic reader
220 * @param string|bool $wiki Wiki ID, or false for the current wiki
221 * @throws MWException
222 * @return bool|int|string
224 public function getReaderIndex( $group = false, $wiki = false ) {
227 # @todo FIXME: For now, only go through all this for mysql databases
228 if ( $wgDBtype != 'mysql' ) {
229 return $this->getWriterIndex();
232 if ( count( $this->mServers
) == 1 ) {
233 # Skip the load balancing if there's only one server
235 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
236 # Shortcut if generic reader exists already
237 return $this->mReadIndex
;
240 # Find the relevant load array
241 if ( $group !== false ) {
242 if ( isset( $this->mGroupLoads
[$group] ) ) {
243 $nonErrorLoads = $this->mGroupLoads
[$group];
245 # No loads for this group, return false and the caller can use some other group
246 wfDebugLog( 'connect', __METHOD__
. ": no loads for group $group\n" );
251 $nonErrorLoads = $this->mLoads
;
254 if ( !count( $nonErrorLoads ) ) {
255 throw new MWException( "Empty server array given to LoadBalancer" );
258 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
259 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
261 $laggedSlaveMode = false;
263 # No server found yet
266 # First try quickly looking through the available servers for a server that
268 $currentLoads = $nonErrorLoads;
269 while ( count( $currentLoads ) ) {
270 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
271 $i = ArrayUtils
::pickRandom( $currentLoads );
274 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
275 # ChronologyProtecter causes mWaitForPos to be set via sessions.
276 # This triggers doWait() after connect, so it's especially good to
277 # avoid lagged servers so as to avoid just blocking in that method.
278 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
279 # Aim for <= 1 second of waiting (being too picky can backfire)
280 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
282 if ( $i === false ) {
283 # Any server with less lag than it's 'max lag' param is preferable
284 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
286 if ( $i === false && count( $currentLoads ) != 0 ) {
287 # All slaves lagged. Switch to read-only mode
288 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
289 $i = ArrayUtils
::pickRandom( $currentLoads );
290 $laggedSlaveMode = true;
294 if ( $i === false ) {
295 # pickRandom() returned false
296 # This is permanent and means the configuration or the load monitor
297 # wants us to return false.
298 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
303 $serverName = $this->getServerName( $i );
304 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
306 $conn = $this->openConnection( $i, $wiki );
308 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
309 unset( $nonErrorLoads[$i] );
310 unset( $currentLoads[$i] );
315 // Decrement reference counter, we are finished with this connection.
316 // It will be incremented for the caller later.
317 if ( $wiki !== false ) {
318 $this->reuseConnection( $conn );
325 # If all servers were down, quit now
326 if ( !count( $nonErrorLoads ) ) {
327 wfDebugLog( 'connect', "All servers down" );
330 if ( $i !== false ) {
331 # Slave connection successful
332 # Wait for the session master pos for a short time
333 if ( $this->mWaitForPos
&& $i > 0 ) {
334 if ( !$this->doWait( $i ) ) {
335 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
338 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
339 $this->mReadIndex
= $i;
340 # Record if the generic reader index is in "lagged slave" mode
341 if ( $laggedSlaveMode ) {
342 $this->laggedSlaveMode
= true;
345 $serverName = $this->getServerName( $i );
346 wfDebugLog( 'connect', __METHOD__
.
347 ": using server $serverName for group '$group'\n" );
354 * Set the master wait position
355 * If a DB_SLAVE connection has been opened already, waits
356 * Otherwise sets a variable telling it to wait if such a connection is opened
357 * @param DBMasterPos $pos
359 public function waitFor( $pos ) {
360 $this->mWaitForPos
= $pos;
361 $i = $this->mReadIndex
;
364 if ( !$this->doWait( $i ) ) {
365 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
366 $this->laggedSlaveMode
= true;
372 * Set the master wait position and wait for a "generic" slave to catch up to it
374 * This can be used a faster proxy for waitForAll()
376 * @param DBMasterPos $pos
377 * @param int $timeout Max seconds to wait; default is mWaitTimeout
378 * @return bool Success (able to connect and no timeouts reached)
381 public function waitForOne( $pos, $timeout = null ) {
382 $this->mWaitForPos
= $pos;
384 $i = $this->mReadIndex
;
386 // Pick a generic slave if there isn't one yet
387 $readLoads = $this->mLoads
;
388 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
389 $readLoads = array_filter( $readLoads ); // with non-zero load
390 $i = ArrayUtils
::pickRandom( $readLoads );
394 $ok = $this->doWait( $i, true, $timeout );
396 $ok = true; // no applicable loads
403 * Set the master wait position and wait for ALL slaves to catch up to it
404 * @param DBMasterPos $pos
405 * @param int $timeout Max seconds to wait; default is mWaitTimeout
406 * @return bool Success (able to connect and no timeouts reached)
408 public function waitForAll( $pos, $timeout = null ) {
409 $this->mWaitForPos
= $pos;
410 $serverCount = count( $this->mServers
);
413 for ( $i = 1; $i < $serverCount; $i++
) {
414 if ( $this->mLoads
[$i] > 0 ) {
415 $ok = $this->doWait( $i, true, $timeout ) && $ok;
423 * Get any open connection to a given server index, local or foreign
424 * Returns false if there is no connection open
427 * @return DatabaseBase|bool False on failure
429 public function getAnyOpenConnection( $i ) {
430 foreach ( $this->mConns
as $conns ) {
431 if ( !empty( $conns[$i] ) ) {
432 return reset( $conns[$i] );
440 * Wait for a given slave to catch up to the master pos stored in $this
441 * @param int $index Server index
442 * @param bool $open Check the server even if a new connection has to be made
443 * @param int $timeout Max seconds to wait; default is mWaitTimeout
446 protected function doWait( $index, $open = false, $timeout = null ) {
447 $close = false; // close the connection afterwards
449 // Check if we already know that the DB has reached this point
450 $server = $this->getServerName( $index );
451 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
452 /** @var DBMasterPos $knownReachedPos */
453 $knownReachedPos = $this->srvCache
->get( $key );
454 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
455 wfDebugLog( 'replication', __METHOD__
.
456 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
460 // Find a connection to wait on, creating one if needed and allowed
461 $conn = $this->getAnyOpenConnection( $index );
464 wfDebugLog( 'replication', __METHOD__
. ": no connection open for $server\n" );
468 $conn = $this->openConnection( $index, '' );
470 wfDebugLog( 'replication', __METHOD__
. ": failed to connect to $server\n" );
474 // Avoid connection spam in waitForAll() when connections
475 // are made just for the sake of doing this lag check.
480 wfDebugLog( 'replication', __METHOD__
. ": Waiting for slave $server to catch up...\n" );
481 $timeout = $timeout ?
: $this->mWaitTimeout
;
482 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
484 if ( $result == -1 ||
is_null( $result ) ) {
485 // Timed out waiting for slave, use master instead
486 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
487 wfDebugLog( 'replication', "$msg\n" );
488 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
491 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
493 // Remember that the DB reached this point
494 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
498 $this->closeConnection( $conn );
505 * Get a connection by index
506 * This is the main entry point for this class.
508 * @param int $i Server index
509 * @param array|string|bool $groups Query group(s), or false for the generic reader
510 * @param string|bool $wiki Wiki ID, or false for the current wiki
512 * @throws MWException
513 * @return DatabaseBase
515 public function getConnection( $i, $groups = [], $wiki = false ) {
516 if ( $i === null ||
$i === false ) {
517 throw new MWException( 'Attempt to call ' . __METHOD__
.
518 ' with invalid server index' );
521 if ( $wiki === wfWikiID() ) {
525 $groups = ( $groups === false ||
$groups === [] )
526 ?
[ false ] // check one "group": the generic pool
529 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
530 $oldConnsOpened = $this->connsOpened
; // connections open now
532 if ( $i == DB_MASTER
) {
533 $i = $this->getWriterIndex();
535 # Try to find an available server in any the query groups (in order)
536 foreach ( $groups as $group ) {
537 $groupIndex = $this->getReaderIndex( $group, $wiki );
538 if ( $groupIndex !== false ) {
545 # Operation-based index
546 if ( $i == DB_SLAVE
) {
547 $this->mLastError
= 'Unknown error'; // reset error string
548 # Try the general server pool if $groups are unavailable.
549 $i = in_array( false, $groups, true )
550 ?
false // don't bother with this if that is what was tried above
551 : $this->getReaderIndex( false, $wiki );
552 # Couldn't find a working server in getReaderIndex()?
553 if ( $i === false ) {
554 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
556 return $this->reportConnectionError();
560 # Now we have an explicit index into the servers array
561 $conn = $this->openConnection( $i, $wiki );
563 return $this->reportConnectionError();
566 # Profile any new connections that happen
567 if ( $this->connsOpened
> $oldConnsOpened ) {
568 $host = $conn->getServer();
569 $dbname = $conn->getDBname();
570 $trxProf = Profiler
::instance()->getTransactionProfiler();
571 $trxProf->recordConnection( $host, $dbname, $masterOnly );
575 # Make master-requested DB handles inherit any read-only mode setting
576 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
583 * Mark a foreign connection as being available for reuse under a different
584 * DB name or prefix. This mechanism is reference-counted, and must be called
585 * the same number of times as getConnection() to work.
587 * @param DatabaseBase $conn
588 * @throws MWException
590 public function reuseConnection( $conn ) {
591 $serverIndex = $conn->getLBInfo( 'serverIndex' );
592 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
593 if ( $serverIndex === null ||
$refCount === null ) {
594 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
596 * This can happen in code like:
597 * foreach ( $dbs as $db ) {
598 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
600 * $lb->reuseConnection( $conn );
602 * When a connection to the local DB is opened in this way, reuseConnection()
608 $dbName = $conn->getDBname();
609 $prefix = $conn->tablePrefix();
610 if ( strval( $prefix ) !== '' ) {
611 $wiki = "$dbName-$prefix";
615 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
616 throw new MWException( __METHOD__
. ": connection not found, has " .
617 "the connection been freed already?" );
619 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
620 if ( $refCount <= 0 ) {
621 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
622 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
623 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
625 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
630 * Get a database connection handle reference
632 * The handle's methods wrap simply wrap those of a DatabaseBase handle
634 * @see LoadBalancer::getConnection() for parameter information
637 * @param array|string|bool $groups Query group(s), or false for the generic reader
638 * @param string|bool $wiki Wiki ID, or false for the current wiki
641 public function getConnectionRef( $db, $groups = [], $wiki = false ) {
642 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
646 * Get a database connection handle reference without connecting yet
648 * The handle's methods wrap simply wrap those of a DatabaseBase handle
650 * @see LoadBalancer::getConnection() for parameter information
653 * @param array|string|bool $groups Query group(s), or false for the generic reader
654 * @param string|bool $wiki Wiki ID, or false for the current wiki
657 public function getLazyConnectionRef( $db, $groups = [], $wiki = false ) {
658 return new DBConnRef( $this, [ $db, $groups, $wiki ] );
662 * Open a connection to the server given by the specified index
663 * Index must be an actual index into the array.
664 * If the server is already open, returns it.
666 * On error, returns false, and the connection which caused the
667 * error will be available via $this->mErrorConnection.
669 * @param int $i Server index
670 * @param string|bool $wiki Wiki ID, or false for the current wiki
671 * @return DatabaseBase|bool Returns false on errors
673 public function openConnection( $i, $wiki = false ) {
674 if ( $wiki !== false ) {
675 $conn = $this->openForeignConnection( $i, $wiki );
676 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
677 $conn = $this->mConns
['local'][$i][0];
679 $server = $this->mServers
[$i];
680 $server['serverIndex'] = $i;
681 $conn = $this->reallyOpenConnection( $server, false );
682 $serverName = $this->getServerName( $i );
683 if ( $conn->isOpen() ) {
684 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
685 $this->mConns
['local'][$i][0] = $conn;
687 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
688 $this->mErrorConnection
= $conn;
693 if ( $conn && !$conn->isOpen() ) {
694 // Connection was made but later unrecoverably lost for some reason.
695 // Do not return a handle that will just throw exceptions on use,
696 // but let the calling code (e.g. getReaderIndex) try another server.
697 // See DatabaseMyslBase::ping() for how this can happen.
698 $this->mErrorConnection
= $conn;
706 * Open a connection to a foreign DB, or return one if it is already open.
708 * Increments a reference count on the returned connection which locks the
709 * connection to the requested wiki. This reference count can be
710 * decremented by calling reuseConnection().
712 * If a connection is open to the appropriate server already, but with the wrong
713 * database, it will be switched to the right database and returned, as long as
714 * it has been freed first with reuseConnection().
716 * On error, returns false, and the connection which caused the
717 * error will be available via $this->mErrorConnection.
719 * @param int $i Server index
720 * @param string $wiki Wiki ID to open
721 * @return DatabaseBase
723 private function openForeignConnection( $i, $wiki ) {
724 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
725 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
726 // Reuse an already-used connection
727 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
728 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
729 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
730 // Reuse a free connection for the same wiki
731 $conn = $this->mConns
['foreignFree'][$i][$wiki];
732 unset( $this->mConns
['foreignFree'][$i][$wiki] );
733 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
734 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
735 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
736 // Reuse a connection from another wiki
737 $conn = reset( $this->mConns
['foreignFree'][$i] );
738 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
740 // The empty string as a DB name means "don't care".
741 // DatabaseMysqlBase::open() already handle this on connection.
742 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
743 $this->mLastError
= "Error selecting database $dbName on server " .
744 $conn->getServer() . " from client host " . wfHostname() . "\n";
745 $this->mErrorConnection
= $conn;
748 $conn->tablePrefix( $prefix );
749 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
750 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
751 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
754 // Open a new connection
755 $server = $this->mServers
[$i];
756 $server['serverIndex'] = $i;
757 $server['foreignPoolRefCount'] = 0;
758 $server['foreign'] = true;
759 $conn = $this->reallyOpenConnection( $server, $dbName );
760 if ( !$conn->isOpen() ) {
761 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
762 $this->mErrorConnection
= $conn;
765 $conn->tablePrefix( $prefix );
766 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
767 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
771 // Increment reference count
773 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
774 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
781 * Test if the specified index represents an open connection
783 * @param int $index Server index
787 private function isOpen( $index ) {
788 if ( !is_integer( $index ) ) {
792 return (bool)$this->getAnyOpenConnection( $index );
796 * Really opens a connection. Uncached.
797 * Returns a Database object whether or not the connection was successful.
800 * @param array $server
801 * @param bool $dbNameOverride
802 * @throws MWException
803 * @return DatabaseBase
805 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
806 if ( !is_array( $server ) ) {
807 throw new MWException( 'You must update your load-balancing configuration. ' .
808 'See DefaultSettings.php entry for $wgDBservers.' );
811 if ( $dbNameOverride !== false ) {
812 $server['dbname'] = $dbNameOverride;
815 // Let the handle know what the cluster master is (e.g. "db1052")
816 $masterName = $this->getServerName( 0 );
817 $server['clusterMasterHost'] = $masterName;
819 // Log when many connection are made on requests
820 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
821 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
822 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
823 wfBacktrace( true ) );
828 $db = DatabaseBase
::factory( $server['type'], $server );
829 } catch ( DBConnectionError
$e ) {
830 // FIXME: This is probably the ugliest thing I have ever done to
831 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
835 $db->setLBInfo( $server );
836 $db->setLazyMasterHandle(
837 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getWikiID() )
839 $db->setTransactionProfiler( $this->trxProfiler
);
845 * @throws DBConnectionError
848 private function reportConnectionError() {
849 $conn = $this->mErrorConnection
; // The connection which caused the error
851 'method' => __METHOD__
,
852 'last_error' => $this->mLastError
,
855 if ( !is_object( $conn ) ) {
856 // No last connection, probably due to all servers being too busy
858 "LB failure with no last connection. Connection error: {last_error}",
862 // If all servers were busy, mLastError will contain something sensible
863 throw new DBConnectionError( null, $this->mLastError
);
865 $context['db_server'] = $conn->getProperty( 'mServer' );
867 "Connection error: {last_error} ({db_server})",
871 // throws DBConnectionError
872 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
875 return false; /* not reached */
882 public function getWriterIndex() {
887 * Returns true if the specified index is a valid server index
892 public function haveIndex( $i ) {
893 return array_key_exists( $i, $this->mServers
);
897 * Returns true if the specified index is valid and has non-zero load
902 public function isNonZeroLoad( $i ) {
903 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
907 * Get the number of defined servers (not the number of open connections)
911 public function getServerCount() {
912 return count( $this->mServers
);
916 * Get the host name or IP address of the server with the specified index
917 * Prefer a readable name if available.
921 public function getServerName( $i ) {
922 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
923 $name = $this->mServers
[$i]['hostName'];
924 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
925 $name = $this->mServers
[$i]['host'];
930 return ( $name != '' ) ?
$name : 'localhost';
934 * Return the server info structure for a given index, or false if the index is invalid.
938 public function getServerInfo( $i ) {
939 if ( isset( $this->mServers
[$i] ) ) {
940 return $this->mServers
[$i];
947 * Sets the server info structure for the given index. Entry at index $i
948 * is created if it doesn't exist
950 * @param array $serverInfo
952 public function setServerInfo( $i, array $serverInfo ) {
953 $this->mServers
[$i] = $serverInfo;
957 * Get the current master position for chronology control purposes
960 public function getMasterPos() {
961 # If this entire request was served from a slave without opening a connection to the
962 # master (however unlikely that may be), then we can fetch the position from the slave.
963 $masterConn = $this->getAnyOpenConnection( 0 );
964 if ( !$masterConn ) {
965 $serverCount = count( $this->mServers
);
966 for ( $i = 1; $i < $serverCount; $i++
) {
967 $conn = $this->getAnyOpenConnection( $i );
969 return $conn->getSlavePos();
973 return $masterConn->getMasterPos();
980 * Close all open connections
982 public function closeAll() {
983 foreach ( $this->mConns
as $conns2 ) {
984 foreach ( $conns2 as $conns3 ) {
985 /** @var DatabaseBase $conn */
986 foreach ( $conns3 as $conn ) {
996 $this->connsOpened
= 0;
1000 * Close a connection
1001 * Using this function makes sure the LoadBalancer knows the connection is closed.
1002 * If you use $conn->close() directly, the load balancer won't update its state.
1003 * @param DatabaseBase $conn
1005 public function closeConnection( $conn ) {
1007 foreach ( $this->mConns
as $i1 => $conns2 ) {
1008 foreach ( $conns2 as $i2 => $conns3 ) {
1009 foreach ( $conns3 as $i3 => $candidateConn ) {
1010 if ( $conn === $candidateConn ) {
1012 unset( $this->mConns
[$i1][$i2][$i3] );
1013 --$this->connsOpened
;
1026 * Commit transactions on all open connections
1027 * @param string $fname Caller name
1029 public function commitAll( $fname = __METHOD__
) {
1030 foreach ( $this->mConns
as $conns2 ) {
1031 foreach ( $conns2 as $conns3 ) {
1032 /** @var DatabaseBase[] $conns3 */
1033 foreach ( $conns3 as $conn ) {
1034 if ( $conn->trxLevel() ) {
1035 $conn->commit( $fname, 'flush' );
1043 * Issue COMMIT only on master, only if queries were done on connection
1044 * @param string $fname Caller name
1046 public function commitMasterChanges( $fname = __METHOD__
) {
1047 $masterIndex = $this->getWriterIndex();
1048 foreach ( $this->mConns
as $conns2 ) {
1049 if ( empty( $conns2[$masterIndex] ) ) {
1052 /** @var DatabaseBase $conn */
1053 foreach ( $conns2[$masterIndex] as $conn ) {
1054 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1055 $conn->commit( $fname, 'flush' );
1062 * Issue ROLLBACK only on master, only if queries were done on connection
1063 * @param string $fname Caller name
1064 * @throws DBExpectedError
1067 public function rollbackMasterChanges( $fname = __METHOD__
) {
1068 $failedServers = [];
1070 $masterIndex = $this->getWriterIndex();
1071 foreach ( $this->mConns
as $conns2 ) {
1072 if ( empty( $conns2[$masterIndex] ) ) {
1075 /** @var DatabaseBase $conn */
1076 foreach ( $conns2[$masterIndex] as $conn ) {
1077 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1079 $conn->rollback( $fname, 'flush' );
1080 } catch ( DBError
$e ) {
1081 MWExceptionHandler
::logException( $e );
1082 $failedServers[] = $conn->getServer();
1088 if ( $failedServers ) {
1089 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1090 implode( ', ', array_unique( $failedServers ) ) );
1095 * @return bool Whether a master connection is already open
1098 public function hasMasterConnection() {
1099 return $this->isOpen( $this->getWriterIndex() );
1103 * Determine if there are pending changes in a transaction by this thread
1107 public function hasMasterChanges() {
1108 $masterIndex = $this->getWriterIndex();
1109 foreach ( $this->mConns
as $conns2 ) {
1110 if ( empty( $conns2[$masterIndex] ) ) {
1113 /** @var DatabaseBase $conn */
1114 foreach ( $conns2[$masterIndex] as $conn ) {
1115 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1124 * Get the timestamp of the latest write query done by this thread
1126 * @return float|bool UNIX timestamp or false
1128 public function lastMasterChangeTimestamp() {
1130 $masterIndex = $this->getWriterIndex();
1131 foreach ( $this->mConns
as $conns2 ) {
1132 if ( empty( $conns2[$masterIndex] ) ) {
1135 /** @var DatabaseBase $conn */
1136 foreach ( $conns2[$masterIndex] as $conn ) {
1137 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1144 * Check if this load balancer object had any recent or still
1145 * pending writes issued against it by this PHP thread
1147 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1151 public function hasOrMadeRecentMasterChanges( $age = null ) {
1152 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1154 return ( $this->hasMasterChanges()
1155 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1159 * Get the list of callers that have pending master changes
1164 public function pendingMasterChangeCallers() {
1167 $masterIndex = $this->getWriterIndex();
1168 foreach ( $this->mConns
as $conns2 ) {
1169 if ( empty( $conns2[$masterIndex] ) ) {
1172 /** @var DatabaseBase $conn */
1173 foreach ( $conns2[$masterIndex] as $conn ) {
1174 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1182 * @param mixed $value
1185 public function waitTimeout( $value = null ) {
1186 return wfSetVar( $this->mWaitTimeout
, $value );
1190 * @note This method will trigger a DB connection if not yet done
1192 * @param string|bool $wiki Wiki ID, or false for the current wiki
1193 * @return bool Whether the generic connection for reads is highly "lagged"
1195 public function getLaggedSlaveMode( $wiki = false ) {
1196 // No-op if there is only one DB (also avoids recursion)
1197 if ( !$this->laggedSlaveMode
&& $this->getServerCount() > 1 ) {
1199 // See if laggedSlaveMode gets set
1200 $conn = $this->getConnection( DB_SLAVE
, false, $wiki );
1201 $this->reuseConnection( $conn );
1202 } catch ( DBConnectionError
$e ) {
1203 // Avoid expensive re-connect attempts and failures
1204 $this->slavesDownMode
= true;
1205 $this->laggedSlaveMode
= true;
1209 return $this->laggedSlaveMode
;
1213 * @note This method will never cause a new DB connection
1214 * @return bool Whether any generic connection used for reads was highly "lagged"
1217 public function laggedSlaveUsed() {
1218 return $this->laggedSlaveMode
;
1222 * @note This method may trigger a DB connection if not yet done
1223 * @param string|bool $wiki Wiki ID, or false for the current wiki
1224 * @return string|bool Reason the master is read-only or false if it is not
1227 public function getReadOnlyReason( $wiki = false ) {
1228 if ( $this->readOnlyReason
!== false ) {
1229 return $this->readOnlyReason
;
1230 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1231 if ( $this->slavesDownMode
) {
1232 return 'The database has been automatically locked ' .
1233 'until the slave database servers become available';
1235 return 'The database has been automatically locked ' .
1236 'while the slave database servers catch up to the master.';
1244 * Disables/enables lag checks
1245 * @param null|bool $mode
1248 public function allowLagged( $mode = null ) {
1249 if ( $mode === null ) {
1250 return $this->mAllowLagged
;
1252 $this->mAllowLagged
= $mode;
1254 return $this->mAllowLagged
;
1260 public function pingAll() {
1262 foreach ( $this->mConns
as $conns2 ) {
1263 foreach ( $conns2 as $conns3 ) {
1264 /** @var DatabaseBase[] $conns3 */
1265 foreach ( $conns3 as $conn ) {
1266 if ( !$conn->ping() ) {
1277 * Call a function with each open connection object
1278 * @param callable $callback
1279 * @param array $params
1281 public function forEachOpenConnection( $callback, array $params = [] ) {
1282 foreach ( $this->mConns
as $conns2 ) {
1283 foreach ( $conns2 as $conns3 ) {
1284 foreach ( $conns3 as $conn ) {
1285 $mergedParams = array_merge( [ $conn ], $params );
1286 call_user_func_array( $callback, $mergedParams );
1293 * Get the hostname and lag time of the most-lagged slave
1295 * This is useful for maintenance scripts that need to throttle their updates.
1296 * May attempt to open connections to slaves on the default DB. If there is
1297 * no lag, the maximum lag will be reported as -1.
1299 * @param bool|string $wiki Wiki ID, or false for the default database
1300 * @return array ( host, max lag, index of max lagged host )
1302 public function getMaxLag( $wiki = false ) {
1307 if ( $this->getServerCount() <= 1 ) {
1308 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1311 $lagTimes = $this->getLagTimes( $wiki );
1312 foreach ( $lagTimes as $i => $lag ) {
1313 if ( $lag > $maxLag ) {
1315 $host = $this->mServers
[$i]['host'];
1320 return [ $host, $maxLag, $maxIndex ];
1324 * Get an estimate of replication lag (in seconds) for each server
1326 * Results are cached for a short time in memcached/process cache
1328 * Values may be "false" if replication is too broken to estimate
1330 * @param string|bool $wiki
1331 * @return int[] Map of (server index => float|int|bool)
1333 public function getLagTimes( $wiki = false ) {
1334 if ( $this->getServerCount() <= 1 ) {
1335 return [ 0 => 0 ]; // no replication = no lag
1338 # Send the request to the load monitor
1339 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1343 * Get the lag in seconds for a given connection, or zero if this load
1344 * balancer does not have replication enabled.
1346 * This should be used in preference to Database::getLag() in cases where
1347 * replication may not be in use, since there is no way to determine if
1348 * replication is in use at the connection level without running
1349 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1350 * function instead of Database::getLag() avoids a fatal error in this
1351 * case on many installations.
1353 * @param IDatabase $conn
1354 * @return int|bool Returns false on error
1356 public function safeGetLag( IDatabase
$conn ) {
1357 if ( $this->getServerCount() == 1 ) {
1360 return $conn->getLag();
1365 * Wait for a slave DB to reach a specified master position
1367 * This will connect to the master to get an accurate position if $pos is not given
1369 * @param IDatabase $conn Slave DB
1370 * @param DBMasterPos|bool $pos Master position; default: current position
1371 * @param integer $timeout Timeout in seconds
1372 * @return bool Success
1375 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1376 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'slave' ) ) {
1377 return true; // server is not a slave DB
1380 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1382 return false; // something is misconfigured
1385 $result = $conn->masterPosWait( $pos, $timeout );
1386 if ( $result == -1 ||
is_null( $result ) ) {
1387 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1388 wfDebugLog( 'replication', "$msg\n" );
1389 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1392 wfDebugLog( 'replication', __METHOD__
. ": Done\n" );
1400 * Clear the cache for slag lag delay times
1402 * This is only used for testing
1404 public function clearLagTimeCache() {
1405 $this->getLoadMonitor()->clearCaches();