3 * Database load balancing
10 * Database load balancing object
16 private $mServers, $mConns, $mLoads, $mGroupLoads;
17 private $mErrorConnection;
18 private $mReadIndex, $mAllowLagged;
19 private $mWaitForPos, $mWaitTimeout;
20 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
21 private $mParentInfo, $mLagTimes;
22 private $mLoadMonitorClass, $mLoadMonitor;
25 * @param $params Array with keys:
26 * servers Required. Array of server info structures.
27 * masterWaitTimeout Replication lag wait timeout
28 * loadMonitor Name of a class used to fetch server lag and load.
30 function __construct( $params ) {
31 if ( !isset( $params['servers'] ) ) {
32 throw new MWException( __CLASS__
.': missing servers parameter' );
34 $this->mServers
= $params['servers'];
36 if ( isset( $params['waitTimeout'] ) ) {
37 $this->mWaitTimeout
= $params['waitTimeout'];
39 $this->mWaitTimeout
= 10;
42 $this->mReadIndex
= -1;
43 $this->mWriteIndex
= -1;
44 $this->mConns
= array(
46 'foreignUsed' => array(),
47 'foreignFree' => array() );
48 $this->mLoads
= array();
49 $this->mWaitForPos
= false;
50 $this->mLaggedSlaveMode
= false;
51 $this->mErrorConnection
= false;
52 $this->mAllowLagged
= false;
54 if ( isset( $params['loadMonitor'] ) ) {
55 $this->mLoadMonitorClass
= $params['loadMonitor'];
57 $master = reset( $params['servers'] );
58 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
59 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
61 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
65 foreach( $params['servers'] as $i => $server ) {
66 $this->mLoads
[$i] = $server['load'];
67 if ( isset( $server['groupLoads'] ) ) {
68 foreach ( $server['groupLoads'] as $group => $ratio ) {
69 if ( !isset( $this->mGroupLoads
[$group] ) ) {
70 $this->mGroupLoads
[$group] = array();
72 $this->mGroupLoads
[$group][$i] = $ratio;
79 * Get a LoadMonitor instance
83 function getLoadMonitor() {
84 if ( !isset( $this->mLoadMonitor
) ) {
85 $class = $this->mLoadMonitorClass
;
86 $this->mLoadMonitor
= new $class( $this );
88 return $this->mLoadMonitor
;
92 * Get or set arbitrary data used by the parent object, usually an LBFactory
94 function parentInfo( $x = null ) {
95 return wfSetVar( $this->mParentInfo
, $x );
99 * Given an array of non-normalised probabilities, this function will select
100 * an element and return the appropriate key
106 function pickRandom( $weights ) {
107 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
111 $sum = array_sum( $weights );
113 # No loads on any of them
114 # In previous versions, this triggered an unweighted random selection,
115 # but this feature has been removed as of April 2006 to allow for strict
116 # separation of query groups.
119 $max = mt_getrandmax();
120 $rand = mt_rand( 0, $max ) / $max * $sum;
123 foreach ( $weights as $i => $w ) {
125 if ( $sum >= $rand ) {
135 * @return bool|int|string
137 function getRandomNonLagged( $loads, $wiki = false ) {
138 # Unset excessively lagged servers
139 $lags = $this->getLagTimes( $wiki );
140 foreach ( $lags as $i => $lag ) {
142 if ( $lag === false ) {
143 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
145 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
146 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
152 # Find out if all the slaves with non-zero load are lagged
154 foreach ( $loads as $load ) {
158 # No appropriate DB servers except maybe the master and some slaves with zero load
159 # Do NOT use the master
160 # Instead, this function will return false, triggering read-only mode,
161 # and a lagged slave will be used instead.
165 if ( count( $loads ) == 0 ) {
169 #wfDebugLog( 'connect', var_export( $loads, true ) );
171 # Return a random representative of the remainder
172 return $this->pickRandom( $loads );
176 * Get the index of the reader connection, which may be a slave
177 * This takes into account load ratios and lag times. It should
178 * always return a consistent index during a given invocation
180 * Side effect: opens connections to databases
183 * @return bool|int|string
185 function getReaderIndex( $group = false, $wiki = false ) {
186 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
188 # @todo FIXME: For now, only go through all this for mysql databases
189 if ($wgDBtype != 'mysql') {
190 return $this->getWriterIndex();
193 if ( count( $this->mServers
) == 1 ) {
194 # Skip the load balancing if there's only one server
196 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
197 # Shortcut if generic reader exists already
198 return $this->mReadIndex
;
201 wfProfileIn( __METHOD__
);
205 # convert from seconds to microseconds
206 $timeout = $wgDBClusterTimeout * 1e6
;
208 # Find the relevant load array
209 if ( $group !== false ) {
210 if ( isset( $this->mGroupLoads
[$group] ) ) {
211 $nonErrorLoads = $this->mGroupLoads
[$group];
213 # No loads for this group, return false and the caller can use some other group
214 wfDebug( __METHOD__
.": no loads for group $group\n" );
215 wfProfileOut( __METHOD__
);
219 $nonErrorLoads = $this->mLoads
;
222 if ( !$nonErrorLoads ) {
223 throw new MWException( "Empty server array given to LoadBalancer" );
226 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
227 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
229 $laggedSlaveMode = false;
231 # First try quickly looking through the available servers for a server that
234 $totalThreadsConnected = 0;
235 $overloadedServers = 0;
236 $currentLoads = $nonErrorLoads;
237 while ( count( $currentLoads ) ) {
238 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
239 $i = $this->pickRandom( $currentLoads );
241 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
242 if ( $i === false && count( $currentLoads ) != 0 ) {
243 # All slaves lagged. Switch to read-only mode
244 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
245 $wgReadOnly = 'The database has been automatically locked ' .
246 'while the slave database servers catch up to the master';
247 $i = $this->pickRandom( $currentLoads );
248 $laggedSlaveMode = true;
252 if ( $i === false ) {
253 # pickRandom() returned false
254 # This is permanent and means the configuration or the load monitor
255 # wants us to return false.
256 wfDebugLog( 'connect', __METHOD__
.": pickRandom() returned false\n" );
257 wfProfileOut( __METHOD__
);
261 wfDebugLog( 'connect', __METHOD__
.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
262 $conn = $this->openConnection( $i, $wiki );
265 wfDebugLog( 'connect', __METHOD__
.": Failed connecting to $i/$wiki\n" );
266 unset( $nonErrorLoads[$i] );
267 unset( $currentLoads[$i] );
271 // Perform post-connection backoff
272 $threshold = isset( $this->mServers
[$i]['max threads'] )
273 ?
$this->mServers
[$i]['max threads'] : false;
274 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
276 // Decrement reference counter, we are finished with this connection.
277 // It will be incremented for the caller later.
278 if ( $wiki !== false ) {
279 $this->reuseConnection( $conn );
283 # Post-connection overload, don't use this server for now
284 $totalThreadsConnected +
= $backoff;
285 $overloadedServers++
;
286 unset( $currentLoads[$i] );
293 # No server found yet
296 # If all servers were down, quit now
297 if ( !count( $nonErrorLoads ) ) {
298 wfDebugLog( 'connect', "All servers down\n" );
302 # Some servers must have been overloaded
303 if ( $overloadedServers == 0 ) {
304 throw new MWException( __METHOD__
.": unexpectedly found no overloaded servers" );
306 # Back off for a while
307 # Scale the sleep time by the number of connected threads, to produce a
308 # roughly constant global poll rate
309 $avgThreads = $totalThreadsConnected / $overloadedServers;
310 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
311 } while ( $totalElapsed < $timeout );
313 if ( $totalElapsed >= $timeout ) {
314 wfDebugLog( 'connect', "All servers busy\n" );
315 $this->mErrorConnection
= false;
316 $this->mLastError
= 'All servers busy';
319 if ( $i !== false ) {
320 # Slave connection successful
321 # Wait for the session master pos for a short time
322 if ( $this->mWaitForPos
&& $i > 0 ) {
323 if ( !$this->doWait( $i ) ) {
324 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
327 if ( $this->mReadIndex
<=0 && $this->mLoads
[$i]>0 && $i !== false ) {
328 $this->mReadIndex
= $i;
331 wfProfileOut( __METHOD__
);
336 * Wait for a specified number of microseconds, and return the period waited
338 function sleep( $t ) {
339 wfProfileIn( __METHOD__
);
340 wfDebug( __METHOD__
.": waiting $t us\n" );
342 wfProfileOut( __METHOD__
);
347 * Set the master wait position
348 * If a DB_SLAVE connection has been opened already, waits
349 * Otherwise sets a variable telling it to wait if such a connection is opened
351 public function waitFor( $pos ) {
352 wfProfileIn( __METHOD__
);
353 $this->mWaitForPos
= $pos;
354 $i = $this->mReadIndex
;
357 if ( !$this->doWait( $i ) ) {
358 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
359 $this->mLaggedSlaveMode
= true;
362 wfProfileOut( __METHOD__
);
366 * Set the master wait position and wait for ALL slaves to catch up to it
368 public function waitForAll( $pos ) {
369 wfProfileIn( __METHOD__
);
370 $this->mWaitForPos
= $pos;
371 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
372 $this->doWait( $i , true );
374 wfProfileOut( __METHOD__
);
378 * Get any open connection to a given server index, local or foreign
379 * Returns false if there is no connection open
381 * @return DatabaseBase
383 function getAnyOpenConnection( $i ) {
384 foreach ( $this->mConns
as $conns ) {
385 if ( !empty( $conns[$i] ) ) {
386 return reset( $conns[$i] );
393 * Wait for a given slave to catch up to the master pos stored in $this
395 function doWait( $index, $open = false ) {
396 # Find a connection to wait on
397 $conn = $this->getAnyOpenConnection( $index );
400 wfDebug( __METHOD__
. ": no connection open\n" );
403 $conn = $this->openConnection( $index );
405 wfDebug( __METHOD__
. ": failed to open connection\n" );
411 wfDebug( __METHOD__
.": Waiting for slave #$index to catch up...\n" );
412 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
414 if ( $result == -1 ||
is_null( $result ) ) {
415 # Timed out waiting for slave, use master instead
416 wfDebug( __METHOD__
.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
419 wfDebug( __METHOD__
.": Done\n" );
425 * Get a connection by index
426 * This is the main entry point for this class.
428 * @param $i Integer: server index
429 * @param $groups Array: query groups
430 * @param $wiki String: wiki ID
432 * @return DatabaseBase
434 public function &getConnection( $i, $groups = array(), $wiki = false ) {
435 wfProfileIn( __METHOD__
);
437 if ( $i == DB_LAST
) {
438 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
439 } elseif ( $i === null ||
$i === false ) {
440 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
443 if ( $wiki === wfWikiID() ) {
448 if ( $i == DB_MASTER
) {
449 $i = $this->getWriterIndex();
450 } elseif ( !is_array( $groups ) ) {
451 $groupIndex = $this->getReaderIndex( $groups, $wiki );
452 if ( $groupIndex !== false ) {
453 $serverName = $this->getServerName( $groupIndex );
454 wfDebug( __METHOD__
.": using server $serverName for group $groups\n" );
458 foreach ( $groups as $group ) {
459 $groupIndex = $this->getReaderIndex( $group, $wiki );
460 if ( $groupIndex !== false ) {
461 $serverName = $this->getServerName( $groupIndex );
462 wfDebug( __METHOD__
.": using server $serverName for group $group\n" );
469 # Operation-based index
470 if ( $i == DB_SLAVE
) {
471 $i = $this->getReaderIndex( false, $wiki );
472 # Couldn't find a working server in getReaderIndex()?
473 if ( $i === false ) {
474 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
475 $this->reportConnectionError( $this->mErrorConnection
);
476 wfProfileOut( __METHOD__
);
481 # Now we have an explicit index into the servers array
482 $conn = $this->openConnection( $i, $wiki );
484 $this->reportConnectionError( $this->mErrorConnection
);
487 wfProfileOut( __METHOD__
);
492 * Mark a foreign connection as being available for reuse under a different
493 * DB name or prefix. This mechanism is reference-counted, and must be called
494 * the same number of times as getConnection() to work.
496 * @param DatabaseBase $conn
498 public function reuseConnection( $conn ) {
499 $serverIndex = $conn->getLBInfo('serverIndex');
500 $refCount = $conn->getLBInfo('foreignPoolRefCount');
501 $dbName = $conn->getDBname();
502 $prefix = $conn->tablePrefix();
503 if ( strval( $prefix ) !== '' ) {
504 $wiki = "$dbName-$prefix";
508 if ( $serverIndex === null ||
$refCount === null ) {
509 wfDebug( __METHOD__
.": this connection was not opened as a foreign connection\n" );
511 * This can happen in code like:
512 * foreach ( $dbs as $db ) {
513 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
515 * $lb->reuseConnection( $conn );
517 * When a connection to the local DB is opened in this way, reuseConnection()
522 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
523 throw new MWException( __METHOD__
.": connection not found, has the connection been freed already?" );
525 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
526 if ( $refCount <= 0 ) {
527 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
528 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
529 wfDebug( __METHOD__
.": freed connection $serverIndex/$wiki\n" );
531 wfDebug( __METHOD__
.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
536 * Open a connection to the server given by the specified index
537 * Index must be an actual index into the array.
538 * If the server is already open, returns it.
540 * On error, returns false, and the connection which caused the
541 * error will be available via $this->mErrorConnection.
543 * @param $i Integer server index
544 * @param $wiki String wiki ID to open
545 * @return DatabaseBase
549 function openConnection( $i, $wiki = false ) {
550 wfProfileIn( __METHOD__
);
551 if ( $wiki !== false ) {
552 $conn = $this->openForeignConnection( $i, $wiki );
553 wfProfileOut( __METHOD__
);
556 if ( isset( $this->mConns
['local'][$i][0] ) ) {
557 $conn = $this->mConns
['local'][$i][0];
559 $server = $this->mServers
[$i];
560 $server['serverIndex'] = $i;
561 $conn = $this->reallyOpenConnection( $server, false );
562 if ( $conn->isOpen() ) {
563 $this->mConns
['local'][$i][0] = $conn;
565 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
566 $this->mErrorConnection
= $conn;
570 wfProfileOut( __METHOD__
);
575 * Open a connection to a foreign DB, or return one if it is already open.
577 * Increments a reference count on the returned connection which locks the
578 * connection to the requested wiki. This reference count can be
579 * decremented by calling reuseConnection().
581 * If a connection is open to the appropriate server already, but with the wrong
582 * database, it will be switched to the right database and returned, as long as
583 * it has been freed first with reuseConnection().
585 * On error, returns false, and the connection which caused the
586 * error will be available via $this->mErrorConnection.
588 * @param $i Integer: server index
589 * @param $wiki String: wiki ID to open
590 * @return DatabaseBase
592 function openForeignConnection( $i, $wiki ) {
593 wfProfileIn(__METHOD__
);
594 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
595 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
596 // Reuse an already-used connection
597 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
598 wfDebug( __METHOD__
.": reusing connection $i/$wiki\n" );
599 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
600 // Reuse a free connection for the same wiki
601 $conn = $this->mConns
['foreignFree'][$i][$wiki];
602 unset( $this->mConns
['foreignFree'][$i][$wiki] );
603 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
604 wfDebug( __METHOD__
.": reusing free connection $i/$wiki\n" );
605 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
606 // Reuse a connection from another wiki
607 $conn = reset( $this->mConns
['foreignFree'][$i] );
608 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
610 if ( !$conn->selectDB( $dbName ) ) {
611 $this->mLastError
= "Error selecting database $dbName on server " .
612 $conn->getServer() . " from client host " . wfHostname() . "\n";
613 $this->mErrorConnection
= $conn;
616 $conn->tablePrefix( $prefix );
617 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
618 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
619 wfDebug( __METHOD__
.": reusing free connection from $oldWiki for $wiki\n" );
622 // Open a new connection
623 $server = $this->mServers
[$i];
624 $server['serverIndex'] = $i;
625 $server['foreignPoolRefCount'] = 0;
626 $conn = $this->reallyOpenConnection( $server, $dbName );
627 if ( !$conn->isOpen() ) {
628 wfDebug( __METHOD__
.": error opening connection for $i/$wiki\n" );
629 $this->mErrorConnection
= $conn;
632 $conn->tablePrefix( $prefix );
633 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
634 wfDebug( __METHOD__
.": opened new connection for $i/$wiki\n" );
638 // Increment reference count
640 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
641 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
643 wfProfileOut(__METHOD__
);
648 * Test if the specified index represents an open connection
650 * @param $index Integer: server index
654 function isOpen( $index ) {
655 if( !is_integer( $index ) ) {
658 return (bool)$this->getAnyOpenConnection( $index );
662 * Really opens a connection. Uncached.
663 * Returns a Database object whether or not the connection was successful.
666 * @return DatabaseBase
668 function reallyOpenConnection( $server, $dbNameOverride = false ) {
669 if( !is_array( $server ) ) {
670 throw new MWException( 'You must update your load-balancing configuration. ' .
671 'See DefaultSettings.php entry for $wgDBservers.' );
674 $host = $server['host'];
675 $dbname = $server['dbname'];
677 if ( $dbNameOverride !== false ) {
678 $server['dbname'] = $dbname = $dbNameOverride;
682 wfDebug( "Connecting to $host $dbname...\n" );
684 $db = DatabaseBase
::factory( $server['type'], $server );
685 } catch ( DBConnectionError
$e ) {
686 // FIXME: This is probably the ugliest thing I have ever done to
687 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
691 if ( $db->isOpen() ) {
692 wfDebug( "Connected to $host $dbname.\n" );
694 wfDebug( "Connection failed to $host $dbname.\n" );
696 $db->setLBInfo( $server );
697 if ( isset( $server['fakeSlaveLag'] ) ) {
698 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
700 if ( isset( $server['fakeMaster'] ) ) {
701 $db->setFakeMaster( true );
706 function reportConnectionError( &$conn ) {
707 wfProfileIn( __METHOD__
);
709 if ( !is_object( $conn ) ) {
710 // No last connection, probably due to all servers being too busy
711 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
712 $conn = new Database
;
713 // If all servers were busy, mLastError will contain something sensible
714 throw new DBConnectionError( $conn, $this->mLastError
);
716 $server = $conn->getProperty( 'mServer' );
717 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
718 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
720 wfProfileOut( __METHOD__
);
723 function getWriterIndex() {
728 * Returns true if the specified index is a valid server index
732 function haveIndex( $i ) {
733 return array_key_exists( $i, $this->mServers
);
737 * Returns true if the specified index is valid and has non-zero load
741 function isNonZeroLoad( $i ) {
742 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
746 * Get the number of defined servers (not the number of open connections)
750 function getServerCount() {
751 return count( $this->mServers
);
755 * Get the host name or IP address of the server with the specified index
756 * Prefer a readable name if available.
758 function getServerName( $i ) {
759 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
760 return $this->mServers
[$i]['hostName'];
761 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
762 return $this->mServers
[$i]['host'];
769 * Return the server info structure for a given index, or false if the index is invalid.
771 function getServerInfo( $i ) {
772 if ( isset( $this->mServers
[$i] ) ) {
773 return $this->mServers
[$i];
780 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
782 function setServerInfo( $i, $serverInfo ) {
783 $this->mServers
[$i] = $serverInfo;
787 * Get the current master position for chronology control purposes
790 function getMasterPos() {
791 # If this entire request was served from a slave without opening a connection to the
792 # master (however unlikely that may be), then we can fetch the position from the slave.
793 $masterConn = $this->getAnyOpenConnection( 0 );
794 if ( !$masterConn ) {
795 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
796 $conn = $this->getAnyOpenConnection( $i );
798 wfDebug( "Master pos fetched from slave\n" );
799 return $conn->getSlavePos();
803 wfDebug( "Master pos fetched from master\n" );
804 return $masterConn->getMasterPos();
810 * Close all open connections
812 function closeAll() {
813 foreach ( $this->mConns
as $conns2 ) {
814 foreach ( $conns2 as $conns3 ) {
815 foreach ( $conns3 as $conn ) {
820 $this->mConns
= array(
822 'foreignFree' => array(),
823 'foreignUsed' => array(),
828 * Deprecated function, typo in function name
830 * @deprecated in 1.18
832 function closeConnecton( $conn ) {
833 $this->closeConnection( $conn );
838 * Using this function makes sure the LoadBalancer knows the connection is closed.
839 * If you use $conn->close() directly, the load balancer won't update its state.
843 function closeConnection( $conn ) {
845 foreach ( $this->mConns
as $i1 => $conns2 ) {
846 foreach ( $conns2 as $i2 => $conns3 ) {
847 foreach ( $conns3 as $i3 => $candidateConn ) {
848 if ( $conn === $candidateConn ) {
850 unset( $this->mConns
[$i1][$i2][$i3] );
863 * Commit transactions on all open connections
865 function commitAll() {
866 foreach ( $this->mConns
as $conns2 ) {
867 foreach ( $conns2 as $conns3 ) {
868 foreach ( $conns3 as $conn ) {
876 * Issue COMMIT only on master, only if queries were done on connection
878 function commitMasterChanges() {
879 // Always 0, but who knows.. :)
880 $masterIndex = $this->getWriterIndex();
881 foreach ( $this->mConns
as $conns2 ) {
882 if ( empty( $conns2[$masterIndex] ) ) {
885 foreach ( $conns2[$masterIndex] as $conn ) {
886 if ( $conn->doneWrites() ) {
893 function waitTimeout( $value = null ) {
894 return wfSetVar( $this->mWaitTimeout
, $value );
897 function getLaggedSlaveMode() {
898 return $this->mLaggedSlaveMode
;
901 /* Disables/enables lag checks */
902 function allowLagged( $mode = null ) {
903 if ( $mode === null) {
904 return $this->mAllowLagged
;
906 $this->mAllowLagged
= $mode;
911 foreach ( $this->mConns
as $conns2 ) {
912 foreach ( $conns2 as $conns3 ) {
913 foreach ( $conns3 as $conn ) {
914 if ( !$conn->ping() ) {
924 * Call a function with each open connection object
926 function forEachOpenConnection( $callback, $params = array() ) {
927 foreach ( $this->mConns
as $conns2 ) {
928 foreach ( $conns2 as $conns3 ) {
929 foreach ( $conns3 as $conn ) {
930 $mergedParams = array_merge( array( $conn ), $params );
931 call_user_func_array( $callback, $mergedParams );
938 * Get the hostname and lag time of the most-lagged slave.
939 * This is useful for maintenance scripts that need to throttle their updates.
940 * May attempt to open connections to slaves on the default DB. If there is
941 * no lag, the maximum lag will be reported as -1.
943 * @param $wiki string Wiki ID, or false for the default database
945 * @return array ( host, max lag, index of max lagged host )
947 function getMaxLag( $wiki = false ) {
951 if ( $this->getServerCount() > 1 ) { // no replication = no lag
952 foreach ( $this->mServers
as $i => $conn ) {
954 if ( $wiki === false ) {
955 $conn = $this->getAnyOpenConnection( $i );
958 $conn = $this->openConnection( $i, $wiki );
963 $lag = $conn->getLag();
964 if ( $lag > $maxLag ) {
966 $host = $this->mServers
[$i]['host'];
971 return array( $host, $maxLag, $maxIndex );
975 * Get lag time for each server
976 * Results are cached for a short time in memcached, and indefinitely in the process cache
982 function getLagTimes( $wiki = false ) {
984 if ( isset( $this->mLagTimes
) ) {
985 return $this->mLagTimes
;
987 if ( $this->getServerCount() == 1 ) {
989 $this->mLagTimes
= array( 0 => 0 );
991 # Send the request to the load monitor
992 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
993 array_keys( $this->mServers
), $wiki );
995 return $this->mLagTimes
;
999 * Get the lag in seconds for a given connection, or zero if this load
1000 * balancer does not have replication enabled.
1002 * This should be used in preference to Database::getLag() in cases where
1003 * replication may not be in use, since there is no way to determine if
1004 * replication is in use at the connection level without running
1005 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1006 * function instead of Database::getLag() avoids a fatal error in this
1007 * case on many installations.
1009 function safeGetLag( $conn ) {
1010 if ( $this->getServerCount() == 1 ) {
1013 return $conn->getLag();
1018 * Clear the cache for getLagTimes
1020 function clearLagTimeCache() {
1021 $this->mLagTimes
= null;