Make updateCollation.php a bit less murderous for WMF databases:
[mediawiki.git] / includes / db / LoadBalancer.php
blob5f2af19443b6761c66f2c7cb62b86ff65128fd83
1 <?php
2 /**
3 * Database load balancing
5 * @file
6 * @ingroup Database
7 */
9 /**
10 * Database load balancing object
12 * @todo document
13 * @ingroup Database
15 class LoadBalancer {
16 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
17 /* private */ var $mErrorConnection;
18 /* private */ var $mReadIndex, $mAllowLagged;
19 /* private */ var $mWaitForPos, $mWaitTimeout;
20 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
21 /* private */ var $mParentInfo, $mLagTimes;
22 /* private */ var $mLoadMonitorClass, $mLoadMonitor;
24 /**
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 )
32 if ( !isset( $params['servers'] ) ) {
33 throw new MWException( __CLASS__.': missing servers parameter' );
35 $this->mServers = $params['servers'];
37 if ( isset( $params['waitTimeout'] ) ) {
38 $this->mWaitTimeout = $params['waitTimeout'];
39 } else {
40 $this->mWaitTimeout = 10;
43 $this->mReadIndex = -1;
44 $this->mWriteIndex = -1;
45 $this->mConns = array(
46 'local' => array(),
47 'foreignUsed' => array(),
48 'foreignFree' => array() );
49 $this->mLoads = array();
50 $this->mWaitForPos = false;
51 $this->mLaggedSlaveMode = false;
52 $this->mErrorConnection = false;
53 $this->mAllowLagged = false;
54 $this->mLoadMonitorClass = isset( $params['loadMonitor'] )
55 ? $params['loadMonitor'] : 'LoadMonitor_MySQL';
57 foreach( $params['servers'] as $i => $server ) {
58 $this->mLoads[$i] = $server['load'];
59 if ( isset( $server['groupLoads'] ) ) {
60 foreach ( $server['groupLoads'] as $group => $ratio ) {
61 if ( !isset( $this->mGroupLoads[$group] ) ) {
62 $this->mGroupLoads[$group] = array();
64 $this->mGroupLoads[$group][$i] = $ratio;
70 /**
71 * Get a LoadMonitor instance
73 function getLoadMonitor() {
74 if ( !isset( $this->mLoadMonitor ) ) {
75 $class = $this->mLoadMonitorClass;
76 $this->mLoadMonitor = new $class( $this );
78 return $this->mLoadMonitor;
81 /**
82 * Get or set arbitrary data used by the parent object, usually an LBFactory
84 function parentInfo( $x = null ) {
85 return wfSetVar( $this->mParentInfo, $x );
88 /**
89 * Given an array of non-normalised probabilities, this function will select
90 * an element and return the appropriate key
92 function pickRandom( $weights )
94 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
95 return false;
98 $sum = array_sum( $weights );
99 if ( $sum == 0 ) {
100 # No loads on any of them
101 # In previous versions, this triggered an unweighted random selection,
102 # but this feature has been removed as of April 2006 to allow for strict
103 # separation of query groups.
104 return false;
106 $max = mt_getrandmax();
107 $rand = mt_rand(0, $max) / $max * $sum;
109 $sum = 0;
110 foreach ( $weights as $i => $w ) {
111 $sum += $w;
112 if ( $sum >= $rand ) {
113 break;
116 return $i;
119 function getRandomNonLagged( $loads, $wiki = false ) {
120 # Unset excessively lagged servers
121 $lags = $this->getLagTimes( $wiki );
122 foreach ( $lags as $i => $lag ) {
123 if ( $i != 0 ) {
124 if ( $lag === false ) {
125 wfDebug( "Server #$i is not replicating\n" );
126 unset( $loads[$i] );
127 } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
128 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
129 unset( $loads[$i] );
134 # Find out if all the slaves with non-zero load are lagged
135 $sum = 0;
136 foreach ( $loads as $load ) {
137 $sum += $load;
139 if ( $sum == 0 ) {
140 # No appropriate DB servers except maybe the master and some slaves with zero load
141 # Do NOT use the master
142 # Instead, this function will return false, triggering read-only mode,
143 # and a lagged slave will be used instead.
144 return false;
147 if ( count( $loads ) == 0 ) {
148 return false;
151 #wfDebugLog( 'connect', var_export( $loads, true ) );
153 # Return a random representative of the remainder
154 return $this->pickRandom( $loads );
158 * Get the index of the reader connection, which may be a slave
159 * This takes into account load ratios and lag times. It should
160 * always return a consistent index during a given invocation
162 * Side effect: opens connections to databases
164 function getReaderIndex( $group = false, $wiki = false ) {
165 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
167 # FIXME: For now, only go through all this for mysql databases
168 if ($wgDBtype != 'mysql') {
169 return $this->getWriterIndex();
172 if ( count( $this->mServers ) == 1 ) {
173 # Skip the load balancing if there's only one server
174 return 0;
175 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
176 # Shortcut if generic reader exists already
177 return $this->mReadIndex;
180 wfProfileIn( __METHOD__ );
182 $totalElapsed = 0;
184 # convert from seconds to microseconds
185 $timeout = $wgDBClusterTimeout * 1e6;
187 # Find the relevant load array
188 if ( $group !== false ) {
189 if ( isset( $this->mGroupLoads[$group] ) ) {
190 $nonErrorLoads = $this->mGroupLoads[$group];
191 } else {
192 # No loads for this group, return false and the caller can use some other group
193 wfDebug( __METHOD__.": no loads for group $group\n" );
194 wfProfileOut( __METHOD__ );
195 return false;
197 } else {
198 $nonErrorLoads = $this->mLoads;
201 if ( !$nonErrorLoads ) {
202 throw new MWException( "Empty server array given to LoadBalancer" );
205 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
206 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
208 $laggedSlaveMode = false;
210 # First try quickly looking through the available servers for a server that
211 # meets our criteria
212 do {
213 $totalThreadsConnected = 0;
214 $overloadedServers = 0;
215 $currentLoads = $nonErrorLoads;
216 while ( count( $currentLoads ) ) {
217 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
218 $i = $this->pickRandom( $currentLoads );
219 } else {
220 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
221 if ( $i === false && count( $currentLoads ) != 0 ) {
222 # All slaves lagged. Switch to read-only mode
223 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
224 $i = $this->pickRandom( $currentLoads );
225 $laggedSlaveMode = true;
229 if ( $i === false ) {
230 # pickRandom() returned false
231 # This is permanent and means the configuration or the load monitor
232 # wants us to return false.
233 wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
234 wfProfileOut( __METHOD__ );
235 return false;
238 wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
239 $conn = $this->openConnection( $i, $wiki );
241 if ( !$conn ) {
242 wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
243 unset( $nonErrorLoads[$i] );
244 unset( $currentLoads[$i] );
245 continue;
248 // Perform post-connection backoff
249 $threshold = isset( $this->mServers[$i]['max threads'] )
250 ? $this->mServers[$i]['max threads'] : false;
251 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
253 // Decrement reference counter, we are finished with this connection.
254 // It will be incremented for the caller later.
255 if ( $wiki !== false ) {
256 $this->reuseConnection( $conn );
259 if ( $backoff ) {
260 # Post-connection overload, don't use this server for now
261 $totalThreadsConnected += $backoff;
262 $overloadedServers++;
263 unset( $currentLoads[$i] );
264 } else {
265 # Return this server
266 break 2;
270 # No server found yet
271 $i = false;
273 # If all servers were down, quit now
274 if ( !count( $nonErrorLoads ) ) {
275 wfDebugLog( 'connect', "All servers down\n" );
276 break;
279 # Some servers must have been overloaded
280 if ( $overloadedServers == 0 ) {
281 throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
283 # Back off for a while
284 # Scale the sleep time by the number of connected threads, to produce a
285 # roughly constant global poll rate
286 $avgThreads = $totalThreadsConnected / $overloadedServers;
287 $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
288 } while ( $totalElapsed < $timeout );
290 if ( $totalElapsed >= $timeout ) {
291 wfDebugLog( 'connect', "All servers busy\n" );
292 $this->mErrorConnection = false;
293 $this->mLastError = 'All servers busy';
296 if ( $i !== false ) {
297 # Slave connection successful
298 # Wait for the session master pos for a short time
299 if ( $this->mWaitForPos && $i > 0 ) {
300 if ( !$this->doWait( $i ) ) {
301 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
304 if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
305 $this->mReadIndex = $i;
308 wfProfileOut( __METHOD__ );
309 return $i;
313 * Wait for a specified number of microseconds, and return the period waited
315 function sleep( $t ) {
316 wfProfileIn( __METHOD__ );
317 wfDebug( __METHOD__.": waiting $t us\n" );
318 usleep( $t );
319 wfProfileOut( __METHOD__ );
320 return $t;
324 * Set the master wait position
325 * If a DB_SLAVE connection has been opened already, waits
326 * Otherwise sets a variable telling it to wait if such a connection is opened
328 public function waitFor( $pos ) {
329 wfProfileIn( __METHOD__ );
330 $this->mWaitForPos = $pos;
331 $i = $this->mReadIndex;
333 if ( $i > 0 ) {
334 if ( !$this->doWait( $i ) ) {
335 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
336 $this->mLaggedSlaveMode = true;
339 wfProfileOut( __METHOD__ );
343 * Set the master wait position and wait for ALL slaves to catch up to it
345 public function waitForAll( $pos ) {
346 wfProfileIn( __METHOD__ );
347 $this->mWaitForPos = $pos;
348 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
349 $this->doWait( $i );
351 wfProfileOut( __METHOD__ );
355 * Get any open connection to a given server index, local or foreign
356 * Returns false if there is no connection open
358 function getAnyOpenConnection( $i ) {
359 foreach ( $this->mConns as $conns ) {
360 if ( !empty( $conns[$i] ) ) {
361 return reset( $conns[$i] );
364 return false;
368 * Wait for a given slave to catch up to the master pos stored in $this
370 function doWait( $index ) {
371 # Find a connection to wait on
372 $conn = $this->getAnyOpenConnection( $index );
373 if ( !$conn ) {
374 wfDebug( __METHOD__ . ": no connection open\n" );
375 return false;
378 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
379 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
381 if ( $result == -1 || is_null( $result ) ) {
382 # Timed out waiting for slave, use master instead
383 wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
384 return false;
385 } else {
386 wfDebug( __METHOD__.": Done\n" );
387 return true;
392 * Get a connection by index
393 * This is the main entry point for this class.
395 * @param $i Integer: server index
396 * @param $groups Array: query groups
397 * @param $wiki String: wiki ID
399 * @return DatabaseBase
401 public function &getConnection( $i, $groups = array(), $wiki = false ) {
402 wfProfileIn( __METHOD__ );
404 if ( $i == DB_LAST ) {
405 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
406 } elseif ( $i === null || $i === false ) {
407 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
410 if ( $wiki === wfWikiID() ) {
411 $wiki = false;
414 # Query groups
415 if ( $i == DB_MASTER ) {
416 $i = $this->getWriterIndex();
417 } elseif ( !is_array( $groups ) ) {
418 $groupIndex = $this->getReaderIndex( $groups, $wiki );
419 if ( $groupIndex !== false ) {
420 $serverName = $this->getServerName( $groupIndex );
421 wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
422 $i = $groupIndex;
424 } else {
425 foreach ( $groups as $group ) {
426 $groupIndex = $this->getReaderIndex( $group, $wiki );
427 if ( $groupIndex !== false ) {
428 $serverName = $this->getServerName( $groupIndex );
429 wfDebug( __METHOD__.": using server $serverName for group $group\n" );
430 $i = $groupIndex;
431 break;
436 # Operation-based index
437 if ( $i == DB_SLAVE ) {
438 $i = $this->getReaderIndex( false, $wiki );
439 # Couldn't find a working server in getReaderIndex()?
440 if ( $i === false ) {
441 $this->mLastError = 'No working slave server: ' . $this->mLastError;
442 $this->reportConnectionError( $this->mErrorConnection );
443 wfProfileOut( __METHOD__ );
444 return false;
448 # Now we have an explicit index into the servers array
449 $conn = $this->openConnection( $i, $wiki );
450 if ( !$conn ) {
451 $this->reportConnectionError( $this->mErrorConnection );
454 wfProfileOut( __METHOD__ );
455 return $conn;
459 * Mark a foreign connection as being available for reuse under a different
460 * DB name or prefix. This mechanism is reference-counted, and must be called
461 * the same number of times as getConnection() to work.
463 public function reuseConnection( $conn ) {
464 $serverIndex = $conn->getLBInfo('serverIndex');
465 $refCount = $conn->getLBInfo('foreignPoolRefCount');
466 $dbName = $conn->getDBname();
467 $prefix = $conn->tablePrefix();
468 if ( strval( $prefix ) !== '' ) {
469 $wiki = "$dbName-$prefix";
470 } else {
471 $wiki = $dbName;
473 if ( $serverIndex === null || $refCount === null ) {
474 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
476 * This can happen in code like:
477 * foreach ( $dbs as $db ) {
478 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
479 * ...
480 * $lb->reuseConnection( $conn );
482 * When a connection to the local DB is opened in this way, reuseConnection()
483 * should be ignored
485 return;
487 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
488 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
490 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
491 if ( $refCount <= 0 ) {
492 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
493 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
494 wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
495 } else {
496 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
501 * Open a connection to the server given by the specified index
502 * Index must be an actual index into the array.
503 * If the server is already open, returns it.
505 * On error, returns false, and the connection which caused the
506 * error will be available via $this->mErrorConnection.
508 * @param $i Integer: server index
509 * @param $wiki String: wiki ID to open
510 * @return DatabaseBase
512 * @access private
514 function openConnection( $i, $wiki = false ) {
515 wfProfileIn( __METHOD__ );
516 if ( $wiki !== false ) {
517 $conn = $this->openForeignConnection( $i, $wiki );
518 wfProfileOut( __METHOD__);
519 return $conn;
521 if ( isset( $this->mConns['local'][$i][0] ) ) {
522 $conn = $this->mConns['local'][$i][0];
523 } else {
524 $server = $this->mServers[$i];
525 $server['serverIndex'] = $i;
526 $conn = $this->reallyOpenConnection( $server, false );
527 if ( $conn->isOpen() ) {
528 $this->mConns['local'][$i][0] = $conn;
529 } else {
530 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
531 $this->mErrorConnection = $conn;
532 $conn = false;
535 wfProfileOut( __METHOD__ );
536 return $conn;
540 * Open a connection to a foreign DB, or return one if it is already open.
542 * Increments a reference count on the returned connection which locks the
543 * connection to the requested wiki. This reference count can be
544 * decremented by calling reuseConnection().
546 * If a connection is open to the appropriate server already, but with the wrong
547 * database, it will be switched to the right database and returned, as long as
548 * it has been freed first with reuseConnection().
550 * On error, returns false, and the connection which caused the
551 * error will be available via $this->mErrorConnection.
553 * @param $i Integer: server index
554 * @param $wiki String: wiki ID to open
555 * @return DatabaseBase
557 function openForeignConnection( $i, $wiki ) {
558 wfProfileIn(__METHOD__);
559 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
560 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
561 // Reuse an already-used connection
562 $conn = $this->mConns['foreignUsed'][$i][$wiki];
563 wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
564 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
565 // Reuse a free connection for the same wiki
566 $conn = $this->mConns['foreignFree'][$i][$wiki];
567 unset( $this->mConns['foreignFree'][$i][$wiki] );
568 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
569 wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
570 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
571 // Reuse a connection from another wiki
572 $conn = reset( $this->mConns['foreignFree'][$i] );
573 $oldWiki = key( $this->mConns['foreignFree'][$i] );
575 if ( !$conn->selectDB( $dbName ) ) {
576 $this->mLastError = "Error selecting database $dbName on server " .
577 $conn->getServer() . " from client host " . wfHostname() . "\n";
578 $this->mErrorConnection = $conn;
579 $conn = false;
580 } else {
581 $conn->tablePrefix( $prefix );
582 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
583 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
584 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
586 } else {
587 // Open a new connection
588 $server = $this->mServers[$i];
589 $server['serverIndex'] = $i;
590 $server['foreignPoolRefCount'] = 0;
591 $conn = $this->reallyOpenConnection( $server, $dbName );
592 if ( !$conn->isOpen() ) {
593 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
594 $this->mErrorConnection = $conn;
595 $conn = false;
596 } else {
597 $conn->tablePrefix( $prefix );
598 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
599 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
603 // Increment reference count
604 if ( $conn ) {
605 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
606 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
608 wfProfileOut(__METHOD__);
609 return $conn;
613 * Test if the specified index represents an open connection
615 * @param $index Integer: server index
616 * @access private
618 function isOpen( $index ) {
619 if( !is_integer( $index ) ) {
620 return false;
622 return (bool)$this->getAnyOpenConnection( $index );
626 * Really opens a connection. Uncached.
627 * Returns a Database object whether or not the connection was successful.
628 * @access private
630 function reallyOpenConnection( $server, $dbNameOverride = false ) {
631 if( !is_array( $server ) ) {
632 throw new MWException( 'You must update your load-balancing configuration. ' .
633 'See DefaultSettings.php entry for $wgDBservers.' );
636 $host = $server['host'];
637 $dbname = $server['dbname'];
639 if ( $dbNameOverride !== false ) {
640 $server['dbname'] = $dbname = $dbNameOverride;
643 # Create object
644 wfDebug( "Connecting to $host $dbname...\n" );
645 $db = DatabaseBase::newFromType( $server['type'], $server );
646 if ( $db->isOpen() ) {
647 wfDebug( "Connected to $host $dbname.\n" );
648 } else {
649 wfDebug( "Connection failed to $host $dbname.\n" );
651 $db->setLBInfo( $server );
652 if ( isset( $server['fakeSlaveLag'] ) ) {
653 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
655 if ( isset( $server['fakeMaster'] ) ) {
656 $db->setFakeMaster( true );
658 return $db;
661 function reportConnectionError( &$conn ) {
662 wfProfileIn( __METHOD__ );
664 if ( !is_object( $conn ) ) {
665 // No last connection, probably due to all servers being too busy
666 wfLogDBError( "LB failure with no last connection\n" );
667 $conn = new Database;
668 // If all servers were busy, mLastError will contain something sensible
669 throw new DBConnectionError( $conn, $this->mLastError );
670 } else {
671 $server = $conn->getProperty( 'mServer' );
672 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
673 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
675 wfProfileOut( __METHOD__ );
678 function getWriterIndex() {
679 return 0;
683 * Returns true if the specified index is a valid server index
685 function haveIndex( $i ) {
686 return array_key_exists( $i, $this->mServers );
690 * Returns true if the specified index is valid and has non-zero load
692 function isNonZeroLoad( $i ) {
693 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
697 * Get the number of defined servers (not the number of open connections)
699 function getServerCount() {
700 return count( $this->mServers );
704 * Get the host name or IP address of the server with the specified index
705 * Prefer a readable name if available.
707 function getServerName( $i ) {
708 if ( isset( $this->mServers[$i]['hostName'] ) ) {
709 return $this->mServers[$i]['hostName'];
710 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
711 return $this->mServers[$i]['host'];
712 } else {
713 return '';
718 * Return the server info structure for a given index, or false if the index is invalid.
720 function getServerInfo( $i ) {
721 if ( isset( $this->mServers[$i] ) ) {
722 return $this->mServers[$i];
723 } else {
724 return false;
729 * Get the current master position for chronology control purposes
730 * @return mixed
732 function getMasterPos() {
733 # If this entire request was served from a slave without opening a connection to the
734 # master (however unlikely that may be), then we can fetch the position from the slave.
735 $masterConn = $this->getAnyOpenConnection( 0 );
736 if ( !$masterConn ) {
737 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
738 $conn = $this->getAnyOpenConnection( $i );
739 if ( $conn ) {
740 wfDebug( "Master pos fetched from slave\n" );
741 return $conn->getSlavePos();
744 } else {
745 wfDebug( "Master pos fetched from master\n" );
746 return $masterConn->getMasterPos();
748 return false;
752 * Close all open connections
754 function closeAll() {
755 foreach ( $this->mConns as $conns2 ) {
756 foreach ( $conns2 as $conns3 ) {
757 foreach ( $conns3 as $conn ) {
758 $conn->close();
762 $this->mConns = array(
763 'local' => array(),
764 'foreignFree' => array(),
765 'foreignUsed' => array(),
770 * Deprecated function, typo in function name
772 function closeConnecton( $conn ) {
773 $this->closeConnection( $conn );
777 * Close a connection
778 * Using this function makes sure the LoadBalancer knows the connection is closed.
779 * If you use $conn->close() directly, the load balancer won't update its state.
780 * @param $conn
781 * @return void
783 function closeConnection( $conn ) {
784 $done = false;
785 foreach ( $this->mConns as $i1 => $conns2 ) {
786 foreach ( $conns2 as $i2 => $conns3 ) {
787 foreach ( $conns3 as $i3 => $candidateConn ) {
788 if ( $conn === $candidateConn ) {
789 $conn->close();
790 unset( $this->mConns[$i1][$i2][$i3] );
791 $done = true;
792 break;
797 if ( !$done ) {
798 $conn->close();
803 * Commit transactions on all open connections
805 function commitAll() {
806 foreach ( $this->mConns as $conns2 ) {
807 foreach ( $conns2 as $conns3 ) {
808 foreach ( $conns3 as $conn ) {
809 $conn->commit();
815 /* Issue COMMIT only on master, only if queries were done on connection */
816 function commitMasterChanges() {
817 // Always 0, but who knows.. :)
818 $masterIndex = $this->getWriterIndex();
819 foreach ( $this->mConns as $conns2 ) {
820 if ( empty( $conns2[$masterIndex] ) ) {
821 continue;
823 foreach ( $conns2[$masterIndex] as $conn ) {
824 if ( $conn->doneWrites() ) {
825 $conn->commit();
831 function waitTimeout( $value = null ) {
832 return wfSetVar( $this->mWaitTimeout, $value );
835 function getLaggedSlaveMode() {
836 return $this->mLaggedSlaveMode;
839 /* Disables/enables lag checks */
840 function allowLagged($mode=null) {
841 if ($mode===null)
842 return $this->mAllowLagged;
843 $this->mAllowLagged=$mode;
846 function pingAll() {
847 $success = true;
848 foreach ( $this->mConns as $conns2 ) {
849 foreach ( $conns2 as $conns3 ) {
850 foreach ( $conns3 as $conn ) {
851 if ( !$conn->ping() ) {
852 $success = false;
857 return $success;
861 * Call a function with each open connection object
863 function forEachOpenConnection( $callback, $params = array() ) {
864 foreach ( $this->mConns as $conns2 ) {
865 foreach ( $conns2 as $conns3 ) {
866 foreach ( $conns3 as $conn ) {
867 $mergedParams = array_merge( array( $conn ), $params );
868 call_user_func_array( $callback, $mergedParams );
875 * Get the hostname and lag time of the most-lagged slave.
876 * This is useful for maintenance scripts that need to throttle their updates.
877 * May attempt to open connections to slaves on the default DB.
878 * @param $wiki string Wiki ID, or false for the default database
880 function getMaxLag( $wiki = false ) {
881 $maxLag = -1;
882 $host = '';
883 foreach ( $this->mServers as $i => $conn ) {
884 $conn = false;
885 if ( $wiki === false ) {
886 $conn = $this->getAnyOpenConnection( $i );
888 if ( !$conn ) {
889 $conn = $this->openConnection( $i, $wiki );
891 if ( !$conn ) {
892 continue;
894 $lag = $conn->getLag();
895 if ( $lag > $maxLag ) {
896 $maxLag = $lag;
897 $host = $this->mServers[$i]['host'];
900 return array( $host, $maxLag );
904 * Get lag time for each server
905 * Results are cached for a short time in memcached, and indefinitely in the process cache
907 function getLagTimes( $wiki = false ) {
908 # Try process cache
909 if ( isset( $this->mLagTimes ) ) {
910 return $this->mLagTimes;
912 # No, send the request to the load monitor
913 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
914 return $this->mLagTimes;
918 * Clear the cache for getLagTimes
920 function clearLagTimeCache() {
921 $this->mLagTimes = null;