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 array $params 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.
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__
. ': missing servers parameter' );
50 $this->mServers
= $params['servers'];
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout
= $params['waitTimeout'];
55 $this->mWaitTimeout
= 10;
58 $this->mReadIndex
= -1;
59 $this->mWriteIndex
= -1;
60 $this->mConns
= array(
62 'foreignUsed' => array(),
63 'foreignFree' => array() );
64 $this->mLoads
= array();
65 $this->mWaitForPos
= false;
66 $this->mLaggedSlaveMode
= false;
67 $this->mErrorConnection
= false;
68 $this->mAllowLagged
= false;
70 if ( isset( $params['loadMonitor'] ) ) {
71 $this->mLoadMonitorClass
= $params['loadMonitor'];
73 $master = reset( $params['servers'] );
74 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
75 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
77 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
81 foreach ( $params['servers'] as $i => $server ) {
82 $this->mLoads
[$i] = $server['load'];
83 if ( isset( $server['groupLoads'] ) ) {
84 foreach ( $server['groupLoads'] as $group => $ratio ) {
85 if ( !isset( $this->mGroupLoads
[$group] ) ) {
86 $this->mGroupLoads
[$group] = array();
88 $this->mGroupLoads
[$group][$i] = $ratio;
95 * Get a LoadMonitor instance
99 function getLoadMonitor() {
100 if ( !isset( $this->mLoadMonitor
) ) {
101 $class = $this->mLoadMonitorClass
;
102 $this->mLoadMonitor
= new $class( $this );
104 return $this->mLoadMonitor
;
108 * Get or set arbitrary data used by the parent object, usually an LBFactory
112 function parentInfo( $x = null ) {
113 return wfSetVar( $this->mParentInfo
, $x );
117 * Given an array of non-normalised probabilities, this function will select
118 * an element and return the appropriate key
120 * @deprecated since 1.21, use ArrayUtils::pickRandom()
122 * @param $weights array
124 * @return bool|int|string
126 function pickRandom( $weights ) {
127 return ArrayUtils
::pickRandom( $weights );
131 * @param $loads array
133 * @return bool|int|string
135 function getRandomNonLagged( $loads, $wiki = false ) {
136 # Unset excessively lagged servers
137 $lags = $this->getLagTimes( $wiki );
138 foreach ( $lags as $i => $lag ) {
140 if ( $lag === false ) {
141 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
143 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
144 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
150 # Find out if all the slaves with non-zero load are lagged
152 foreach ( $loads as $load ) {
156 # No appropriate DB servers except maybe the master and some slaves with zero load
157 # Do NOT use the master
158 # Instead, this function will return false, triggering read-only mode,
159 # and a lagged slave will be used instead.
163 if ( count( $loads ) == 0 ) {
167 #wfDebugLog( 'connect', var_export( $loads, true ) );
169 # Return a random representative of the remainder
170 return ArrayUtils
::pickRandom( $loads );
174 * Get the index of the reader connection, which may be a slave
175 * This takes into account load ratios and lag times. It should
176 * always return a consistent index during a given invocation
178 * Side effect: opens connections to databases
181 * @throws MWException
182 * @return bool|int|string
184 function getReaderIndex( $group = false, $wiki = false ) {
185 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
187 # @todo FIXME: For now, only go through all this for mysql databases
188 if ( $wgDBtype != 'mysql' ) {
189 return $this->getWriterIndex();
192 if ( count( $this->mServers
) == 1 ) {
193 # Skip the load balancing if there's only one server
195 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
196 # Shortcut if generic reader exists already
197 return $this->mReadIndex
;
200 wfProfileIn( __METHOD__
);
204 # convert from seconds to microseconds
205 $timeout = $wgDBClusterTimeout * 1e6
;
207 # Find the relevant load array
208 if ( $group !== false ) {
209 if ( isset( $this->mGroupLoads
[$group] ) ) {
210 $nonErrorLoads = $this->mGroupLoads
[$group];
212 # No loads for this group, return false and the caller can use some other group
213 wfDebug( __METHOD__
. ": no loads for group $group\n" );
214 wfProfileOut( __METHOD__
);
218 $nonErrorLoads = $this->mLoads
;
221 if ( !$nonErrorLoads ) {
222 wfProfileOut( __METHOD__
);
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 = ArrayUtils
::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 = ArrayUtils
::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
340 function sleep( $t ) {
341 wfProfileIn( __METHOD__
);
342 wfDebug( __METHOD__
. ": waiting $t us\n" );
344 wfProfileOut( __METHOD__
);
349 * Set the master wait position
350 * If a DB_SLAVE connection has been opened already, waits
351 * Otherwise sets a variable telling it to wait if such a connection is opened
352 * @param $pos DBMasterPos
354 public function waitFor( $pos ) {
355 wfProfileIn( __METHOD__
);
356 $this->mWaitForPos
= $pos;
357 $i = $this->mReadIndex
;
360 if ( !$this->doWait( $i ) ) {
361 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
362 $this->mLaggedSlaveMode
= true;
365 wfProfileOut( __METHOD__
);
369 * Set the master wait position and wait for ALL slaves to catch up to it
370 * @param $pos DBMasterPos
372 public function waitForAll( $pos ) {
373 wfProfileIn( __METHOD__
);
374 $this->mWaitForPos
= $pos;
375 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
376 if ( $this->mLoads
[$i] > 0 ) {
377 $this->doWait( $i, true );
380 wfProfileOut( __METHOD__
);
384 * Get any open connection to a given server index, local or foreign
385 * Returns false if there is no connection open
388 * @return DatabaseBase|bool False on failure
390 function getAnyOpenConnection( $i ) {
391 foreach ( $this->mConns
as $conns ) {
392 if ( !empty( $conns[$i] ) ) {
393 return reset( $conns[$i] );
400 * Wait for a given slave to catch up to the master pos stored in $this
405 protected function doWait( $index, $open = false ) {
406 # Find a connection to wait on
407 $conn = $this->getAnyOpenConnection( $index );
410 wfDebug( __METHOD__
. ": no connection open\n" );
413 $conn = $this->openConnection( $index, '' );
415 wfDebug( __METHOD__
. ": failed to open connection\n" );
421 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
422 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
424 if ( $result == -1 ||
is_null( $result ) ) {
425 # Timed out waiting for slave, use master instead
426 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
429 wfDebug( __METHOD__
. ": Done\n" );
435 * Get a connection by index
436 * This is the main entry point for this class.
438 * @param $i Integer: server index
439 * @param array $groups query groups
440 * @param bool|string $wiki Wiki ID
442 * @throws MWException
443 * @return DatabaseBase
445 public function &getConnection( $i, $groups = array(), $wiki = false ) {
446 wfProfileIn( __METHOD__
);
448 if ( $i == DB_LAST
) {
449 wfProfileOut( __METHOD__
);
450 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
451 } elseif ( $i === null ||
$i === false ) {
452 wfProfileOut( __METHOD__
);
453 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
456 if ( $wiki === wfWikiID() ) {
461 if ( $i == DB_MASTER
) {
462 $i = $this->getWriterIndex();
463 } elseif ( !is_array( $groups ) ) {
464 $groupIndex = $this->getReaderIndex( $groups, $wiki );
465 if ( $groupIndex !== false ) {
466 $serverName = $this->getServerName( $groupIndex );
467 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
471 foreach ( $groups as $group ) {
472 $groupIndex = $this->getReaderIndex( $group, $wiki );
473 if ( $groupIndex !== false ) {
474 $serverName = $this->getServerName( $groupIndex );
475 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
482 # Operation-based index
483 if ( $i == DB_SLAVE
) {
484 $this->mLastError
= 'Unknown error'; // reset error string
485 $i = $this->getReaderIndex( false, $wiki );
486 # Couldn't find a working server in getReaderIndex()?
487 if ( $i === false ) {
488 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
489 wfProfileOut( __METHOD__
);
490 return $this->reportConnectionError();
494 # Now we have an explicit index into the servers array
495 $conn = $this->openConnection( $i, $wiki );
497 wfProfileOut( __METHOD__
);
498 return $this->reportConnectionError();
501 wfProfileOut( __METHOD__
);
506 * Mark a foreign connection as being available for reuse under a different
507 * DB name or prefix. This mechanism is reference-counted, and must be called
508 * the same number of times as getConnection() to work.
510 * @param DatabaseBase $conn
511 * @throws MWException
513 public function reuseConnection( $conn ) {
514 $serverIndex = $conn->getLBInfo( 'serverIndex' );
515 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
516 $dbName = $conn->getDBname();
517 $prefix = $conn->tablePrefix();
518 if ( strval( $prefix ) !== '' ) {
519 $wiki = "$dbName-$prefix";
523 if ( $serverIndex === null ||
$refCount === null ) {
524 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
526 * This can happen in code like:
527 * foreach ( $dbs as $db ) {
528 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
530 * $lb->reuseConnection( $conn );
532 * When a connection to the local DB is opened in this way, reuseConnection()
537 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
538 throw new MWException( __METHOD__
. ": connection not found, has the connection been freed already?" );
540 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
541 if ( $refCount <= 0 ) {
542 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
543 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
544 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
546 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
551 * Get a database connection handle reference
553 * The handle's methods wrap simply wrap those of a DatabaseBase handle
555 * @see LoadBalancer::getConnection() for parameter information
558 * @param mixed $groups
559 * @param string $wiki
562 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
563 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
567 * Get a database connection handle reference without connecting yet
569 * The handle's methods wrap simply wrap those of a DatabaseBase handle
571 * @see LoadBalancer::getConnection() for parameter information
574 * @param mixed $groups
575 * @param string $wiki
578 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
579 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
583 * Open a connection to the server given by the specified index
584 * Index must be an actual index into the array.
585 * If the server is already open, returns it.
587 * On error, returns false, and the connection which caused the
588 * error will be available via $this->mErrorConnection.
590 * @param $i Integer server index
591 * @param string $wiki wiki ID to open
592 * @return DatabaseBase
596 function openConnection( $i, $wiki = false ) {
597 wfProfileIn( __METHOD__
);
598 if ( $wiki !== false ) {
599 $conn = $this->openForeignConnection( $i, $wiki );
600 wfProfileOut( __METHOD__
);
603 if ( isset( $this->mConns
['local'][$i][0] ) ) {
604 $conn = $this->mConns
['local'][$i][0];
606 $server = $this->mServers
[$i];
607 $server['serverIndex'] = $i;
608 $conn = $this->reallyOpenConnection( $server, false );
609 if ( $conn->isOpen() ) {
610 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
611 $this->mConns
['local'][$i][0] = $conn;
613 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
614 $this->mErrorConnection
= $conn;
618 wfProfileOut( __METHOD__
);
623 * Open a connection to a foreign DB, or return one if it is already open.
625 * Increments a reference count on the returned connection which locks the
626 * connection to the requested wiki. This reference count can be
627 * decremented by calling reuseConnection().
629 * If a connection is open to the appropriate server already, but with the wrong
630 * database, it will be switched to the right database and returned, as long as
631 * it has been freed first with reuseConnection().
633 * On error, returns false, and the connection which caused the
634 * error will be available via $this->mErrorConnection.
636 * @param $i Integer: server index
637 * @param string $wiki wiki ID to open
638 * @return DatabaseBase
640 function openForeignConnection( $i, $wiki ) {
641 wfProfileIn( __METHOD__
);
642 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
643 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
644 // Reuse an already-used connection
645 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
646 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
647 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
648 // Reuse a free connection for the same wiki
649 $conn = $this->mConns
['foreignFree'][$i][$wiki];
650 unset( $this->mConns
['foreignFree'][$i][$wiki] );
651 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
652 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
653 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
654 // Reuse a connection from another wiki
655 $conn = reset( $this->mConns
['foreignFree'][$i] );
656 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
658 if ( !$conn->selectDB( $dbName ) ) {
659 $this->mLastError
= "Error selecting database $dbName on server " .
660 $conn->getServer() . " from client host " . wfHostname() . "\n";
661 $this->mErrorConnection
= $conn;
664 $conn->tablePrefix( $prefix );
665 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
666 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
667 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
670 // Open a new connection
671 $server = $this->mServers
[$i];
672 $server['serverIndex'] = $i;
673 $server['foreignPoolRefCount'] = 0;
674 $server['foreign'] = true;
675 $conn = $this->reallyOpenConnection( $server, $dbName );
676 if ( !$conn->isOpen() ) {
677 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
678 $this->mErrorConnection
= $conn;
681 $conn->tablePrefix( $prefix );
682 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
683 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
687 // Increment reference count
689 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
690 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
692 wfProfileOut( __METHOD__
);
697 * Test if the specified index represents an open connection
699 * @param $index Integer: server index
703 function isOpen( $index ) {
704 if ( !is_integer( $index ) ) {
707 return (bool)$this->getAnyOpenConnection( $index );
711 * Really opens a connection. Uncached.
712 * Returns a Database object whether or not the connection was successful.
716 * @param $dbNameOverride bool
717 * @throws MWException
718 * @return DatabaseBase
720 function reallyOpenConnection( $server, $dbNameOverride = false ) {
721 if ( !is_array( $server ) ) {
722 throw new MWException( 'You must update your load-balancing configuration. ' .
723 'See DefaultSettings.php entry for $wgDBservers.' );
726 if ( $dbNameOverride !== false ) {
727 $server['dbname'] = $dbNameOverride;
732 $db = DatabaseBase
::factory( $server['type'], $server );
733 } catch ( DBConnectionError
$e ) {
734 // FIXME: This is probably the ugliest thing I have ever done to
735 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
739 $db->setLBInfo( $server );
740 if ( isset( $server['fakeSlaveLag'] ) ) {
741 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
743 if ( isset( $server['fakeMaster'] ) ) {
744 $db->setFakeMaster( true );
750 * @throws DBConnectionError
753 private function reportConnectionError() {
754 $conn = $this->mErrorConnection
; // The connection which caused the error
756 if ( !is_object( $conn ) ) {
757 // No last connection, probably due to all servers being too busy
758 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
760 // If all servers were busy, mLastError will contain something sensible
761 throw new DBConnectionError( null, $this->mLastError
);
763 $server = $conn->getProperty( 'mServer' );
764 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
765 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
767 return false; /* not reached */
773 function getWriterIndex() {
778 * Returns true if the specified index is a valid server index
783 function haveIndex( $i ) {
784 return array_key_exists( $i, $this->mServers
);
788 * Returns true if the specified index is valid and has non-zero load
793 function isNonZeroLoad( $i ) {
794 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
798 * Get the number of defined servers (not the number of open connections)
802 function getServerCount() {
803 return count( $this->mServers
);
807 * Get the host name or IP address of the server with the specified index
808 * Prefer a readable name if available.
812 function getServerName( $i ) {
813 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
814 return $this->mServers
[$i]['hostName'];
815 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
816 return $this->mServers
[$i]['host'];
823 * Return the server info structure for a given index, or false if the index is invalid.
827 function getServerInfo( $i ) {
828 if ( isset( $this->mServers
[$i] ) ) {
829 return $this->mServers
[$i];
836 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
840 function setServerInfo( $i, $serverInfo ) {
841 $this->mServers
[$i] = $serverInfo;
845 * Get the current master position for chronology control purposes
848 function getMasterPos() {
849 # If this entire request was served from a slave without opening a connection to the
850 # master (however unlikely that may be), then we can fetch the position from the slave.
851 $masterConn = $this->getAnyOpenConnection( 0 );
852 if ( !$masterConn ) {
853 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
854 $conn = $this->getAnyOpenConnection( $i );
856 wfDebug( "Master pos fetched from slave\n" );
857 return $conn->getSlavePos();
861 wfDebug( "Master pos fetched from master\n" );
862 return $masterConn->getMasterPos();
868 * Close all open connections
870 function closeAll() {
871 foreach ( $this->mConns
as $conns2 ) {
872 foreach ( $conns2 as $conns3 ) {
873 foreach ( $conns3 as $conn ) {
878 $this->mConns
= array(
880 'foreignFree' => array(),
881 'foreignUsed' => array(),
886 * Deprecated function, typo in function name
888 * @deprecated in 1.18
891 function closeConnecton( $conn ) {
892 wfDeprecated( __METHOD__
, '1.18' );
893 $this->closeConnection( $conn );
898 * Using this function makes sure the LoadBalancer knows the connection is closed.
899 * If you use $conn->close() directly, the load balancer won't update its state.
900 * @param $conn DatabaseBase
902 function closeConnection( $conn ) {
904 foreach ( $this->mConns
as $i1 => $conns2 ) {
905 foreach ( $conns2 as $i2 => $conns3 ) {
906 foreach ( $conns3 as $i3 => $candidateConn ) {
907 if ( $conn === $candidateConn ) {
909 unset( $this->mConns
[$i1][$i2][$i3] );
922 * Commit transactions on all open connections
924 function commitAll() {
925 foreach ( $this->mConns
as $conns2 ) {
926 foreach ( $conns2 as $conns3 ) {
927 foreach ( $conns3 as $conn ) {
928 if ( $conn->trxLevel() ) {
929 $conn->commit( __METHOD__
, 'flush' );
937 * Issue COMMIT only on master, only if queries were done on connection
939 function commitMasterChanges() {
940 // Always 0, but who knows.. :)
941 $masterIndex = $this->getWriterIndex();
942 foreach ( $this->mConns
as $conns2 ) {
943 if ( empty( $conns2[$masterIndex] ) ) {
946 foreach ( $conns2[$masterIndex] as $conn ) {
947 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
948 $conn->commit( __METHOD__
, 'flush' );
958 function waitTimeout( $value = null ) {
959 return wfSetVar( $this->mWaitTimeout
, $value );
965 function getLaggedSlaveMode() {
966 return $this->mLaggedSlaveMode
;
970 * Disables/enables lag checks
974 function allowLagged( $mode = null ) {
975 if ( $mode === null ) {
976 return $this->mAllowLagged
;
978 $this->mAllowLagged
= $mode;
979 return $this->mAllowLagged
;
987 foreach ( $this->mConns
as $conns2 ) {
988 foreach ( $conns2 as $conns3 ) {
989 foreach ( $conns3 as $conn ) {
990 if ( !$conn->ping() ) {
1000 * Call a function with each open connection object
1002 * @param array $params
1004 function forEachOpenConnection( $callback, $params = array() ) {
1005 foreach ( $this->mConns
as $conns2 ) {
1006 foreach ( $conns2 as $conns3 ) {
1007 foreach ( $conns3 as $conn ) {
1008 $mergedParams = array_merge( array( $conn ), $params );
1009 call_user_func_array( $callback, $mergedParams );
1016 * Get the hostname and lag time of the most-lagged slave.
1017 * This is useful for maintenance scripts that need to throttle their updates.
1018 * May attempt to open connections to slaves on the default DB. If there is
1019 * no lag, the maximum lag will be reported as -1.
1021 * @param string $wiki Wiki ID, or false for the default database
1023 * @return array ( host, max lag, index of max lagged host )
1025 function getMaxLag( $wiki = false ) {
1029 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1030 foreach ( $this->mServers
as $i => $conn ) {
1032 if ( $wiki === false ) {
1033 $conn = $this->getAnyOpenConnection( $i );
1036 $conn = $this->openConnection( $i, $wiki );
1041 $lag = $conn->getLag();
1042 if ( $lag > $maxLag ) {
1044 $host = $this->mServers
[$i]['host'];
1049 return array( $host, $maxLag, $maxIndex );
1053 * Get lag time for each server
1054 * Results are cached for a short time in memcached, and indefinitely in the process cache
1060 function getLagTimes( $wiki = false ) {
1062 if ( isset( $this->mLagTimes
) ) {
1063 return $this->mLagTimes
;
1065 if ( $this->getServerCount() == 1 ) {
1067 $this->mLagTimes
= array( 0 => 0 );
1069 # Send the request to the load monitor
1070 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1071 array_keys( $this->mServers
), $wiki );
1073 return $this->mLagTimes
;
1077 * Get the lag in seconds for a given connection, or zero if this load
1078 * balancer does not have replication enabled.
1080 * This should be used in preference to Database::getLag() in cases where
1081 * replication may not be in use, since there is no way to determine if
1082 * replication is in use at the connection level without running
1083 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1084 * function instead of Database::getLag() avoids a fatal error in this
1085 * case on many installations.
1087 * @param $conn DatabaseBase
1091 function safeGetLag( $conn ) {
1092 if ( $this->getServerCount() == 1 ) {
1095 return $conn->getLag();
1100 * Clear the cache for getLagTimes
1102 function clearLagTimeCache() {
1103 $this->mLagTimes
= null;
1108 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1109 * as well handling deferring the actual network connection until the handle is used
1114 class DBConnRef
implements IDatabase
{
1115 /** @var LoadBalancer */
1117 /** @var DatabaseBase|null */
1119 /** @var Array|null */
1123 * @param $lb LoadBalancer
1124 * @param $conn DatabaseBase|array Connection or (server index, group, wiki ID) array
1126 public function __construct( LoadBalancer
$lb, $conn ) {
1128 if ( $conn instanceof DatabaseBase
) {
1129 $this->conn
= $conn;
1131 $this->params
= $conn;
1135 public function __call( $name, $arguments ) {
1136 if ( $this->conn
=== null ) {
1137 list( $db, $groups, $wiki ) = $this->params
;
1138 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1140 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1143 function __destruct() {
1144 if ( $this->conn
!== null ) {
1145 $this->lb
->reuseConnection( $this->conn
);