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;
44 /** @var array LBFactory information */
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
51 /** @var bool|DatabaseBase Database connection that caused a problem */
52 private $mErrorConnection;
53 /** @var integer The generic (not query grouped) slave index (of $mServers) */
55 /** @var bool|DBMasterPos False if not set */
57 /** @var bool Whether the generic reader fell back to a lagged slave */
58 private $mLaggedSlaveMode;
59 /** @var string The last DB selection or connection error */
60 private $mLastError = 'Unknown error';
61 /** @var integer Total connections opened */
62 private $connsOpened = 0;
64 /** @var integer Warn when this many connection are held */
65 const CONN_HELD_WARN_THRESHOLD
= 10;
68 * @param array $params Array with keys:
69 * servers Required. Array of server info structures.
70 * loadMonitor Name of a class used to fetch server lag and load.
73 public function __construct( array $params ) {
74 if ( !isset( $params['servers'] ) ) {
75 throw new MWException( __CLASS__
. ': missing servers parameter' );
77 $this->mServers
= $params['servers'];
78 $this->mWaitTimeout
= 10;
80 $this->mReadIndex
= -1;
81 $this->mWriteIndex
= -1;
82 $this->mConns
= array(
84 'foreignUsed' => array(),
85 'foreignFree' => array() );
86 $this->mLoads
= array();
87 $this->mWaitForPos
= false;
88 $this->mLaggedSlaveMode
= false;
89 $this->mErrorConnection
= false;
90 $this->mAllowLagged
= false;
92 if ( isset( $params['loadMonitor'] ) ) {
93 $this->mLoadMonitorClass
= $params['loadMonitor'];
95 $master = reset( $params['servers'] );
96 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
97 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
99 $this->mLoadMonitorClass
= 'LoadMonitorNull';
103 foreach ( $params['servers'] as $i => $server ) {
104 $this->mLoads
[$i] = $server['load'];
105 if ( isset( $server['groupLoads'] ) ) {
106 foreach ( $server['groupLoads'] as $group => $ratio ) {
107 if ( !isset( $this->mGroupLoads
[$group] ) ) {
108 $this->mGroupLoads
[$group] = array();
110 $this->mGroupLoads
[$group][$i] = $ratio;
117 * Get a LoadMonitor instance
119 * @return LoadMonitor
121 private function getLoadMonitor() {
122 if ( !isset( $this->mLoadMonitor
) ) {
123 $class = $this->mLoadMonitorClass
;
124 $this->mLoadMonitor
= new $class( $this );
127 return $this->mLoadMonitor
;
131 * Get or set arbitrary data used by the parent object, usually an LBFactory
135 public function parentInfo( $x = null ) {
136 return wfSetVar( $this->mParentInfo
, $x );
140 * Given an array of non-normalised probabilities, this function will select
141 * an element and return the appropriate key
143 * @deprecated since 1.21, use ArrayUtils::pickRandom()
145 * @param array $weights
146 * @return bool|int|string
148 public function pickRandom( array $weights ) {
149 return ArrayUtils
::pickRandom( $weights );
153 * @param array $loads
154 * @param bool|string $wiki Wiki to get non-lagged for
155 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
156 * @return bool|int|string
158 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
159 $lags = $this->getLagTimes( $wiki );
161 # Unset excessively lagged servers
162 foreach ( $lags as $i => $lag ) {
164 $maxServerLag = $maxLag;
165 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
166 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
168 if ( $lag === false ) {
169 wfDebugLog( 'replication', "Server #$i is not replicating" );
171 } elseif ( $lag > $maxServerLag ) {
172 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
178 # Find out if all the slaves with non-zero load are lagged
180 foreach ( $loads as $load ) {
184 # No appropriate DB servers except maybe the master and some slaves with zero load
185 # Do NOT use the master
186 # Instead, this function will return false, triggering read-only mode,
187 # and a lagged slave will be used instead.
191 if ( count( $loads ) == 0 ) {
195 #wfDebugLog( 'connect', var_export( $loads, true ) );
197 # Return a random representative of the remainder
198 return ArrayUtils
::pickRandom( $loads );
202 * Get the index of the reader connection, which may be a slave
203 * This takes into account load ratios and lag times. It should
204 * always return a consistent index during a given invocation
206 * Side effect: opens connections to databases
207 * @param string|bool $group Query group, or false for the generic reader
208 * @param string|bool $wiki Wiki ID, or false for the current wiki
209 * @throws MWException
210 * @return bool|int|string
212 public function getReaderIndex( $group = false, $wiki = false ) {
215 # @todo FIXME: For now, only go through all this for mysql databases
216 if ( $wgDBtype != 'mysql' ) {
217 return $this->getWriterIndex();
220 if ( count( $this->mServers
) == 1 ) {
221 # Skip the load balancing if there's only one server
223 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
224 # Shortcut if generic reader exists already
225 return $this->mReadIndex
;
228 # Find the relevant load array
229 if ( $group !== false ) {
230 if ( isset( $this->mGroupLoads
[$group] ) ) {
231 $nonErrorLoads = $this->mGroupLoads
[$group];
233 # No loads for this group, return false and the caller can use some other group
234 wfDebug( __METHOD__
. ": no loads for group $group\n" );
239 $nonErrorLoads = $this->mLoads
;
242 if ( !count( $nonErrorLoads ) ) {
243 throw new MWException( "Empty server array given to LoadBalancer" );
246 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
247 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
249 $laggedSlaveMode = false;
251 # No server found yet
253 # First try quickly looking through the available servers for a server that
255 $currentLoads = $nonErrorLoads;
256 while ( count( $currentLoads ) ) {
257 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
258 $i = ArrayUtils
::pickRandom( $currentLoads );
261 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
262 # ChronologyProtecter causes mWaitForPos to be set via sessions.
263 # This triggers doWait() after connect, so it's especially good to
264 # avoid lagged servers so as to avoid just blocking in that method.
265 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
266 # Aim for <= 1 second of waiting (being too picky can backfire)
267 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
269 if ( $i === false ) {
270 # Any server with less lag than it's 'max lag' param is preferable
271 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
273 if ( $i === false && count( $currentLoads ) != 0 ) {
274 # All slaves lagged. Switch to read-only mode
275 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
276 $i = ArrayUtils
::pickRandom( $currentLoads );
277 $laggedSlaveMode = true;
281 if ( $i === false ) {
282 # pickRandom() returned false
283 # This is permanent and means the configuration or the load monitor
284 # wants us to return false.
285 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
290 $serverName = $this->getServerName( $i );
291 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
293 $conn = $this->openConnection( $i, $wiki );
295 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
296 unset( $nonErrorLoads[$i] );
297 unset( $currentLoads[$i] );
302 // Decrement reference counter, we are finished with this connection.
303 // It will be incremented for the caller later.
304 if ( $wiki !== false ) {
305 $this->reuseConnection( $conn );
312 # If all servers were down, quit now
313 if ( !count( $nonErrorLoads ) ) {
314 wfDebugLog( 'connect', "All servers down" );
317 if ( $i !== false ) {
318 # Slave connection successful
319 # Wait for the session master pos for a short time
320 if ( $this->mWaitForPos
&& $i > 0 ) {
321 if ( !$this->doWait( $i ) ) {
322 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
325 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
326 $this->mReadIndex
= $i;
327 # Record if the generic reader index is in "lagged slave" mode
328 if ( $laggedSlaveMode ) {
329 $this->mLaggedSlaveMode
= true;
332 $serverName = $this->getServerName( $i );
333 wfDebug( __METHOD__
. ": using server $serverName for group '$group'\n" );
340 * Set the master wait position
341 * If a DB_SLAVE connection has been opened already, waits
342 * Otherwise sets a variable telling it to wait if such a connection is opened
343 * @param DBMasterPos $pos
345 public function waitFor( $pos ) {
346 $this->mWaitForPos
= $pos;
347 $i = $this->mReadIndex
;
350 if ( !$this->doWait( $i ) ) {
351 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
352 $this->mLaggedSlaveMode
= true;
358 * Set the master wait position and wait for a "generic" slave to catch up to it
360 * This can be used a faster proxy for waitForAll()
362 * @param DBMasterPos $pos
363 * @param int $timeout Max seconds to wait; default is mWaitTimeout
364 * @return bool Success (able to connect and no timeouts reached)
367 public function waitForOne( $pos, $timeout = null ) {
368 $this->mWaitForPos
= $pos;
370 $i = $this->mReadIndex
;
372 // Pick a generic slave if there isn't one yet
373 $readLoads = $this->mLoads
;
374 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
375 $readLoads = array_filter( $readLoads ); // with non-zero load
376 $i = ArrayUtils
::pickRandom( $readLoads );
380 $ok = $this->doWait( $i, true, $timeout );
382 $ok = true; // no applicable loads
389 * Set the master wait position and wait for ALL slaves to catch up to it
390 * @param DBMasterPos $pos
391 * @param int $timeout Max seconds to wait; default is mWaitTimeout
392 * @return bool Success (able to connect and no timeouts reached)
394 public function waitForAll( $pos, $timeout = null ) {
395 $this->mWaitForPos
= $pos;
396 $serverCount = count( $this->mServers
);
399 for ( $i = 1; $i < $serverCount; $i++
) {
400 if ( $this->mLoads
[$i] > 0 ) {
401 $ok = $this->doWait( $i, true, $timeout ) && $ok;
409 * Get any open connection to a given server index, local or foreign
410 * Returns false if there is no connection open
413 * @return DatabaseBase|bool False on failure
415 public function getAnyOpenConnection( $i ) {
416 foreach ( $this->mConns
as $conns ) {
417 if ( !empty( $conns[$i] ) ) {
418 return reset( $conns[$i] );
426 * Wait for a given slave to catch up to the master pos stored in $this
427 * @param int $index Server index
428 * @param bool $open Check the server even if a new connection has to be made
429 * @param int $timeout Max seconds to wait; default is mWaitTimeout
432 protected function doWait( $index, $open = false, $timeout = null ) {
433 $close = false; // close the connection afterwards
435 # Find a connection to wait on, creating one if needed and allowed
436 $conn = $this->getAnyOpenConnection( $index );
439 wfDebug( __METHOD__
. ": no connection open\n" );
443 $conn = $this->openConnection( $index, '' );
445 wfDebug( __METHOD__
. ": failed to open connection\n" );
449 // Avoid connection spam in waitForAll() when connections
450 // are made just for the sake of doing this lag check.
455 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
456 $timeout = $timeout ?
: $this->mWaitTimeout
;
457 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
459 if ( $result == -1 ||
is_null( $result ) ) {
460 # Timed out waiting for slave, use master instead
461 $server = $server = $this->getServerName( $index );
462 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
464 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
467 wfDebug( __METHOD__
. ": Done\n" );
472 $this->closeConnection( $conn );
479 * Get a connection by index
480 * This is the main entry point for this class.
482 * @param int $i Server index
483 * @param array|string|bool $groups Query group(s), or false for the generic reader
484 * @param string|bool $wiki Wiki ID, or false for the current wiki
486 * @throws MWException
487 * @return DatabaseBase
489 public function getConnection( $i, $groups = array(), $wiki = false ) {
490 if ( $i === null ||
$i === false ) {
491 throw new MWException( 'Attempt to call ' . __METHOD__
.
492 ' with invalid server index' );
495 if ( $wiki === wfWikiID() ) {
499 $groups = ( $groups === false ||
$groups === array() )
500 ?
array( false ) // check one "group": the generic pool
503 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
504 $oldConnsOpened = $this->connsOpened
; // connections open now
506 if ( $i == DB_MASTER
) {
507 $i = $this->getWriterIndex();
509 # Try to find an available server in any the query groups (in order)
510 foreach ( $groups as $group ) {
511 $groupIndex = $this->getReaderIndex( $group, $wiki );
512 if ( $groupIndex !== false ) {
519 # Operation-based index
520 if ( $i == DB_SLAVE
) {
521 $this->mLastError
= 'Unknown error'; // reset error string
522 # Try the general server pool if $groups are unavailable.
523 $i = in_array( false, $groups, true )
524 ?
false // don't bother with this if that is what was tried above
525 : $this->getReaderIndex( false, $wiki );
526 # Couldn't find a working server in getReaderIndex()?
527 if ( $i === false ) {
528 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
530 return $this->reportConnectionError();
534 # Now we have an explicit index into the servers array
535 $conn = $this->openConnection( $i, $wiki );
537 return $this->reportConnectionError();
540 # Profile any new connections that happen
541 if ( $this->connsOpened
> $oldConnsOpened ) {
542 $host = $conn->getServer();
543 $dbname = $conn->getDBname();
544 $trxProf = Profiler
::instance()->getTransactionProfiler();
545 $trxProf->recordConnection( $host, $dbname, $masterOnly );
552 * Mark a foreign connection as being available for reuse under a different
553 * DB name or prefix. This mechanism is reference-counted, and must be called
554 * the same number of times as getConnection() to work.
556 * @param DatabaseBase $conn
557 * @throws MWException
559 public function reuseConnection( $conn ) {
560 $serverIndex = $conn->getLBInfo( 'serverIndex' );
561 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
562 if ( $serverIndex === null ||
$refCount === null ) {
563 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
566 * This can happen in code like:
567 * foreach ( $dbs as $db ) {
568 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
570 * $lb->reuseConnection( $conn );
572 * When a connection to the local DB is opened in this way, reuseConnection()
579 $dbName = $conn->getDBname();
580 $prefix = $conn->tablePrefix();
581 if ( strval( $prefix ) !== '' ) {
582 $wiki = "$dbName-$prefix";
586 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
587 throw new MWException( __METHOD__
. ": connection not found, has " .
588 "the connection been freed already?" );
590 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
591 if ( $refCount <= 0 ) {
592 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
593 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
594 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
596 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
601 * Get a database connection handle reference
603 * The handle's methods wrap simply wrap those of a DatabaseBase handle
605 * @see LoadBalancer::getConnection() for parameter information
608 * @param array|string|bool $groups Query group(s), or false for the generic reader
609 * @param string|bool $wiki Wiki ID, or false for the current wiki
612 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
613 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
617 * Get a database connection handle reference without connecting yet
619 * The handle's methods wrap simply wrap those of a DatabaseBase handle
621 * @see LoadBalancer::getConnection() for parameter information
624 * @param array|string|bool $groups Query group(s), or false for the generic reader
625 * @param string|bool $wiki Wiki ID, or false for the current wiki
628 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
629 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
633 * Open a connection to the server given by the specified index
634 * Index must be an actual index into the array.
635 * If the server is already open, returns it.
637 * On error, returns false, and the connection which caused the
638 * error will be available via $this->mErrorConnection.
640 * @param int $i Server index
641 * @param string|bool $wiki Wiki ID, or false for the current wiki
642 * @return DatabaseBase
646 public function openConnection( $i, $wiki = false ) {
647 if ( $wiki !== false ) {
648 $conn = $this->openForeignConnection( $i, $wiki );
649 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
650 $conn = $this->mConns
['local'][$i][0];
652 $server = $this->mServers
[$i];
653 $server['serverIndex'] = $i;
654 $conn = $this->reallyOpenConnection( $server, false );
655 $serverName = $this->getServerName( $i );
656 if ( $conn->isOpen() ) {
657 wfDebug( "Connected to database $i at $serverName\n" );
658 $this->mConns
['local'][$i][0] = $conn;
660 wfDebug( "Failed to connect to database $i at $serverName\n" );
661 $this->mErrorConnection
= $conn;
666 if ( $conn && !$conn->isOpen() ) {
667 // Connection was made but later unrecoverably lost for some reason.
668 // Do not return a handle that will just throw exceptions on use,
669 // but let the calling code (e.g. getReaderIndex) try another server.
670 // See DatabaseMyslBase::ping() for how this can happen.
671 $this->mErrorConnection
= $conn;
679 * Open a connection to a foreign DB, or return one if it is already open.
681 * Increments a reference count on the returned connection which locks the
682 * connection to the requested wiki. This reference count can be
683 * decremented by calling reuseConnection().
685 * If a connection is open to the appropriate server already, but with the wrong
686 * database, it will be switched to the right database and returned, as long as
687 * it has been freed first with reuseConnection().
689 * On error, returns false, and the connection which caused the
690 * error will be available via $this->mErrorConnection.
692 * @param int $i Server index
693 * @param string $wiki Wiki ID to open
694 * @return DatabaseBase
696 private function openForeignConnection( $i, $wiki ) {
697 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
698 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
699 // Reuse an already-used connection
700 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
701 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
702 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
703 // Reuse a free connection for the same wiki
704 $conn = $this->mConns
['foreignFree'][$i][$wiki];
705 unset( $this->mConns
['foreignFree'][$i][$wiki] );
706 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
707 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
708 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
709 // Reuse a connection from another wiki
710 $conn = reset( $this->mConns
['foreignFree'][$i] );
711 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
713 // The empty string as a DB name means "don't care".
714 // DatabaseMysqlBase::open() already handle this on connection.
715 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
716 $this->mLastError
= "Error selecting database $dbName on server " .
717 $conn->getServer() . " from client host " . wfHostname() . "\n";
718 $this->mErrorConnection
= $conn;
721 $conn->tablePrefix( $prefix );
722 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
723 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
724 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
727 // Open a new connection
728 $server = $this->mServers
[$i];
729 $server['serverIndex'] = $i;
730 $server['foreignPoolRefCount'] = 0;
731 $server['foreign'] = true;
732 $conn = $this->reallyOpenConnection( $server, $dbName );
733 if ( !$conn->isOpen() ) {
734 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
735 $this->mErrorConnection
= $conn;
738 $conn->tablePrefix( $prefix );
739 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
740 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
744 // Increment reference count
746 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
747 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
754 * Test if the specified index represents an open connection
756 * @param int $index Server index
760 private function isOpen( $index ) {
761 if ( !is_integer( $index ) ) {
765 return (bool)$this->getAnyOpenConnection( $index );
769 * Really opens a connection. Uncached.
770 * Returns a Database object whether or not the connection was successful.
773 * @param array $server
774 * @param bool $dbNameOverride
775 * @throws MWException
776 * @return DatabaseBase
778 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
779 if ( !is_array( $server ) ) {
780 throw new MWException( 'You must update your load-balancing configuration. ' .
781 'See DefaultSettings.php entry for $wgDBservers.' );
784 if ( $dbNameOverride !== false ) {
785 $server['dbname'] = $dbNameOverride;
788 // Log when many connection are made on requests
789 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
790 $masterAddr = $this->getServerName( 0 );
791 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
792 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
793 wfBacktrace( true ) );
798 $db = DatabaseBase
::factory( $server['type'], $server );
799 } catch ( DBConnectionError
$e ) {
800 // FIXME: This is probably the ugliest thing I have ever done to
801 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
805 $db->setLBInfo( $server );
806 if ( isset( $server['fakeSlaveLag'] ) ) {
807 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
809 if ( isset( $server['fakeMaster'] ) ) {
810 $db->setFakeMaster( true );
817 * @throws DBConnectionError
820 private function reportConnectionError() {
821 $conn = $this->mErrorConnection
; // The connection which caused the error
823 'method' => __METHOD__
,
824 'last_error' => $this->mLastError
,
827 if ( !is_object( $conn ) ) {
828 // No last connection, probably due to all servers being too busy
830 "LB failure with no last connection. Connection error: {last_error}",
834 // If all servers were busy, mLastError will contain something sensible
835 throw new DBConnectionError( null, $this->mLastError
);
837 $context['db_server'] = $conn->getProperty( 'mServer' );
839 "Connection error: {last_error} ({db_server})",
842 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
845 return false; /* not reached */
852 public function getWriterIndex() {
857 * Returns true if the specified index is a valid server index
862 public function haveIndex( $i ) {
863 return array_key_exists( $i, $this->mServers
);
867 * Returns true if the specified index is valid and has non-zero load
872 public function isNonZeroLoad( $i ) {
873 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
877 * Get the number of defined servers (not the number of open connections)
881 public function getServerCount() {
882 return count( $this->mServers
);
886 * Get the host name or IP address of the server with the specified index
887 * Prefer a readable name if available.
891 public function getServerName( $i ) {
892 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
893 $name = $this->mServers
[$i]['hostName'];
894 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
895 $name = $this->mServers
[$i]['host'];
900 return ( $name != '' ) ?
$name : 'localhost';
904 * Return the server info structure for a given index, or false if the index is invalid.
908 public function getServerInfo( $i ) {
909 if ( isset( $this->mServers
[$i] ) ) {
910 return $this->mServers
[$i];
917 * Sets the server info structure for the given index. Entry at index $i
918 * is created if it doesn't exist
920 * @param array $serverInfo
922 public function setServerInfo( $i, array $serverInfo ) {
923 $this->mServers
[$i] = $serverInfo;
927 * Get the current master position for chronology control purposes
930 public function getMasterPos() {
931 # If this entire request was served from a slave without opening a connection to the
932 # master (however unlikely that may be), then we can fetch the position from the slave.
933 $masterConn = $this->getAnyOpenConnection( 0 );
934 if ( !$masterConn ) {
935 $serverCount = count( $this->mServers
);
936 for ( $i = 1; $i < $serverCount; $i++
) {
937 $conn = $this->getAnyOpenConnection( $i );
939 wfDebug( "Master pos fetched from slave\n" );
941 return $conn->getSlavePos();
945 wfDebug( "Master pos fetched from master\n" );
947 return $masterConn->getMasterPos();
954 * Close all open connections
956 public function closeAll() {
957 foreach ( $this->mConns
as $conns2 ) {
958 foreach ( $conns2 as $conns3 ) {
959 /** @var DatabaseBase $conn */
960 foreach ( $conns3 as $conn ) {
965 $this->mConns
= array(
967 'foreignFree' => array(),
968 'foreignUsed' => array(),
970 $this->connsOpened
= 0;
975 * Using this function makes sure the LoadBalancer knows the connection is closed.
976 * If you use $conn->close() directly, the load balancer won't update its state.
977 * @param DatabaseBase $conn
979 public function closeConnection( $conn ) {
981 foreach ( $this->mConns
as $i1 => $conns2 ) {
982 foreach ( $conns2 as $i2 => $conns3 ) {
983 foreach ( $conns3 as $i3 => $candidateConn ) {
984 if ( $conn === $candidateConn ) {
986 unset( $this->mConns
[$i1][$i2][$i3] );
987 --$this->connsOpened
;
1000 * Commit transactions on all open connections
1002 public function commitAll() {
1003 foreach ( $this->mConns
as $conns2 ) {
1004 foreach ( $conns2 as $conns3 ) {
1005 /** @var DatabaseBase[] $conns3 */
1006 foreach ( $conns3 as $conn ) {
1007 if ( $conn->trxLevel() ) {
1008 $conn->commit( __METHOD__
, 'flush' );
1016 * Issue COMMIT only on master, only if queries were done on connection
1018 public function commitMasterChanges() {
1019 $masterIndex = $this->getWriterIndex();
1020 foreach ( $this->mConns
as $conns2 ) {
1021 if ( empty( $conns2[$masterIndex] ) ) {
1024 /** @var DatabaseBase $conn */
1025 foreach ( $conns2[$masterIndex] as $conn ) {
1026 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1027 $conn->commit( __METHOD__
, 'flush' );
1034 * Issue ROLLBACK only on master, only if queries were done on connection
1037 public function rollbackMasterChanges() {
1038 $failedServers = array();
1040 $masterIndex = $this->getWriterIndex();
1041 foreach ( $this->mConns
as $conns2 ) {
1042 if ( empty( $conns2[$masterIndex] ) ) {
1045 /** @var DatabaseBase $conn */
1046 foreach ( $conns2[$masterIndex] as $conn ) {
1047 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1049 $conn->rollback( __METHOD__
, 'flush' );
1050 } catch ( DBError
$e ) {
1051 MWExceptionHandler
::logException( $e );
1052 $failedServers[] = $conn->getServer();
1058 if ( $failedServers ) {
1059 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1060 implode( ', ', array_unique( $failedServers ) ) );
1065 * @return bool Whether a master connection is already open
1068 public function hasMasterConnection() {
1069 return $this->isOpen( $this->getWriterIndex() );
1073 * Determine if there are pending changes in a transaction by this thread
1077 public function hasMasterChanges() {
1078 $masterIndex = $this->getWriterIndex();
1079 foreach ( $this->mConns
as $conns2 ) {
1080 if ( empty( $conns2[$masterIndex] ) ) {
1083 /** @var DatabaseBase $conn */
1084 foreach ( $conns2[$masterIndex] as $conn ) {
1085 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1094 * Get the timestamp of the latest write query done by this thread
1096 * @return float|bool UNIX timestamp or false
1098 public function lastMasterChangeTimestamp() {
1100 $masterIndex = $this->getWriterIndex();
1101 foreach ( $this->mConns
as $conns2 ) {
1102 if ( empty( $conns2[$masterIndex] ) ) {
1105 /** @var DatabaseBase $conn */
1106 foreach ( $conns2[$masterIndex] as $conn ) {
1107 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1114 * Check if this load balancer object had any recent or still
1115 * pending writes issued against it by this PHP thread
1117 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1121 public function hasOrMadeRecentMasterChanges( $age = null ) {
1122 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1124 return ( $this->hasMasterChanges()
1125 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1129 * @param mixed $value
1132 public function waitTimeout( $value = null ) {
1133 return wfSetVar( $this->mWaitTimeout
, $value );
1137 * @return bool Whether the generic connection for reads is highly "lagged"
1139 public function getLaggedSlaveMode() {
1140 # Get a generic reader connection
1141 $this->getConnection( DB_SLAVE
);
1143 return $this->mLaggedSlaveMode
;
1147 * Disables/enables lag checks
1148 * @param null|bool $mode
1151 public function allowLagged( $mode = null ) {
1152 if ( $mode === null ) {
1153 return $this->mAllowLagged
;
1155 $this->mAllowLagged
= $mode;
1157 return $this->mAllowLagged
;
1163 public function pingAll() {
1165 foreach ( $this->mConns
as $conns2 ) {
1166 foreach ( $conns2 as $conns3 ) {
1167 /** @var DatabaseBase[] $conns3 */
1168 foreach ( $conns3 as $conn ) {
1169 if ( !$conn->ping() ) {
1180 * Call a function with each open connection object
1181 * @param callable $callback
1182 * @param array $params
1184 public function forEachOpenConnection( $callback, array $params = array() ) {
1185 foreach ( $this->mConns
as $conns2 ) {
1186 foreach ( $conns2 as $conns3 ) {
1187 foreach ( $conns3 as $conn ) {
1188 $mergedParams = array_merge( array( $conn ), $params );
1189 call_user_func_array( $callback, $mergedParams );
1196 * Get the hostname and lag time of the most-lagged slave
1198 * This is useful for maintenance scripts that need to throttle their updates.
1199 * May attempt to open connections to slaves on the default DB. If there is
1200 * no lag, the maximum lag will be reported as -1.
1202 * @param bool|string $wiki Wiki ID, or false for the default database
1203 * @return array ( host, max lag, index of max lagged host )
1205 public function getMaxLag( $wiki = false ) {
1210 if ( $this->getServerCount() <= 1 ) {
1211 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1214 $lagTimes = $this->getLagTimes( $wiki );
1215 foreach ( $lagTimes as $i => $lag ) {
1216 if ( $lag > $maxLag ) {
1218 $host = $this->mServers
[$i]['host'];
1223 return array( $host, $maxLag, $maxIndex );
1227 * Get lag time for each server
1229 * Results are cached for a short time in memcached/process cache
1231 * @param string|bool $wiki
1232 * @return int[] Map of (server index => seconds)
1234 public function getLagTimes( $wiki = false ) {
1235 if ( $this->getServerCount() <= 1 ) {
1236 return array( 0 => 0 ); // no replication = no lag
1239 # Send the request to the load monitor
1240 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1244 * Get the lag in seconds for a given connection, or zero if this load
1245 * balancer does not have replication enabled.
1247 * This should be used in preference to Database::getLag() in cases where
1248 * replication may not be in use, since there is no way to determine if
1249 * replication is in use at the connection level without running
1250 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1251 * function instead of Database::getLag() avoids a fatal error in this
1252 * case on many installations.
1254 * @param DatabaseBase $conn
1257 public function safeGetLag( $conn ) {
1258 if ( $this->getServerCount() == 1 ) {
1261 return $conn->getLag();
1266 * Clear the cache for slag lag delay times
1268 * This is only used for testing
1270 public function clearLagTimeCache() {
1271 $this->getLoadMonitor()->clearCaches();