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;
32 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
40 * @param $params Array with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
45 function __construct( $params ) {
46 if ( !isset( $params['servers'] ) ) {
47 throw new MWException( __CLASS__
.': missing servers parameter' );
49 $this->mServers
= $params['servers'];
51 if ( isset( $params['waitTimeout'] ) ) {
52 $this->mWaitTimeout
= $params['waitTimeout'];
54 $this->mWaitTimeout
= 10;
57 $this->mReadIndex
= -1;
58 $this->mWriteIndex
= -1;
59 $this->mConns
= array(
61 'foreignUsed' => array(),
62 'foreignFree' => array() );
63 $this->mLoads
= array();
64 $this->mWaitForPos
= false;
65 $this->mLaggedSlaveMode
= false;
66 $this->mErrorConnection
= false;
67 $this->mAllowLagged
= false;
69 if ( isset( $params['loadMonitor'] ) ) {
70 $this->mLoadMonitorClass
= $params['loadMonitor'];
72 $master = reset( $params['servers'] );
73 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
74 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
76 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
80 foreach( $params['servers'] as $i => $server ) {
81 $this->mLoads
[$i] = $server['load'];
82 if ( isset( $server['groupLoads'] ) ) {
83 foreach ( $server['groupLoads'] as $group => $ratio ) {
84 if ( !isset( $this->mGroupLoads
[$group] ) ) {
85 $this->mGroupLoads
[$group] = array();
87 $this->mGroupLoads
[$group][$i] = $ratio;
94 * Get a LoadMonitor instance
98 function getLoadMonitor() {
99 if ( !isset( $this->mLoadMonitor
) ) {
100 $class = $this->mLoadMonitorClass
;
101 $this->mLoadMonitor
= new $class( $this );
103 return $this->mLoadMonitor
;
107 * Get or set arbitrary data used by the parent object, usually an LBFactory
111 function parentInfo( $x = null ) {
112 return wfSetVar( $this->mParentInfo
, $x );
116 * Given an array of non-normalised probabilities, this function will select
117 * an element and return the appropriate key
119 * @param $weights array
123 function pickRandom( $weights ) {
124 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
128 $sum = array_sum( $weights );
130 # No loads on any of them
131 # In previous versions, this triggered an unweighted random selection,
132 # but this feature has been removed as of April 2006 to allow for strict
133 # separation of query groups.
136 $max = mt_getrandmax();
137 $rand = mt_rand( 0, $max ) / $max * $sum;
140 foreach ( $weights as $i => $w ) {
142 if ( $sum >= $rand ) {
150 * @param $loads array
152 * @return bool|int|string
154 function getRandomNonLagged( $loads, $wiki = false ) {
155 # Unset excessively lagged servers
156 $lags = $this->getLagTimes( $wiki );
157 foreach ( $lags as $i => $lag ) {
159 if ( $lag === false ) {
160 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
162 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
163 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
169 # Find out if all the slaves with non-zero load are lagged
171 foreach ( $loads as $load ) {
175 # No appropriate DB servers except maybe the master and some slaves with zero load
176 # Do NOT use the master
177 # Instead, this function will return false, triggering read-only mode,
178 # and a lagged slave will be used instead.
182 if ( count( $loads ) == 0 ) {
186 #wfDebugLog( 'connect', var_export( $loads, true ) );
188 # Return a random representative of the remainder
189 return $this->pickRandom( $loads );
193 * Get the index of the reader connection, which may be a slave
194 * This takes into account load ratios and lag times. It should
195 * always return a consistent index during a given invocation
197 * Side effect: opens connections to databases
200 * @return bool|int|string
202 function getReaderIndex( $group = false, $wiki = false ) {
203 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
205 # @todo FIXME: For now, only go through all this for mysql databases
206 if ($wgDBtype != 'mysql') {
207 return $this->getWriterIndex();
210 if ( count( $this->mServers
) == 1 ) {
211 # Skip the load balancing if there's only one server
213 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
214 # Shortcut if generic reader exists already
215 return $this->mReadIndex
;
218 wfProfileIn( __METHOD__
);
222 # convert from seconds to microseconds
223 $timeout = $wgDBClusterTimeout * 1e6
;
225 # Find the relevant load array
226 if ( $group !== false ) {
227 if ( isset( $this->mGroupLoads
[$group] ) ) {
228 $nonErrorLoads = $this->mGroupLoads
[$group];
230 # No loads for this group, return false and the caller can use some other group
231 wfDebug( __METHOD__
.": no loads for group $group\n" );
232 wfProfileOut( __METHOD__
);
236 $nonErrorLoads = $this->mLoads
;
239 if ( !$nonErrorLoads ) {
240 throw new MWException( "Empty server array given to LoadBalancer" );
243 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
244 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
246 $laggedSlaveMode = false;
248 # First try quickly looking through the available servers for a server that
251 $totalThreadsConnected = 0;
252 $overloadedServers = 0;
253 $currentLoads = $nonErrorLoads;
254 while ( count( $currentLoads ) ) {
255 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
256 $i = $this->pickRandom( $currentLoads );
258 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
259 if ( $i === false && count( $currentLoads ) != 0 ) {
260 # All slaves lagged. Switch to read-only mode
261 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
262 $wgReadOnly = 'The database has been automatically locked ' .
263 'while the slave database servers catch up to the master';
264 $i = $this->pickRandom( $currentLoads );
265 $laggedSlaveMode = true;
269 if ( $i === false ) {
270 # pickRandom() returned false
271 # This is permanent and means the configuration or the load monitor
272 # wants us to return false.
273 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
274 wfProfileOut( __METHOD__
);
278 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
279 $conn = $this->openConnection( $i, $wiki );
282 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
283 unset( $nonErrorLoads[$i] );
284 unset( $currentLoads[$i] );
288 // Perform post-connection backoff
289 $threshold = isset( $this->mServers
[$i]['max threads'] )
290 ?
$this->mServers
[$i]['max threads'] : false;
291 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
293 // Decrement reference counter, we are finished with this connection.
294 // It will be incremented for the caller later.
295 if ( $wiki !== false ) {
296 $this->reuseConnection( $conn );
300 # Post-connection overload, don't use this server for now
301 $totalThreadsConnected +
= $backoff;
302 $overloadedServers++
;
303 unset( $currentLoads[$i] );
310 # No server found yet
313 # If all servers were down, quit now
314 if ( !count( $nonErrorLoads ) ) {
315 wfDebugLog( 'connect', "All servers down\n" );
319 # Some servers must have been overloaded
320 if ( $overloadedServers == 0 ) {
321 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
323 # Back off for a while
324 # Scale the sleep time by the number of connected threads, to produce a
325 # roughly constant global poll rate
326 $avgThreads = $totalThreadsConnected / $overloadedServers;
327 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
328 } while ( $totalElapsed < $timeout );
330 if ( $totalElapsed >= $timeout ) {
331 wfDebugLog( 'connect', "All servers busy\n" );
332 $this->mErrorConnection
= false;
333 $this->mLastError
= 'All servers busy';
336 if ( $i !== false ) {
337 # Slave connection successful
338 # Wait for the session master pos for a short time
339 if ( $this->mWaitForPos
&& $i > 0 ) {
340 if ( !$this->doWait( $i ) ) {
341 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
344 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
345 $this->mReadIndex
= $i;
348 wfProfileOut( __METHOD__
);
353 * Wait for a specified number of microseconds, and return the period waited
357 function sleep( $t ) {
358 wfProfileIn( __METHOD__
);
359 wfDebug( __METHOD__
.": waiting $t us\n" );
361 wfProfileOut( __METHOD__
);
366 * Set the master wait position
367 * If a DB_SLAVE connection has been opened already, waits
368 * Otherwise sets a variable telling it to wait if such a connection is opened
371 public function waitFor( $pos ) {
372 wfProfileIn( __METHOD__
);
373 $this->mWaitForPos
= $pos;
374 $i = $this->mReadIndex
;
377 if ( !$this->doWait( $i ) ) {
378 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
379 $this->mLaggedSlaveMode
= true;
382 wfProfileOut( __METHOD__
);
386 * Set the master wait position and wait for ALL slaves to catch up to it
389 public function waitForAll( $pos ) {
390 wfProfileIn( __METHOD__
);
391 $this->mWaitForPos
= $pos;
392 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
393 $this->doWait( $i , true );
395 wfProfileOut( __METHOD__
);
399 * Get any open connection to a given server index, local or foreign
400 * Returns false if there is no connection open
403 * @return DatabaseBase|bool False on failure
405 function getAnyOpenConnection( $i ) {
406 foreach ( $this->mConns
as $conns ) {
407 if ( !empty( $conns[$i] ) ) {
408 return reset( $conns[$i] );
415 * Wait for a given slave to catch up to the master pos stored in $this
420 function doWait( $index, $open = false ) {
421 # Find a connection to wait on
422 $conn = $this->getAnyOpenConnection( $index );
425 wfDebug( __METHOD__
. ": no connection open\n" );
428 $conn = $this->openConnection( $index );
430 wfDebug( __METHOD__
. ": failed to open connection\n" );
436 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
437 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
439 if ( $result == -1 ||
is_null( $result ) ) {
440 # Timed out waiting for slave, use master instead
441 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
444 wfDebug( __METHOD__
.": Done\n" );
450 * Get a connection by index
451 * This is the main entry point for this class.
453 * @param $i Integer: server index
454 * @param $groups Array: query groups
455 * @param $wiki String: wiki ID
457 * @return DatabaseBase
459 public function &getConnection( $i, $groups = array(), $wiki = false ) {
460 wfProfileIn( __METHOD__
);
462 if ( $i == DB_LAST
) {
463 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
464 } elseif ( $i === null ||
$i === false ) {
465 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
468 if ( $wiki === wfWikiID() ) {
473 if ( $i == DB_MASTER
) {
474 $i = $this->getWriterIndex();
475 } elseif ( !is_array( $groups ) ) {
476 $groupIndex = $this->getReaderIndex( $groups, $wiki );
477 if ( $groupIndex !== false ) {
478 $serverName = $this->getServerName( $groupIndex );
479 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
483 foreach ( $groups as $group ) {
484 $groupIndex = $this->getReaderIndex( $group, $wiki );
485 if ( $groupIndex !== false ) {
486 $serverName = $this->getServerName( $groupIndex );
487 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
494 # Operation-based index
495 if ( $i == DB_SLAVE
) {
496 $i = $this->getReaderIndex( false, $wiki );
497 # Couldn't find a working server in getReaderIndex()?
498 if ( $i === false ) {
499 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
500 wfProfileOut( __METHOD__
);
501 $this->reportConnectionError( $this->mErrorConnection
);
506 # Now we have an explicit index into the servers array
507 $conn = $this->openConnection( $i, $wiki );
509 wfProfileOut( __METHOD__
);
510 $this->reportConnectionError( $this->mErrorConnection
);
513 wfProfileOut( __METHOD__
);
518 * Mark a foreign connection as being available for reuse under a different
519 * DB name or prefix. This mechanism is reference-counted, and must be called
520 * the same number of times as getConnection() to work.
522 * @param DatabaseBase $conn
524 public function reuseConnection( $conn ) {
525 $serverIndex = $conn->getLBInfo('serverIndex');
526 $refCount = $conn->getLBInfo('foreignPoolRefCount');
527 $dbName = $conn->getDBname();
528 $prefix = $conn->tablePrefix();
529 if ( strval( $prefix ) !== '' ) {
530 $wiki = "$dbName-$prefix";
534 if ( $serverIndex === null ||
$refCount === null ) {
535 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
537 * This can happen in code like:
538 * foreach ( $dbs as $db ) {
539 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
541 * $lb->reuseConnection( $conn );
543 * When a connection to the local DB is opened in this way, reuseConnection()
548 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
549 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
551 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
552 if ( $refCount <= 0 ) {
553 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
554 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
555 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
557 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
562 * Open a connection to the server given by the specified index
563 * Index must be an actual index into the array.
564 * If the server is already open, returns it.
566 * On error, returns false, and the connection which caused the
567 * error will be available via $this->mErrorConnection.
569 * @param $i Integer server index
570 * @param $wiki String wiki ID to open
571 * @return DatabaseBase
575 function openConnection( $i, $wiki = false ) {
576 wfProfileIn( __METHOD__
);
577 if ( $wiki !== false ) {
578 $conn = $this->openForeignConnection( $i, $wiki );
579 wfProfileOut( __METHOD__
);
582 if ( isset( $this->mConns
['local'][$i][0] ) ) {
583 $conn = $this->mConns
['local'][$i][0];
585 $server = $this->mServers
[$i];
586 $server['serverIndex'] = $i;
587 $conn = $this->reallyOpenConnection( $server, false );
588 if ( $conn->isOpen() ) {
589 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
590 $this->mConns
['local'][$i][0] = $conn;
592 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
593 $this->mErrorConnection
= $conn;
597 wfProfileOut( __METHOD__
);
602 * Open a connection to a foreign DB, or return one if it is already open.
604 * Increments a reference count on the returned connection which locks the
605 * connection to the requested wiki. This reference count can be
606 * decremented by calling reuseConnection().
608 * If a connection is open to the appropriate server already, but with the wrong
609 * database, it will be switched to the right database and returned, as long as
610 * it has been freed first with reuseConnection().
612 * On error, returns false, and the connection which caused the
613 * error will be available via $this->mErrorConnection.
615 * @param $i Integer: server index
616 * @param $wiki String: wiki ID to open
617 * @return DatabaseBase
619 function openForeignConnection( $i, $wiki ) {
620 wfProfileIn(__METHOD__
);
621 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
622 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
623 // Reuse an already-used connection
624 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
625 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
626 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
627 // Reuse a free connection for the same wiki
628 $conn = $this->mConns
['foreignFree'][$i][$wiki];
629 unset( $this->mConns
['foreignFree'][$i][$wiki] );
630 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
631 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
632 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
633 // Reuse a connection from another wiki
634 $conn = reset( $this->mConns
['foreignFree'][$i] );
635 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
637 if ( !$conn->selectDB( $dbName ) ) {
638 $this->mLastError
= "Error selecting database $dbName on server " .
639 $conn->getServer() . " from client host " . wfHostname() . "\n";
640 $this->mErrorConnection
= $conn;
643 $conn->tablePrefix( $prefix );
644 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
645 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
646 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
649 // Open a new connection
650 $server = $this->mServers
[$i];
651 $server['serverIndex'] = $i;
652 $server['foreignPoolRefCount'] = 0;
653 $conn = $this->reallyOpenConnection( $server, $dbName );
654 if ( !$conn->isOpen() ) {
655 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
656 $this->mErrorConnection
= $conn;
659 $conn->tablePrefix( $prefix );
660 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
661 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
665 // Increment reference count
667 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
668 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
670 wfProfileOut(__METHOD__
);
675 * Test if the specified index represents an open connection
677 * @param $index Integer: server index
681 function isOpen( $index ) {
682 if( !is_integer( $index ) ) {
685 return (bool)$this->getAnyOpenConnection( $index );
689 * Really opens a connection. Uncached.
690 * Returns a Database object whether or not the connection was successful.
694 * @param $dbNameOverride bool
695 * @return DatabaseBase
697 function reallyOpenConnection( $server, $dbNameOverride = false ) {
698 if( !is_array( $server ) ) {
699 throw new MWException( 'You must update your load-balancing configuration. ' .
700 'See DefaultSettings.php entry for $wgDBservers.' );
703 $host = $server['host'];
704 $dbname = $server['dbname'];
706 if ( $dbNameOverride !== false ) {
707 $server['dbname'] = $dbname = $dbNameOverride;
712 $db = DatabaseBase
::factory( $server['type'], $server );
713 } catch ( DBConnectionError
$e ) {
714 // FIXME: This is probably the ugliest thing I have ever done to
715 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
719 $db->setLBInfo( $server );
720 if ( isset( $server['fakeSlaveLag'] ) ) {
721 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
723 if ( isset( $server['fakeMaster'] ) ) {
724 $db->setFakeMaster( true );
731 * @throws DBConnectionError
733 function reportConnectionError( &$conn ) {
734 if ( !is_object( $conn ) ) {
735 // No last connection, probably due to all servers being too busy
736 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
737 $conn = new Database
;
738 // If all servers were busy, mLastError will contain something sensible
739 throw new DBConnectionError( $conn, $this->mLastError
);
741 $server = $conn->getProperty( 'mServer' );
742 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
743 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
750 function getWriterIndex() {
755 * Returns true if the specified index is a valid server index
760 function haveIndex( $i ) {
761 return array_key_exists( $i, $this->mServers
);
765 * Returns true if the specified index is valid and has non-zero load
770 function isNonZeroLoad( $i ) {
771 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
775 * Get the number of defined servers (not the number of open connections)
779 function getServerCount() {
780 return count( $this->mServers
);
784 * Get the host name or IP address of the server with the specified index
785 * Prefer a readable name if available.
789 function getServerName( $i ) {
790 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
791 return $this->mServers
[$i]['hostName'];
792 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
793 return $this->mServers
[$i]['host'];
800 * Return the server info structure for a given index, or false if the index is invalid.
804 function getServerInfo( $i ) {
805 if ( isset( $this->mServers
[$i] ) ) {
806 return $this->mServers
[$i];
813 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
817 function setServerInfo( $i, $serverInfo ) {
818 $this->mServers
[$i] = $serverInfo;
822 * Get the current master position for chronology control purposes
825 function getMasterPos() {
826 # If this entire request was served from a slave without opening a connection to the
827 # master (however unlikely that may be), then we can fetch the position from the slave.
828 $masterConn = $this->getAnyOpenConnection( 0 );
829 if ( !$masterConn ) {
830 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
831 $conn = $this->getAnyOpenConnection( $i );
833 wfDebug( "Master pos fetched from slave\n" );
834 return $conn->getSlavePos();
838 wfDebug( "Master pos fetched from master\n" );
839 return $masterConn->getMasterPos();
845 * Close all open connections
847 function closeAll() {
848 foreach ( $this->mConns
as $conns2 ) {
849 foreach ( $conns2 as $conns3 ) {
850 foreach ( $conns3 as $conn ) {
855 $this->mConns
= array(
857 'foreignFree' => array(),
858 'foreignUsed' => array(),
863 * Deprecated function, typo in function name
865 * @deprecated in 1.18
868 function closeConnecton( $conn ) {
869 wfDeprecated( __METHOD__
, '1.18' );
870 $this->closeConnection( $conn );
875 * Using this function makes sure the LoadBalancer knows the connection is closed.
876 * If you use $conn->close() directly, the load balancer won't update its state.
877 * @param $conn DatabaseBase
879 function closeConnection( $conn ) {
881 foreach ( $this->mConns
as $i1 => $conns2 ) {
882 foreach ( $conns2 as $i2 => $conns3 ) {
883 foreach ( $conns3 as $i3 => $candidateConn ) {
884 if ( $conn === $candidateConn ) {
886 unset( $this->mConns
[$i1][$i2][$i3] );
899 * Commit transactions on all open connections
901 function commitAll() {
902 foreach ( $this->mConns
as $conns2 ) {
903 foreach ( $conns2 as $conns3 ) {
904 foreach ( $conns3 as $conn ) {
905 $conn->commit( __METHOD__
);
912 * Issue COMMIT only on master, only if queries were done on connection
914 function commitMasterChanges() {
915 // Always 0, but who knows.. :)
916 $masterIndex = $this->getWriterIndex();
917 foreach ( $this->mConns
as $conns2 ) {
918 if ( empty( $conns2[$masterIndex] ) ) {
921 foreach ( $conns2[$masterIndex] as $conn ) {
922 if ( $conn->trxLevel() && $conn->doneWrites() ) {
923 $conn->commit( __METHOD__
);
933 function waitTimeout( $value = null ) {
934 return wfSetVar( $this->mWaitTimeout
, $value );
940 function getLaggedSlaveMode() {
941 return $this->mLaggedSlaveMode
;
945 * Disables/enables lag checks
949 function allowLagged( $mode = null ) {
950 if ( $mode === null) {
951 return $this->mAllowLagged
;
953 $this->mAllowLagged
= $mode;
961 foreach ( $this->mConns
as $conns2 ) {
962 foreach ( $conns2 as $conns3 ) {
963 foreach ( $conns3 as $conn ) {
964 if ( !$conn->ping() ) {
974 * Call a function with each open connection object
976 * @param array $params
978 function forEachOpenConnection( $callback, $params = array() ) {
979 foreach ( $this->mConns
as $conns2 ) {
980 foreach ( $conns2 as $conns3 ) {
981 foreach ( $conns3 as $conn ) {
982 $mergedParams = array_merge( array( $conn ), $params );
983 call_user_func_array( $callback, $mergedParams );
990 * Get the hostname and lag time of the most-lagged slave.
991 * This is useful for maintenance scripts that need to throttle their updates.
992 * May attempt to open connections to slaves on the default DB. If there is
993 * no lag, the maximum lag will be reported as -1.
995 * @param $wiki string Wiki ID, or false for the default database
997 * @return array ( host, max lag, index of max lagged host )
999 function getMaxLag( $wiki = false ) {
1003 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1004 foreach ( $this->mServers
as $i => $conn ) {
1006 if ( $wiki === false ) {
1007 $conn = $this->getAnyOpenConnection( $i );
1010 $conn = $this->openConnection( $i, $wiki );
1015 $lag = $conn->getLag();
1016 if ( $lag > $maxLag ) {
1018 $host = $this->mServers
[$i]['host'];
1023 return array( $host, $maxLag, $maxIndex );
1027 * Get lag time for each server
1028 * Results are cached for a short time in memcached, and indefinitely in the process cache
1034 function getLagTimes( $wiki = false ) {
1036 if ( isset( $this->mLagTimes
) ) {
1037 return $this->mLagTimes
;
1039 if ( $this->getServerCount() == 1 ) {
1041 $this->mLagTimes
= array( 0 => 0 );
1043 # Send the request to the load monitor
1044 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1045 array_keys( $this->mServers
), $wiki );
1047 return $this->mLagTimes
;
1051 * Get the lag in seconds for a given connection, or zero if this load
1052 * balancer does not have replication enabled.
1054 * This should be used in preference to Database::getLag() in cases where
1055 * replication may not be in use, since there is no way to determine if
1056 * replication is in use at the connection level without running
1057 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1058 * function instead of Database::getLag() avoids a fatal error in this
1059 * case on many installations.
1061 * @param $conn DatabaseBase
1065 function safeGetLag( $conn ) {
1066 if ( $this->getServerCount() == 1 ) {
1069 return $conn->getLag();
1074 * Clear the cache for getLagTimes
1076 function clearLagTimeCache() {
1077 $this->mLagTimes
= null;