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 /** @var array Map of (server index => server config array) */
33 /** @var array Map of (local/foreignUsed/foreignFree => server index => DatabaseBase array) */
35 /** @var array Map of (server index => weight) */
37 /** @var array Map of (group => server index => weight) */
39 /** @var bool Whether to disregard slave lag as a factor in slave selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on slave lag to resolve */
42 private $mWaitTimeout;
44 /** @var array LBFactory information */
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
51 /** @var bool|DatabaseBase Database connection that caused a problem */
52 private $mErrorConnection;
53 /** @var integer The generic (not query grouped) slave index (of $mServers) */
55 /** @var bool|DBMasterPos False if not set */
57 /** @var bool Whether the generic reader fell back to a lagged slave */
58 private $mLaggedSlaveMode;
59 /** @var string The last DB selection or connection error */
60 private $mLastError = 'Unknown error';
61 /** @var ProcessCacheLRU */
65 * @param array $params Array with keys:
66 * servers Required. Array of server info structures.
67 * loadMonitor Name of a class used to fetch server lag and load.
70 function __construct( $params ) {
71 if ( !isset( $params['servers'] ) ) {
72 throw new MWException( __CLASS__
. ': missing servers parameter' );
74 $this->mServers
= $params['servers'];
75 $this->mWaitTimeout
= 10;
77 $this->mReadIndex
= -1;
78 $this->mWriteIndex
= -1;
79 $this->mConns
= array(
81 'foreignUsed' => array(),
82 'foreignFree' => array() );
83 $this->mLoads
= array();
84 $this->mWaitForPos
= false;
85 $this->mLaggedSlaveMode
= false;
86 $this->mErrorConnection
= false;
87 $this->mAllowLagged
= false;
89 if ( isset( $params['loadMonitor'] ) ) {
90 $this->mLoadMonitorClass
= $params['loadMonitor'];
92 $master = reset( $params['servers'] );
93 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
94 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
96 $this->mLoadMonitorClass
= 'LoadMonitorNull';
100 foreach ( $params['servers'] as $i => $server ) {
101 $this->mLoads
[$i] = $server['load'];
102 if ( isset( $server['groupLoads'] ) ) {
103 foreach ( $server['groupLoads'] as $group => $ratio ) {
104 if ( !isset( $this->mGroupLoads
[$group] ) ) {
105 $this->mGroupLoads
[$group] = array();
107 $this->mGroupLoads
[$group][$i] = $ratio;
112 $this->mProcCache
= new ProcessCacheLRU( 30 );
116 * Get a LoadMonitor instance
118 * @return LoadMonitor
120 function getLoadMonitor() {
121 if ( !isset( $this->mLoadMonitor
) ) {
122 $class = $this->mLoadMonitorClass
;
123 $this->mLoadMonitor
= new $class( $this );
126 return $this->mLoadMonitor
;
130 * Get or set arbitrary data used by the parent object, usually an LBFactory
134 function parentInfo( $x = null ) {
135 return wfSetVar( $this->mParentInfo
, $x );
139 * Given an array of non-normalised probabilities, this function will select
140 * an element and return the appropriate key
142 * @deprecated since 1.21, use ArrayUtils::pickRandom()
144 * @param array $weights
145 * @return bool|int|string
147 function pickRandom( $weights ) {
148 return ArrayUtils
::pickRandom( $weights );
152 * @param array $loads
153 * @param bool|string $wiki Wiki to get non-lagged for
154 * @return bool|int|string
156 function getRandomNonLagged( $loads, $wiki = false ) {
157 # Unset excessively lagged servers
158 $lags = $this->getLagTimes( $wiki );
159 foreach ( $lags as $i => $lag ) {
161 if ( $lag === false ) {
162 wfDebugLog( 'replication', "Server #$i is not replicating" );
164 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
165 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
171 # Find out if all the slaves with non-zero load are lagged
173 foreach ( $loads as $load ) {
177 # No appropriate DB servers except maybe the master and some slaves with zero load
178 # Do NOT use the master
179 # Instead, this function will return false, triggering read-only mode,
180 # and a lagged slave will be used instead.
184 if ( count( $loads ) == 0 ) {
188 #wfDebugLog( 'connect', var_export( $loads, true ) );
190 # Return a random representative of the remainder
191 return ArrayUtils
::pickRandom( $loads );
195 * Get the index of the reader connection, which may be a slave
196 * This takes into account load ratios and lag times. It should
197 * always return a consistent index during a given invocation
199 * Side effect: opens connections to databases
200 * @param bool|string $group
201 * @param bool|string $wiki
202 * @throws MWException
203 * @return bool|int|string
205 function getReaderIndex( $group = false, $wiki = false ) {
206 global $wgReadOnly, $wgDBtype;
208 # @todo FIXME: For now, only go through all this for mysql databases
209 if ( $wgDBtype != 'mysql' ) {
210 return $this->getWriterIndex();
213 if ( count( $this->mServers
) == 1 ) {
214 # Skip the load balancing if there's only one server
216 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
217 # Shortcut if generic reader exists already
218 return $this->mReadIndex
;
221 $section = new ProfileSection( __METHOD__
);
223 # Find the relevant load array
224 if ( $group !== false ) {
225 if ( isset( $this->mGroupLoads
[$group] ) ) {
226 $nonErrorLoads = $this->mGroupLoads
[$group];
228 # No loads for this group, return false and the caller can use some other group
229 wfDebug( __METHOD__
. ": no loads for group $group\n" );
234 $nonErrorLoads = $this->mLoads
;
237 if ( !count( $nonErrorLoads ) ) {
238 throw new MWException( "Empty server array given to LoadBalancer" );
241 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
242 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
244 $laggedSlaveMode = false;
246 # No server found yet
248 # First try quickly looking through the available servers for a server that
250 $currentLoads = $nonErrorLoads;
251 while ( count( $currentLoads ) ) {
252 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
253 $i = ArrayUtils
::pickRandom( $currentLoads );
255 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
256 if ( $i === false && count( $currentLoads ) != 0 ) {
257 # All slaves lagged. Switch to read-only mode
258 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
259 $wgReadOnly = 'The database has been automatically locked ' .
260 'while the slave database servers catch up to the master';
261 $i = ArrayUtils
::pickRandom( $currentLoads );
262 $laggedSlaveMode = true;
266 if ( $i === false ) {
267 # pickRandom() returned false
268 # This is permanent and means the configuration or the load monitor
269 # wants us to return false.
270 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
275 wfDebugLog( 'connect', __METHOD__
.
276 ": Using reader #$i: {$this->mServers[$i]['host']}..." );
278 $conn = $this->openConnection( $i, $wiki );
280 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
281 unset( $nonErrorLoads[$i] );
282 unset( $currentLoads[$i] );
287 // Decrement reference counter, we are finished with this connection.
288 // It will be incremented for the caller later.
289 if ( $wiki !== false ) {
290 $this->reuseConnection( $conn );
297 # If all servers were down, quit now
298 if ( !count( $nonErrorLoads ) ) {
299 wfDebugLog( 'connect', "All servers down" );
302 if ( $i !== false ) {
303 # Slave connection successful
304 # Wait for the session master pos for a short time
305 if ( $this->mWaitForPos
&& $i > 0 ) {
306 if ( !$this->doWait( $i ) ) {
307 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
310 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group !== false ) {
311 $this->mReadIndex
= $i;
319 * Wait for a specified number of microseconds, and return the period waited
323 function sleep( $t ) {
324 wfProfileIn( __METHOD__
);
325 wfDebug( __METHOD__
. ": waiting $t us\n" );
327 wfProfileOut( __METHOD__
);
333 * Set the master wait position
334 * If a DB_SLAVE connection has been opened already, waits
335 * Otherwise sets a variable telling it to wait if such a connection is opened
336 * @param DBMasterPos $pos
338 public function waitFor( $pos ) {
339 wfProfileIn( __METHOD__
);
340 $this->mWaitForPos
= $pos;
341 $i = $this->mReadIndex
;
344 if ( !$this->doWait( $i ) ) {
345 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
346 $this->mLaggedSlaveMode
= true;
349 wfProfileOut( __METHOD__
);
353 * Set the master wait position and wait for ALL slaves to catch up to it
354 * @param DBMasterPos $pos
355 * @param int $timeout Max seconds to wait; default is mWaitTimeout
356 * @return bool Success (able to connect and no timeouts reached)
358 public function waitForAll( $pos, $timeout = null ) {
359 wfProfileIn( __METHOD__
);
360 $this->mWaitForPos
= $pos;
361 $serverCount = count( $this->mServers
);
364 for ( $i = 1; $i < $serverCount; $i++
) {
365 if ( $this->mLoads
[$i] > 0 ) {
366 $ok = $this->doWait( $i, true, $timeout ) && $ok;
369 wfProfileOut( __METHOD__
);
375 * Get any open connection to a given server index, local or foreign
376 * Returns false if there is no connection open
379 * @return DatabaseBase|bool False on failure
381 function getAnyOpenConnection( $i ) {
382 foreach ( $this->mConns
as $conns ) {
383 if ( !empty( $conns[$i] ) ) {
384 return reset( $conns[$i] );
392 * Wait for a given slave to catch up to the master pos stored in $this
393 * @param int $index Server index
394 * @param bool $open Check the server even if a new connection has to be made
395 * @param int $timeout Max seconds to wait; default is mWaitTimeout
398 protected function doWait( $index, $open = false, $timeout = null ) {
399 $close = false; // close the connection afterwards
401 # Find a connection to wait on, creating one if needed and allowed
402 $conn = $this->getAnyOpenConnection( $index );
405 wfDebug( __METHOD__
. ": no connection open\n" );
409 $conn = $this->openConnection( $index, '' );
411 wfDebug( __METHOD__
. ": failed to open connection\n" );
415 // Avoid connection spam in waitForAll() when connections
416 // are made just for the sake of doing this lag check.
421 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
422 $timeout = $timeout ?
: $this->mWaitTimeout
;
423 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
425 if ( $result == -1 ||
is_null( $result ) ) {
426 # Timed out waiting for slave, use master instead
427 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
430 wfDebug( __METHOD__
. ": Done\n" );
435 $this->closeConnection( $conn );
442 * Get a connection by index
443 * This is the main entry point for this class.
445 * @param int $i Server index
446 * @param array $groups Query groups
447 * @param bool|string $wiki Wiki ID
449 * @throws MWException
450 * @return DatabaseBase
452 public function &getConnection( $i, $groups = array(), $wiki = false ) {
453 wfProfileIn( __METHOD__
);
455 if ( $i === null ||
$i === false ) {
456 wfProfileOut( __METHOD__
);
457 throw new MWException( 'Attempt to call ' . __METHOD__
.
458 ' with invalid server index' );
461 if ( $wiki === wfWikiID() ) {
466 if ( $i == DB_MASTER
) {
467 $i = $this->getWriterIndex();
468 } elseif ( !is_array( $groups ) ) {
469 $groupIndex = $this->getReaderIndex( $groups, $wiki );
470 if ( $groupIndex !== false ) {
471 $serverName = $this->getServerName( $groupIndex );
472 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
476 foreach ( $groups as $group ) {
477 $groupIndex = $this->getReaderIndex( $group, $wiki );
478 if ( $groupIndex !== false ) {
479 $serverName = $this->getServerName( $groupIndex );
480 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
487 # Operation-based index
488 if ( $i == DB_SLAVE
) {
489 $this->mLastError
= 'Unknown error'; // reset error string
490 $i = $this->getReaderIndex( false, $wiki );
491 # Couldn't find a working server in getReaderIndex()?
492 if ( $i === false ) {
493 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
494 wfProfileOut( __METHOD__
);
496 return $this->reportConnectionError();
500 # Now we have an explicit index into the servers array
501 $conn = $this->openConnection( $i, $wiki );
503 wfProfileOut( __METHOD__
);
505 return $this->reportConnectionError();
508 wfProfileOut( __METHOD__
);
514 * Mark a foreign connection as being available for reuse under a different
515 * DB name or prefix. This mechanism is reference-counted, and must be called
516 * the same number of times as getConnection() to work.
518 * @param DatabaseBase $conn
519 * @throws MWException
521 public function reuseConnection( $conn ) {
522 $serverIndex = $conn->getLBInfo( 'serverIndex' );
523 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
524 if ( $serverIndex === null ||
$refCount === null ) {
525 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
528 * This can happen in code like:
529 * foreach ( $dbs as $db ) {
530 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
532 * $lb->reuseConnection( $conn );
534 * When a connection to the local DB is opened in this way, reuseConnection()
541 $dbName = $conn->getDBname();
542 $prefix = $conn->tablePrefix();
543 if ( strval( $prefix ) !== '' ) {
544 $wiki = "$dbName-$prefix";
548 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
549 throw new MWException( __METHOD__
. ": connection not found, has " .
550 "the connection been freed already?" );
552 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
553 if ( $refCount <= 0 ) {
554 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
555 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
556 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
558 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
563 * Get a database connection handle reference
565 * The handle's methods wrap simply wrap those of a DatabaseBase handle
567 * @see LoadBalancer::getConnection() for parameter information
570 * @param mixed $groups
571 * @param bool|string $wiki
574 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
575 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
579 * Get a database connection handle reference without connecting yet
581 * The handle's methods wrap simply wrap those of a DatabaseBase handle
583 * @see LoadBalancer::getConnection() for parameter information
586 * @param mixed $groups
587 * @param bool|string $wiki
590 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
591 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
595 * Open a connection to the server given by the specified index
596 * Index must be an actual index into the array.
597 * If the server is already open, returns it.
599 * On error, returns false, and the connection which caused the
600 * error will be available via $this->mErrorConnection.
602 * @param int $i Server index
603 * @param bool|string $wiki Wiki ID to open
604 * @return DatabaseBase
608 function openConnection( $i, $wiki = false ) {
609 wfProfileIn( __METHOD__
);
610 if ( $wiki !== false ) {
611 $conn = $this->openForeignConnection( $i, $wiki );
612 wfProfileOut( __METHOD__
);
616 if ( isset( $this->mConns
['local'][$i][0] ) ) {
617 $conn = $this->mConns
['local'][$i][0];
619 $server = $this->mServers
[$i];
620 $server['serverIndex'] = $i;
621 $conn = $this->reallyOpenConnection( $server, false );
622 if ( $conn->isOpen() ) {
623 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
624 $this->mConns
['local'][$i][0] = $conn;
626 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
627 $this->mErrorConnection
= $conn;
631 wfProfileOut( __METHOD__
);
637 * Open a connection to a foreign DB, or return one if it is already open.
639 * Increments a reference count on the returned connection which locks the
640 * connection to the requested wiki. This reference count can be
641 * decremented by calling reuseConnection().
643 * If a connection is open to the appropriate server already, but with the wrong
644 * database, it will be switched to the right database and returned, as long as
645 * it has been freed first with reuseConnection().
647 * On error, returns false, and the connection which caused the
648 * error will be available via $this->mErrorConnection.
650 * @param int $i Server index
651 * @param string $wiki Wiki ID to open
652 * @return DatabaseBase
654 function openForeignConnection( $i, $wiki ) {
655 wfProfileIn( __METHOD__
);
656 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
657 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
658 // Reuse an already-used connection
659 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
660 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
661 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
662 // Reuse a free connection for the same wiki
663 $conn = $this->mConns
['foreignFree'][$i][$wiki];
664 unset( $this->mConns
['foreignFree'][$i][$wiki] );
665 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
666 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
667 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
668 // Reuse a connection from another wiki
669 $conn = reset( $this->mConns
['foreignFree'][$i] );
670 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
672 if ( !$conn->selectDB( $dbName ) ) {
673 $this->mLastError
= "Error selecting database $dbName on server " .
674 $conn->getServer() . " from client host " . wfHostname() . "\n";
675 $this->mErrorConnection
= $conn;
678 $conn->tablePrefix( $prefix );
679 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
680 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
681 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
684 // Open a new connection
685 $server = $this->mServers
[$i];
686 $server['serverIndex'] = $i;
687 $server['foreignPoolRefCount'] = 0;
688 $server['foreign'] = true;
689 $conn = $this->reallyOpenConnection( $server, $dbName );
690 if ( !$conn->isOpen() ) {
691 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
692 $this->mErrorConnection
= $conn;
695 $conn->tablePrefix( $prefix );
696 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
697 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
701 // Increment reference count
703 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
704 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
706 wfProfileOut( __METHOD__
);
712 * Test if the specified index represents an open connection
714 * @param int $index Server index
718 function isOpen( $index ) {
719 if ( !is_integer( $index ) ) {
723 return (bool)$this->getAnyOpenConnection( $index );
727 * Really opens a connection. Uncached.
728 * Returns a Database object whether or not the connection was successful.
731 * @param array $server
732 * @param bool $dbNameOverride
733 * @throws MWException
734 * @return DatabaseBase
736 function reallyOpenConnection( $server, $dbNameOverride = false ) {
737 if ( !is_array( $server ) ) {
738 throw new MWException( 'You must update your load-balancing configuration. ' .
739 'See DefaultSettings.php entry for $wgDBservers.' );
742 if ( $dbNameOverride !== false ) {
743 $server['dbname'] = $dbNameOverride;
748 $db = DatabaseBase
::factory( $server['type'], $server );
749 } catch ( DBConnectionError
$e ) {
750 // FIXME: This is probably the ugliest thing I have ever done to
751 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
755 $db->setLBInfo( $server );
756 if ( isset( $server['fakeSlaveLag'] ) ) {
757 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
759 if ( isset( $server['fakeMaster'] ) ) {
760 $db->setFakeMaster( true );
767 * @throws DBConnectionError
770 private function reportConnectionError() {
771 $conn = $this->mErrorConnection
; // The connection which caused the error
773 if ( !is_object( $conn ) ) {
774 // No last connection, probably due to all servers being too busy
775 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}" );
777 // If all servers were busy, mLastError will contain something sensible
778 throw new DBConnectionError( null, $this->mLastError
);
780 $server = $conn->getProperty( 'mServer' );
781 wfLogDBError( "Connection error: {$this->mLastError} ({$server})" );
782 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
785 return false; /* not reached */
791 function getWriterIndex() {
796 * Returns true if the specified index is a valid server index
801 function haveIndex( $i ) {
802 return array_key_exists( $i, $this->mServers
);
806 * Returns true if the specified index is valid and has non-zero load
811 function isNonZeroLoad( $i ) {
812 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
816 * Get the number of defined servers (not the number of open connections)
820 function getServerCount() {
821 return count( $this->mServers
);
825 * Get the host name or IP address of the server with the specified index
826 * Prefer a readable name if available.
830 function getServerName( $i ) {
831 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
832 return $this->mServers
[$i]['hostName'];
833 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
834 return $this->mServers
[$i]['host'];
841 * Return the server info structure for a given index, or false if the index is invalid.
845 function getServerInfo( $i ) {
846 if ( isset( $this->mServers
[$i] ) ) {
847 return $this->mServers
[$i];
854 * Sets the server info structure for the given index. Entry at index $i
855 * is created if it doesn't exist
857 * @param array $serverInfo
859 function setServerInfo( $i, $serverInfo ) {
860 $this->mServers
[$i] = $serverInfo;
864 * Get the current master position for chronology control purposes
867 function getMasterPos() {
868 # If this entire request was served from a slave without opening a connection to the
869 # master (however unlikely that may be), then we can fetch the position from the slave.
870 $masterConn = $this->getAnyOpenConnection( 0 );
871 if ( !$masterConn ) {
872 $serverCount = count( $this->mServers
);
873 for ( $i = 1; $i < $serverCount; $i++
) {
874 $conn = $this->getAnyOpenConnection( $i );
876 wfDebug( "Master pos fetched from slave\n" );
878 return $conn->getSlavePos();
882 wfDebug( "Master pos fetched from master\n" );
884 return $masterConn->getMasterPos();
891 * Close all open connections
893 function closeAll() {
894 foreach ( $this->mConns
as $conns2 ) {
895 foreach ( $conns2 as $conns3 ) {
896 /** @var DatabaseBase $conn */
897 foreach ( $conns3 as $conn ) {
902 $this->mConns
= array(
904 'foreignFree' => array(),
905 'foreignUsed' => array(),
911 * Using this function makes sure the LoadBalancer knows the connection is closed.
912 * If you use $conn->close() directly, the load balancer won't update its state.
913 * @param DatabaseBase $conn
915 function closeConnection( $conn ) {
917 foreach ( $this->mConns
as $i1 => $conns2 ) {
918 foreach ( $conns2 as $i2 => $conns3 ) {
919 foreach ( $conns3 as $i3 => $candidateConn ) {
920 if ( $conn === $candidateConn ) {
922 unset( $this->mConns
[$i1][$i2][$i3] );
935 * Commit transactions on all open connections
937 function commitAll() {
938 foreach ( $this->mConns
as $conns2 ) {
939 foreach ( $conns2 as $conns3 ) {
940 /** @var DatabaseBase[] $conns3 */
941 foreach ( $conns3 as $conn ) {
942 if ( $conn->trxLevel() ) {
943 $conn->commit( __METHOD__
, 'flush' );
951 * Issue COMMIT only on master, only if queries were done on connection
953 function commitMasterChanges() {
954 // Always 0, but who knows.. :)
955 $masterIndex = $this->getWriterIndex();
956 foreach ( $this->mConns
as $conns2 ) {
957 if ( empty( $conns2[$masterIndex] ) ) {
960 /** @var DatabaseBase $conn */
961 foreach ( $conns2[$masterIndex] as $conn ) {
962 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
963 $conn->commit( __METHOD__
, 'flush' );
970 * Issue ROLLBACK only on master, only if queries were done on connection
973 function rollbackMasterChanges() {
974 // Always 0, but who knows.. :)
975 $masterIndex = $this->getWriterIndex();
976 foreach ( $this->mConns
as $conns2 ) {
977 if ( empty( $conns2[$masterIndex] ) ) {
980 /** @var DatabaseBase $conn */
981 foreach ( $conns2[$masterIndex] as $conn ) {
982 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
983 $conn->rollback( __METHOD__
, 'flush' );
990 * @return bool Whether a master connection is already open
993 function hasMasterConnection() {
994 return $this->isOpen( $this->getWriterIndex() );
998 * Determine if there are any pending changes that need to be rolled back
1003 function hasMasterChanges() {
1004 // Always 0, but who knows.. :)
1005 $masterIndex = $this->getWriterIndex();
1006 foreach ( $this->mConns
as $conns2 ) {
1007 if ( empty( $conns2[$masterIndex] ) ) {
1010 /** @var DatabaseBase $conn */
1011 foreach ( $conns2[$masterIndex] as $conn ) {
1012 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1021 * @param mixed $value
1024 function waitTimeout( $value = null ) {
1025 return wfSetVar( $this->mWaitTimeout
, $value );
1031 function getLaggedSlaveMode() {
1032 return $this->mLaggedSlaveMode
;
1036 * Disables/enables lag checks
1037 * @param null|bool $mode
1040 function allowLagged( $mode = null ) {
1041 if ( $mode === null ) {
1042 return $this->mAllowLagged
;
1044 $this->mAllowLagged
= $mode;
1046 return $this->mAllowLagged
;
1052 function pingAll() {
1054 foreach ( $this->mConns
as $conns2 ) {
1055 foreach ( $conns2 as $conns3 ) {
1056 /** @var DatabaseBase[] $conns3 */
1057 foreach ( $conns3 as $conn ) {
1058 if ( !$conn->ping() ) {
1069 * Call a function with each open connection object
1070 * @param callable $callback
1071 * @param array $params
1073 function forEachOpenConnection( $callback, $params = array() ) {
1074 foreach ( $this->mConns
as $conns2 ) {
1075 foreach ( $conns2 as $conns3 ) {
1076 foreach ( $conns3 as $conn ) {
1077 $mergedParams = array_merge( array( $conn ), $params );
1078 call_user_func_array( $callback, $mergedParams );
1085 * Get the hostname and lag time of the most-lagged slave
1087 * This is useful for maintenance scripts that need to throttle their updates.
1088 * May attempt to open connections to slaves on the default DB. If there is
1089 * no lag, the maximum lag will be reported as -1.
1091 * @param bool|string $wiki Wiki ID, or false for the default database
1092 * @return array ( host, max lag, index of max lagged host )
1094 function getMaxLag( $wiki = false ) {
1099 if ( $this->getServerCount() <= 1 ) {
1100 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1103 $lagTimes = $this->getLagTimes( $wiki );
1104 foreach ( $lagTimes as $i => $lag ) {
1105 if ( $lag > $maxLag ) {
1107 $host = $this->mServers
[$i]['host'];
1112 return array( $host, $maxLag, $maxIndex );
1116 * Get lag time for each server
1118 * Results are cached for a short time in memcached/process cache
1120 * @param string|bool $wiki
1121 * @return array Map of (server index => seconds)
1123 function getLagTimes( $wiki = false ) {
1124 if ( $this->getServerCount() <= 1 ) {
1125 return array( 0 => 0 ); // no replication = no lag
1128 if ( $this->mProcCache
->has( 'slave_lag', 'times', 1 ) ) {
1129 return $this->mProcCache
->get( 'slave_lag', 'times' );
1132 # Send the request to the load monitor
1133 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1135 $this->mProcCache
->set( 'slave_lag', 'times', $times );
1141 * Get the lag in seconds for a given connection, or zero if this load
1142 * balancer does not have replication enabled.
1144 * This should be used in preference to Database::getLag() in cases where
1145 * replication may not be in use, since there is no way to determine if
1146 * replication is in use at the connection level without running
1147 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1148 * function instead of Database::getLag() avoids a fatal error in this
1149 * case on many installations.
1151 * @param DatabaseBase $conn
1154 function safeGetLag( $conn ) {
1155 if ( $this->getServerCount() == 1 ) {
1158 return $conn->getLag();
1163 * Clear the cache for slag lag delay times
1165 function clearLagTimeCache() {
1166 $this->mProcCache
->clear( 'slave_lag' );
1171 * Helper class to handle automatically marking connections as reusable (via RAII pattern)
1172 * as well handling deferring the actual network connection until the handle is used
1177 class DBConnRef
implements IDatabase
{
1178 /** @var LoadBalancer */
1181 /** @var DatabaseBase|null */
1184 /** @var array|null */
1188 * @param LoadBalancer $lb
1189 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1191 public function __construct( LoadBalancer
$lb, $conn ) {
1193 if ( $conn instanceof DatabaseBase
) {
1194 $this->conn
= $conn;
1196 $this->params
= $conn;
1200 public function __call( $name, $arguments ) {
1201 if ( $this->conn
=== null ) {
1202 list( $db, $groups, $wiki ) = $this->params
;
1203 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1206 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1209 function __destruct() {
1210 if ( $this->conn
!== null ) {
1211 $this->lb
->reuseConnection( $this->conn
);