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 private $mServers, $mConns, $mLoads, $mGroupLoads;
33 /** @var bool|DatabaseBase Database connection that caused a problem */
34 private $mErrorConnection;
35 private $mReadIndex, $mAllowLagged;
37 /** @var bool|DBMasterPos False if not set */
40 private $mWaitTimeout;
41 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
42 private $mParentInfo, $mLagTimes;
43 private $mLoadMonitorClass, $mLoadMonitor;
46 * @param array $params with keys:
47 * servers Required. Array of server info structures.
48 * masterWaitTimeout Replication lag wait timeout
49 * loadMonitor Name of a class used to fetch server lag and load.
52 function __construct( $params ) {
53 if ( !isset( $params['servers'] ) ) {
54 throw new MWException( __CLASS__
. ': missing servers parameter' );
56 $this->mServers
= $params['servers'];
58 if ( isset( $params['waitTimeout'] ) ) {
59 $this->mWaitTimeout
= $params['waitTimeout'];
61 $this->mWaitTimeout
= 10;
64 $this->mReadIndex
= -1;
65 $this->mWriteIndex
= -1;
66 $this->mConns
= array(
68 'foreignUsed' => array(),
69 'foreignFree' => array() );
70 $this->mLoads
= array();
71 $this->mWaitForPos
= false;
72 $this->mLaggedSlaveMode
= false;
73 $this->mErrorConnection
= false;
74 $this->mAllowLagged
= false;
76 if ( isset( $params['loadMonitor'] ) ) {
77 $this->mLoadMonitorClass
= $params['loadMonitor'];
79 $master = reset( $params['servers'] );
80 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
81 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
83 $this->mLoadMonitorClass
= 'LoadMonitorNull';
87 foreach ( $params['servers'] as $i => $server ) {
88 $this->mLoads
[$i] = $server['load'];
89 if ( isset( $server['groupLoads'] ) ) {
90 foreach ( $server['groupLoads'] as $group => $ratio ) {
91 if ( !isset( $this->mGroupLoads
[$group] ) ) {
92 $this->mGroupLoads
[$group] = array();
94 $this->mGroupLoads
[$group][$i] = $ratio;
101 * Get a LoadMonitor instance
103 * @return LoadMonitor
105 function getLoadMonitor() {
106 if ( !isset( $this->mLoadMonitor
) ) {
107 $class = $this->mLoadMonitorClass
;
108 $this->mLoadMonitor
= new $class( $this );
111 return $this->mLoadMonitor
;
115 * Get or set arbitrary data used by the parent object, usually an LBFactory
119 function parentInfo( $x = null ) {
120 return wfSetVar( $this->mParentInfo
, $x );
124 * Given an array of non-normalised probabilities, this function will select
125 * an element and return the appropriate key
127 * @deprecated since 1.21, use ArrayUtils::pickRandom()
129 * @param array $weights
130 * @return bool|int|string
132 function pickRandom( $weights ) {
133 return ArrayUtils
::pickRandom( $weights );
137 * @param array $loads
138 * @param bool|string $wiki Wiki to get non-lagged for
139 * @return bool|int|string
141 function getRandomNonLagged( $loads, $wiki = false ) {
142 # Unset excessively lagged servers
143 $lags = $this->getLagTimes( $wiki );
144 foreach ( $lags as $i => $lag ) {
146 if ( $lag === false ) {
147 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
149 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
150 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
156 # Find out if all the slaves with non-zero load are lagged
158 foreach ( $loads as $load ) {
162 # No appropriate DB servers except maybe the master and some slaves with zero load
163 # Do NOT use the master
164 # Instead, this function will return false, triggering read-only mode,
165 # and a lagged slave will be used instead.
169 if ( count( $loads ) == 0 ) {
173 #wfDebugLog( 'connect', var_export( $loads, true ) );
175 # Return a random representative of the remainder
176 return ArrayUtils
::pickRandom( $loads );
180 * Get the index of the reader connection, which may be a slave
181 * This takes into account load ratios and lag times. It should
182 * always return a consistent index during a given invocation
184 * Side effect: opens connections to databases
185 * @param bool|string $group
186 * @param bool|string $wiki
187 * @throws MWException
188 * @return bool|int|string
190 function getReaderIndex( $group = false, $wiki = false ) {
191 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
193 # @todo FIXME: For now, only go through all this for mysql databases
194 if ( $wgDBtype != 'mysql' ) {
195 return $this->getWriterIndex();
198 if ( count( $this->mServers
) == 1 ) {
199 # Skip the load balancing if there's only one server
201 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
202 # Shortcut if generic reader exists already
203 return $this->mReadIndex
;
206 wfProfileIn( __METHOD__
);
210 # convert from seconds to microseconds
211 $timeout = $wgDBClusterTimeout * 1e6
;
213 # Find the relevant load array
214 if ( $group !== false ) {
215 if ( isset( $this->mGroupLoads
[$group] ) ) {
216 $nonErrorLoads = $this->mGroupLoads
[$group];
218 # No loads for this group, return false and the caller can use some other group
219 wfDebug( __METHOD__
. ": no loads for group $group\n" );
220 wfProfileOut( __METHOD__
);
225 $nonErrorLoads = $this->mLoads
;
228 if ( !$nonErrorLoads ) {
229 wfProfileOut( __METHOD__
);
230 throw new MWException( "Empty server array given to LoadBalancer" );
233 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
234 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
236 $laggedSlaveMode = false;
238 # First try quickly looking through the available servers for a server that
241 $totalThreadsConnected = 0;
242 $overloadedServers = 0;
243 $currentLoads = $nonErrorLoads;
244 while ( count( $currentLoads ) ) {
245 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
246 $i = ArrayUtils
::pickRandom( $currentLoads );
248 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
249 if ( $i === false && count( $currentLoads ) != 0 ) {
250 # All slaves lagged. Switch to read-only mode
251 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
252 $wgReadOnly = 'The database has been automatically locked ' .
253 'while the slave database servers catch up to the master';
254 $i = ArrayUtils
::pickRandom( $currentLoads );
255 $laggedSlaveMode = true;
259 if ( $i === false ) {
260 # pickRandom() returned false
261 # This is permanent and means the configuration or the load monitor
262 # wants us to return false.
263 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false\n" );
264 wfProfileOut( __METHOD__
);
269 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
270 $conn = $this->openConnection( $i, $wiki );
273 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki\n" );
274 unset( $nonErrorLoads[$i] );
275 unset( $currentLoads[$i] );
279 // Perform post-connection backoff
280 $threshold = isset( $this->mServers
[$i]['max threads'] )
281 ?
$this->mServers
[$i]['max threads'] : 0;
282 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
284 // Decrement reference counter, we are finished with this connection.
285 // It will be incremented for the caller later.
286 if ( $wiki !== false ) {
287 $this->reuseConnection( $conn );
291 # Post-connection overload, don't use this server for now
292 $totalThreadsConnected +
= $backoff;
293 $overloadedServers++
;
294 unset( $currentLoads[$i] );
301 # No server found yet
304 # If all servers were down, quit now
305 if ( !count( $nonErrorLoads ) ) {
306 wfDebugLog( 'connect', "All servers down\n" );
310 # Some servers must have been overloaded
311 if ( $overloadedServers == 0 ) {
312 throw new MWException( __METHOD__
. ": unexpectedly found no overloaded servers" );
314 # Back off for a while
315 # Scale the sleep time by the number of connected threads, to produce a
316 # roughly constant global poll rate
317 $avgThreads = $totalThreadsConnected / $overloadedServers;
318 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
319 } while ( $totalElapsed < $timeout );
321 if ( $totalElapsed >= $timeout ) {
322 wfDebugLog( 'connect', "All servers busy\n" );
323 $this->mErrorConnection
= false;
324 $this->mLastError
= 'All servers busy';
327 if ( $i !== false ) {
328 # Slave connection successful
329 # Wait for the session master pos for a short time
330 if ( $this->mWaitForPos
&& $i > 0 ) {
331 if ( !$this->doWait( $i ) ) {
332 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
335 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $i !== false ) {
336 $this->mReadIndex
= $i;
339 wfProfileOut( __METHOD__
);
345 * Wait for a specified number of microseconds, and return the period waited
349 function sleep( $t ) {
350 wfProfileIn( __METHOD__
);
351 wfDebug( __METHOD__
. ": waiting $t us\n" );
353 wfProfileOut( __METHOD__
);
359 * Set the master wait position
360 * If a DB_SLAVE connection has been opened already, waits
361 * Otherwise sets a variable telling it to wait if such a connection is opened
362 * @param DBMasterPos $pos
364 public function waitFor( $pos ) {
365 wfProfileIn( __METHOD__
);
366 $this->mWaitForPos
= $pos;
367 $i = $this->mReadIndex
;
370 if ( !$this->doWait( $i ) ) {
371 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
372 $this->mLaggedSlaveMode
= true;
375 wfProfileOut( __METHOD__
);
379 * Set the master wait position and wait for ALL slaves to catch up to it
380 * @param DBMasterPos $pos
382 public function waitForAll( $pos ) {
383 wfProfileIn( __METHOD__
);
384 $this->mWaitForPos
= $pos;
385 $serverCount = count( $this->mServers
);
386 for ( $i = 1; $i < $serverCount; $i++
) {
387 if ( $this->mLoads
[$i] > 0 ) {
388 $this->doWait( $i, true );
391 wfProfileOut( __METHOD__
);
395 * Get any open connection to a given server index, local or foreign
396 * Returns false if there is no connection open
399 * @return DatabaseBase|bool False on failure
401 function getAnyOpenConnection( $i ) {
402 foreach ( $this->mConns
as $conns ) {
403 if ( !empty( $conns[$i] ) ) {
404 return reset( $conns[$i] );
412 * Wait for a given slave to catch up to the master pos stored in $this
417 protected function doWait( $index, $open = false ) {
418 # Find a connection to wait on
419 $conn = $this->getAnyOpenConnection( $index );
422 wfDebug( __METHOD__
. ": no connection open\n" );
426 $conn = $this->openConnection( $index, '' );
428 wfDebug( __METHOD__
. ": failed to open connection\n" );
435 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
436 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
438 if ( $result == -1 ||
is_null( $result ) ) {
439 # Timed out waiting for slave, use master instead
440 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
444 wfDebug( __METHOD__
. ": Done\n" );
451 * Get a connection by index
452 * This is the main entry point for this class.
454 * @param $i Integer: server index
455 * @param array $groups query groups
456 * @param bool|string $wiki Wiki ID
458 * @throws MWException
459 * @return DatabaseBase
461 public function &getConnection( $i, $groups = array(), $wiki = false ) {
462 wfProfileIn( __METHOD__
);
464 if ( $i == DB_LAST
) {
465 wfProfileOut( __METHOD__
);
466 throw new MWException( 'Attempt to call ' . __METHOD__
.
467 ' with deprecated server index DB_LAST' );
468 } elseif ( $i === null ||
$i === false ) {
469 wfProfileOut( __METHOD__
);
470 throw new MWException( 'Attempt to call ' . __METHOD__
.
471 ' with invalid server index' );
474 if ( $wiki === wfWikiID() ) {
479 if ( $i == DB_MASTER
) {
480 $i = $this->getWriterIndex();
481 } elseif ( !is_array( $groups ) ) {
482 $groupIndex = $this->getReaderIndex( $groups, $wiki );
483 if ( $groupIndex !== false ) {
484 $serverName = $this->getServerName( $groupIndex );
485 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
489 foreach ( $groups as $group ) {
490 $groupIndex = $this->getReaderIndex( $group, $wiki );
491 if ( $groupIndex !== false ) {
492 $serverName = $this->getServerName( $groupIndex );
493 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
500 # Operation-based index
501 if ( $i == DB_SLAVE
) {
502 $this->mLastError
= 'Unknown error'; // reset error string
503 $i = $this->getReaderIndex( false, $wiki );
504 # Couldn't find a working server in getReaderIndex()?
505 if ( $i === false ) {
506 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
507 wfProfileOut( __METHOD__
);
509 return $this->reportConnectionError();
513 # Now we have an explicit index into the servers array
514 $conn = $this->openConnection( $i, $wiki );
516 wfProfileOut( __METHOD__
);
518 return $this->reportConnectionError();
521 wfProfileOut( __METHOD__
);
527 * Mark a foreign connection as being available for reuse under a different
528 * DB name or prefix. This mechanism is reference-counted, and must be called
529 * the same number of times as getConnection() to work.
531 * @param DatabaseBase $conn
532 * @throws MWException
534 public function reuseConnection( $conn ) {
535 $serverIndex = $conn->getLBInfo( 'serverIndex' );
536 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
537 $dbName = $conn->getDBname();
538 $prefix = $conn->tablePrefix();
539 if ( strval( $prefix ) !== '' ) {
540 $wiki = "$dbName-$prefix";
544 if ( $serverIndex === null ||
$refCount === null ) {
545 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
548 * This can happen in code like:
549 * foreach ( $dbs as $db ) {
550 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
552 * $lb->reuseConnection( $conn );
554 * When a connection to the local DB is opened in this way, reuseConnection()
560 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
561 throw new MWException( __METHOD__
. ": connection not found, has " .
562 "the connection been freed already?" );
564 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
565 if ( $refCount <= 0 ) {
566 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
567 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
568 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
570 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
575 * Get a database connection handle reference
577 * The handle's methods wrap simply wrap those of a DatabaseBase handle
579 * @see LoadBalancer::getConnection() for parameter information
582 * @param mixed $groups
583 * @param bool|string $wiki
586 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
587 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
591 * Get a database connection handle reference without connecting yet
593 * The handle's methods wrap simply wrap those of a DatabaseBase handle
595 * @see LoadBalancer::getConnection() for parameter information
598 * @param mixed $groups
599 * @param bool|string $wiki
602 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
603 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
607 * Open a connection to the server given by the specified index
608 * Index must be an actual index into the array.
609 * If the server is already open, returns it.
611 * On error, returns false, and the connection which caused the
612 * error will be available via $this->mErrorConnection.
614 * @param $i Integer server index
615 * @param bool|string $wiki wiki ID to open
616 * @return DatabaseBase
620 function openConnection( $i, $wiki = false ) {
621 wfProfileIn( __METHOD__
);
622 if ( $wiki !== false ) {
623 $conn = $this->openForeignConnection( $i, $wiki );
624 wfProfileOut( __METHOD__
);
628 if ( isset( $this->mConns
['local'][$i][0] ) ) {
629 $conn = $this->mConns
['local'][$i][0];
631 $server = $this->mServers
[$i];
632 $server['serverIndex'] = $i;
633 $conn = $this->reallyOpenConnection( $server, false );
634 if ( $conn->isOpen() ) {
635 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
636 $this->mConns
['local'][$i][0] = $conn;
638 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
639 $this->mErrorConnection
= $conn;
643 wfProfileOut( __METHOD__
);
649 * Open a connection to a foreign DB, or return one if it is already open.
651 * Increments a reference count on the returned connection which locks the
652 * connection to the requested wiki. This reference count can be
653 * decremented by calling reuseConnection().
655 * If a connection is open to the appropriate server already, but with the wrong
656 * database, it will be switched to the right database and returned, as long as
657 * it has been freed first with reuseConnection().
659 * On error, returns false, and the connection which caused the
660 * error will be available via $this->mErrorConnection.
662 * @param $i Integer: server index
663 * @param string $wiki wiki ID to open
664 * @return DatabaseBase
666 function openForeignConnection( $i, $wiki ) {
667 wfProfileIn( __METHOD__
);
668 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
669 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
670 // Reuse an already-used connection
671 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
672 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
673 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
674 // Reuse a free connection for the same wiki
675 $conn = $this->mConns
['foreignFree'][$i][$wiki];
676 unset( $this->mConns
['foreignFree'][$i][$wiki] );
677 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
678 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
679 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
680 // Reuse a connection from another wiki
681 $conn = reset( $this->mConns
['foreignFree'][$i] );
682 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
684 if ( !$conn->selectDB( $dbName ) ) {
685 $this->mLastError
= "Error selecting database $dbName on server " .
686 $conn->getServer() . " from client host " . wfHostname() . "\n";
687 $this->mErrorConnection
= $conn;
690 $conn->tablePrefix( $prefix );
691 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
692 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
693 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
696 // Open a new connection
697 $server = $this->mServers
[$i];
698 $server['serverIndex'] = $i;
699 $server['foreignPoolRefCount'] = 0;
700 $server['foreign'] = true;
701 $conn = $this->reallyOpenConnection( $server, $dbName );
702 if ( !$conn->isOpen() ) {
703 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
704 $this->mErrorConnection
= $conn;
707 $conn->tablePrefix( $prefix );
708 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
709 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
713 // Increment reference count
715 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
716 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
718 wfProfileOut( __METHOD__
);
724 * Test if the specified index represents an open connection
726 * @param $index Integer: server index
730 function isOpen( $index ) {
731 if ( !is_integer( $index ) ) {
735 return (bool)$this->getAnyOpenConnection( $index );
739 * Really opens a connection. Uncached.
740 * Returns a Database object whether or not the connection was successful.
744 * @param $dbNameOverride bool
745 * @throws MWException
746 * @return DatabaseBase
748 function reallyOpenConnection( $server, $dbNameOverride = false ) {
749 if ( !is_array( $server ) ) {
750 throw new MWException( 'You must update your load-balancing configuration. ' .
751 'See DefaultSettings.php entry for $wgDBservers.' );
754 if ( $dbNameOverride !== false ) {
755 $server['dbname'] = $dbNameOverride;
760 $db = DatabaseBase
::factory( $server['type'], $server );
761 } catch ( DBConnectionError
$e ) {
762 // FIXME: This is probably the ugliest thing I have ever done to
763 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
767 $db->setLBInfo( $server );
768 if ( isset( $server['fakeSlaveLag'] ) ) {
769 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
771 if ( isset( $server['fakeMaster'] ) ) {
772 $db->setFakeMaster( true );
779 * @throws DBConnectionError
782 private function reportConnectionError() {
783 $conn = $this->mErrorConnection
; // The connection which caused the error
785 if ( !is_object( $conn ) ) {
786 // No last connection, probably due to all servers being too busy
787 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
789 // If all servers were busy, mLastError will contain something sensible
790 throw new DBConnectionError( null, $this->mLastError
);
792 $server = $conn->getProperty( 'mServer' );
793 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
794 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
797 return false; /* not reached */
803 function getWriterIndex() {
808 * Returns true if the specified index is a valid server index
813 function haveIndex( $i ) {
814 return array_key_exists( $i, $this->mServers
);
818 * Returns true if the specified index is valid and has non-zero load
823 function isNonZeroLoad( $i ) {
824 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
828 * Get the number of defined servers (not the number of open connections)
832 function getServerCount() {
833 return count( $this->mServers
);
837 * Get the host name or IP address of the server with the specified index
838 * Prefer a readable name if available.
842 function getServerName( $i ) {
843 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
844 return $this->mServers
[$i]['hostName'];
845 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
846 return $this->mServers
[$i]['host'];
853 * Return the server info structure for a given index, or false if the index is invalid.
857 function getServerInfo( $i ) {
858 if ( isset( $this->mServers
[$i] ) ) {
859 return $this->mServers
[$i];
866 * Sets the server info structure for the given index. Entry at index $i
867 * is created if it doesn't exist
871 function setServerInfo( $i, $serverInfo ) {
872 $this->mServers
[$i] = $serverInfo;
876 * Get the current master position for chronology control purposes
879 function getMasterPos() {
880 # If this entire request was served from a slave without opening a connection to the
881 # master (however unlikely that may be), then we can fetch the position from the slave.
882 $masterConn = $this->getAnyOpenConnection( 0 );
883 if ( !$masterConn ) {
884 $serverCount = count( $this->mServers
);
885 for ( $i = 1; $i < $serverCount; $i++
) {
886 $conn = $this->getAnyOpenConnection( $i );
888 wfDebug( "Master pos fetched from slave\n" );
890 return $conn->getSlavePos();
894 wfDebug( "Master pos fetched from master\n" );
896 return $masterConn->getMasterPos();
903 * Close all open connections
905 function closeAll() {
906 foreach ( $this->mConns
as $conns2 ) {
907 foreach ( $conns2 as $conns3 ) {
908 /** @var DatabaseBase $conn */
909 foreach ( $conns3 as $conn ) {
914 $this->mConns
= array(
916 'foreignFree' => array(),
917 'foreignUsed' => array(),
922 * Deprecated function, typo in function name
924 * @deprecated in 1.18
925 * @param DatabaseBase $conn
927 function closeConnecton( $conn ) {
928 wfDeprecated( __METHOD__
, '1.18' );
929 $this->closeConnection( $conn );
934 * Using this function makes sure the LoadBalancer knows the connection is closed.
935 * If you use $conn->close() directly, the load balancer won't update its state.
936 * @param DatabaseBase $conn
938 function closeConnection( $conn ) {
940 foreach ( $this->mConns
as $i1 => $conns2 ) {
941 foreach ( $conns2 as $i2 => $conns3 ) {
942 foreach ( $conns3 as $i3 => $candidateConn ) {
943 if ( $conn === $candidateConn ) {
945 unset( $this->mConns
[$i1][$i2][$i3] );
958 * Commit transactions on all open connections
960 function commitAll() {
961 foreach ( $this->mConns
as $conns2 ) {
962 foreach ( $conns2 as $conns3 ) {
963 /** @var DatabaseBase[] $conns3 */
964 foreach ( $conns3 as $conn ) {
965 if ( $conn->trxLevel() ) {
966 $conn->commit( __METHOD__
, 'flush' );
974 * Issue COMMIT only on master, only if queries were done on connection
976 function commitMasterChanges() {
977 // Always 0, but who knows.. :)
978 $masterIndex = $this->getWriterIndex();
979 foreach ( $this->mConns
as $conns2 ) {
980 if ( empty( $conns2[$masterIndex] ) ) {
983 /** @var DatabaseBase $conn */
984 foreach ( $conns2[$masterIndex] as $conn ) {
985 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
986 $conn->commit( __METHOD__
, 'flush' );
996 function waitTimeout( $value = null ) {
997 return wfSetVar( $this->mWaitTimeout
, $value );
1003 function getLaggedSlaveMode() {
1004 return $this->mLaggedSlaveMode
;
1008 * Disables/enables lag checks
1009 * @param null|bool $mode
1012 function allowLagged( $mode = null ) {
1013 if ( $mode === null ) {
1014 return $this->mAllowLagged
;
1016 $this->mAllowLagged
= $mode;
1018 return $this->mAllowLagged
;
1024 function pingAll() {
1026 foreach ( $this->mConns
as $conns2 ) {
1027 foreach ( $conns2 as $conns3 ) {
1028 /** @var DatabaseBase[] $conns3 */
1029 foreach ( $conns3 as $conn ) {
1030 if ( !$conn->ping() ) {
1041 * Call a function with each open connection object
1042 * @param callable $callback
1043 * @param array $params
1045 function forEachOpenConnection( $callback, $params = array() ) {
1046 foreach ( $this->mConns
as $conns2 ) {
1047 foreach ( $conns2 as $conns3 ) {
1048 foreach ( $conns3 as $conn ) {
1049 $mergedParams = array_merge( array( $conn ), $params );
1050 call_user_func_array( $callback, $mergedParams );
1057 * Get the hostname and lag time of the most-lagged slave.
1058 * This is useful for maintenance scripts that need to throttle their updates.
1059 * May attempt to open connections to slaves on the default DB. If there is
1060 * no lag, the maximum lag will be reported as -1.
1062 * @param bool|string $wiki Wiki ID, or false for the default database
1063 * @return array ( host, max lag, index of max lagged host )
1065 function getMaxLag( $wiki = false ) {
1069 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1070 foreach ( $this->mServers
as $i => $conn ) {
1072 if ( $wiki === false ) {
1073 $conn = $this->getAnyOpenConnection( $i );
1076 $conn = $this->openConnection( $i, $wiki );
1081 $lag = $conn->getLag();
1082 if ( $lag > $maxLag ) {
1084 $host = $this->mServers
[$i]['host'];
1090 return array( $host, $maxLag, $maxIndex );
1094 * Get lag time for each server
1095 * Results are cached for a short time in memcached, and indefinitely in the process cache
1097 * @param string|bool $wiki
1100 function getLagTimes( $wiki = false ) {
1102 if ( isset( $this->mLagTimes
) ) {
1103 return $this->mLagTimes
;
1105 if ( $this->getServerCount() == 1 ) {
1107 $this->mLagTimes
= array( 0 => 0 );
1109 # Send the request to the load monitor
1110 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1111 array_keys( $this->mServers
), $wiki );
1114 return $this->mLagTimes
;
1118 * Get the lag in seconds for a given connection, or zero if this load
1119 * balancer does not have replication enabled.
1121 * This should be used in preference to Database::getLag() in cases where
1122 * replication may not be in use, since there is no way to determine if
1123 * replication is in use at the connection level without running
1124 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1125 * function instead of Database::getLag() avoids a fatal error in this
1126 * case on many installations.
1128 * @param DatabaseBase $conn
1131 function safeGetLag( $conn ) {
1132 if ( $this->getServerCount() == 1 ) {
1135 return $conn->getLag();
1140 * Clear the cache for getLagTimes
1142 function clearLagTimeCache() {
1143 $this->mLagTimes
= null;
1148 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1149 * as well handling deferring the actual network connection until the handle is used
1154 class DBConnRef
implements IDatabase
{
1155 /** @var LoadBalancer */
1158 /** @var DatabaseBase|null */
1161 /** @var array|null */
1165 * @param LoadBalancer $lb
1166 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1168 public function __construct( LoadBalancer
$lb, $conn ) {
1170 if ( $conn instanceof DatabaseBase
) {
1171 $this->conn
= $conn;
1173 $this->params
= $conn;
1177 public function __call( $name, $arguments ) {
1178 if ( $this->conn
=== null ) {
1179 list( $db, $groups, $wiki ) = $this->params
;
1180 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1183 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1186 function __destruct() {
1187 if ( $this->conn
!== null ) {
1188 $this->lb
->reuseConnection( $this->conn
);