128118781f96db881863a463a79b643057b7ba51
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 integer Total connections opened */
62 private $connsOpened = 0;
63 /** @var ProcessCacheLRU */
66 /** @var integer Warn when this many connection are held */
67 const CONN_HELD_WARN_THRESHOLD
= 10;
70 * @param array $params Array with keys:
71 * servers Required. Array of server info structures.
72 * loadMonitor Name of a class used to fetch server lag and load.
75 public function __construct( array $params ) {
76 if ( !isset( $params['servers'] ) ) {
77 throw new MWException( __CLASS__
. ': missing servers parameter' );
79 $this->mServers
= $params['servers'];
80 $this->mWaitTimeout
= 10;
82 $this->mReadIndex
= -1;
83 $this->mWriteIndex
= -1;
84 $this->mConns
= array(
86 'foreignUsed' => array(),
87 'foreignFree' => array() );
88 $this->mLoads
= array();
89 $this->mWaitForPos
= false;
90 $this->mLaggedSlaveMode
= false;
91 $this->mErrorConnection
= false;
92 $this->mAllowLagged
= false;
94 if ( isset( $params['loadMonitor'] ) ) {
95 $this->mLoadMonitorClass
= $params['loadMonitor'];
97 $master = reset( $params['servers'] );
98 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
99 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
101 $this->mLoadMonitorClass
= 'LoadMonitorNull';
105 foreach ( $params['servers'] as $i => $server ) {
106 $this->mLoads
[$i] = $server['load'];
107 if ( isset( $server['groupLoads'] ) ) {
108 foreach ( $server['groupLoads'] as $group => $ratio ) {
109 if ( !isset( $this->mGroupLoads
[$group] ) ) {
110 $this->mGroupLoads
[$group] = array();
112 $this->mGroupLoads
[$group][$i] = $ratio;
117 $this->mProcCache
= new ProcessCacheLRU( 30 );
121 * Get a LoadMonitor instance
123 * @return LoadMonitor
125 private function getLoadMonitor() {
126 if ( !isset( $this->mLoadMonitor
) ) {
127 $class = $this->mLoadMonitorClass
;
128 $this->mLoadMonitor
= new $class( $this );
131 return $this->mLoadMonitor
;
135 * Get or set arbitrary data used by the parent object, usually an LBFactory
139 public function parentInfo( $x = null ) {
140 return wfSetVar( $this->mParentInfo
, $x );
144 * Given an array of non-normalised probabilities, this function will select
145 * an element and return the appropriate key
147 * @deprecated since 1.21, use ArrayUtils::pickRandom()
149 * @param array $weights
150 * @return bool|int|string
152 public function pickRandom( array $weights ) {
153 return ArrayUtils
::pickRandom( $weights );
157 * @param array $loads
158 * @param bool|string $wiki Wiki to get non-lagged for
159 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
160 * @return bool|int|string
162 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
163 $lags = $this->getLagTimes( $wiki );
165 # Unset excessively lagged servers
166 foreach ( $lags as $i => $lag ) {
168 $maxServerLag = $maxLag;
169 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
170 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
172 if ( $lag === false ) {
173 wfDebugLog( 'replication', "Server #$i is not replicating" );
175 } elseif ( $lag > $maxServerLag ) {
176 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
182 # Find out if all the slaves with non-zero load are lagged
184 foreach ( $loads as $load ) {
188 # No appropriate DB servers except maybe the master and some slaves with zero load
189 # Do NOT use the master
190 # Instead, this function will return false, triggering read-only mode,
191 # and a lagged slave will be used instead.
195 if ( count( $loads ) == 0 ) {
199 #wfDebugLog( 'connect', var_export( $loads, true ) );
201 # Return a random representative of the remainder
202 return ArrayUtils
::pickRandom( $loads );
206 * Get the index of the reader connection, which may be a slave
207 * This takes into account load ratios and lag times. It should
208 * always return a consistent index during a given invocation
210 * Side effect: opens connections to databases
211 * @param string|bool $group Query group, or false for the generic reader
212 * @param string|bool $wiki Wiki ID, or false for the current wiki
213 * @throws MWException
214 * @return bool|int|string
216 public function getReaderIndex( $group = false, $wiki = false ) {
219 # @todo FIXME: For now, only go through all this for mysql databases
220 if ( $wgDBtype != 'mysql' ) {
221 return $this->getWriterIndex();
224 if ( count( $this->mServers
) == 1 ) {
225 # Skip the load balancing if there's only one server
227 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
228 # Shortcut if generic reader exists already
229 return $this->mReadIndex
;
232 # Find the relevant load array
233 if ( $group !== false ) {
234 if ( isset( $this->mGroupLoads
[$group] ) ) {
235 $nonErrorLoads = $this->mGroupLoads
[$group];
237 # No loads for this group, return false and the caller can use some other group
238 wfDebug( __METHOD__
. ": no loads for group $group\n" );
243 $nonErrorLoads = $this->mLoads
;
246 if ( !count( $nonErrorLoads ) ) {
247 throw new MWException( "Empty server array given to LoadBalancer" );
250 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
251 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
253 $laggedSlaveMode = false;
255 # No server found yet
257 # First try quickly looking through the available servers for a server that
259 $currentLoads = $nonErrorLoads;
260 while ( count( $currentLoads ) ) {
261 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
262 $i = ArrayUtils
::pickRandom( $currentLoads );
265 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
266 # ChronologyProtecter causes mWaitForPos to be set via sessions.
267 # This triggers doWait() after connect, so it's especially good to
268 # avoid lagged servers so as to avoid just blocking in that method.
269 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
270 # Aim for <= 1 second of waiting (being too picky can backfire)
271 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
273 if ( $i === false ) {
274 # Any server with less lag than it's 'max lag' param is preferable
275 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
277 if ( $i === false && count( $currentLoads ) != 0 ) {
278 # All slaves lagged. Switch to read-only mode
279 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
280 $i = ArrayUtils
::pickRandom( $currentLoads );
281 $laggedSlaveMode = true;
285 if ( $i === false ) {
286 # pickRandom() returned false
287 # This is permanent and means the configuration or the load monitor
288 # wants us to return false.
289 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
294 $serverName = $this->getServerName( $i );
295 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
297 $conn = $this->openConnection( $i, $wiki );
299 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
300 unset( $nonErrorLoads[$i] );
301 unset( $currentLoads[$i] );
306 // Decrement reference counter, we are finished with this connection.
307 // It will be incremented for the caller later.
308 if ( $wiki !== false ) {
309 $this->reuseConnection( $conn );
316 # If all servers were down, quit now
317 if ( !count( $nonErrorLoads ) ) {
318 wfDebugLog( 'connect', "All servers down" );
321 if ( $i !== false ) {
322 # Slave connection successful
323 # Wait for the session master pos for a short time
324 if ( $this->mWaitForPos
&& $i > 0 ) {
325 if ( !$this->doWait( $i ) ) {
326 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
329 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
330 $this->mReadIndex
= $i;
331 # Record if the generic reader index is in "lagged slave" mode
332 if ( $laggedSlaveMode ) {
333 $this->mLaggedSlaveMode
= true;
336 $serverName = $this->getServerName( $i );
337 wfDebug( __METHOD__
. ": using server $serverName for group '$group'\n" );
344 * Set the master wait position
345 * If a DB_SLAVE connection has been opened already, waits
346 * Otherwise sets a variable telling it to wait if such a connection is opened
347 * @param DBMasterPos $pos
349 public function waitFor( $pos ) {
350 $this->mWaitForPos
= $pos;
351 $i = $this->mReadIndex
;
354 if ( !$this->doWait( $i ) ) {
355 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
356 $this->mLaggedSlaveMode
= true;
362 * Set the master wait position and wait for a "generic" slave to catch up to it
364 * This can be used a faster proxy for waitForAll()
366 * @param DBMasterPos $pos
367 * @param int $timeout Max seconds to wait; default is mWaitTimeout
368 * @return bool Success (able to connect and no timeouts reached)
371 public function waitForOne( $pos, $timeout = null ) {
372 $this->mWaitForPos
= $pos;
374 $i = $this->mReadIndex
;
376 // Pick a generic slave if there isn't one yet
377 $readLoads = $this->mLoads
;
378 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
379 $readLoads = array_filter( $readLoads ); // with non-zero load
380 $i = ArrayUtils
::pickRandom( $readLoads );
384 $ok = $this->doWait( $i, true, $timeout );
386 $ok = true; // no applicable loads
393 * Set the master wait position and wait for ALL slaves to catch up to it
394 * @param DBMasterPos $pos
395 * @param int $timeout Max seconds to wait; default is mWaitTimeout
396 * @return bool Success (able to connect and no timeouts reached)
398 public function waitForAll( $pos, $timeout = null ) {
399 $this->mWaitForPos
= $pos;
400 $serverCount = count( $this->mServers
);
403 for ( $i = 1; $i < $serverCount; $i++
) {
404 if ( $this->mLoads
[$i] > 0 ) {
405 $ok = $this->doWait( $i, true, $timeout ) && $ok;
413 * Get any open connection to a given server index, local or foreign
414 * Returns false if there is no connection open
417 * @return DatabaseBase|bool False on failure
419 public function getAnyOpenConnection( $i ) {
420 foreach ( $this->mConns
as $conns ) {
421 if ( !empty( $conns[$i] ) ) {
422 return reset( $conns[$i] );
430 * Wait for a given slave to catch up to the master pos stored in $this
431 * @param int $index Server index
432 * @param bool $open Check the server even if a new connection has to be made
433 * @param int $timeout Max seconds to wait; default is mWaitTimeout
436 protected function doWait( $index, $open = false, $timeout = null ) {
437 $close = false; // close the connection afterwards
439 # Find a connection to wait on, creating one if needed and allowed
440 $conn = $this->getAnyOpenConnection( $index );
443 wfDebug( __METHOD__
. ": no connection open\n" );
447 $conn = $this->openConnection( $index, '' );
449 wfDebug( __METHOD__
. ": failed to open connection\n" );
453 // Avoid connection spam in waitForAll() when connections
454 // are made just for the sake of doing this lag check.
459 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
460 $timeout = $timeout ?
: $this->mWaitTimeout
;
461 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
463 if ( $result == -1 ||
is_null( $result ) ) {
464 # Timed out waiting for slave, use master instead
465 $server = $server = $this->getServerName( $index );
466 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
468 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
471 wfDebug( __METHOD__
. ": Done\n" );
476 $this->closeConnection( $conn );
483 * Get a connection by index
484 * This is the main entry point for this class.
486 * @param int $i Server index
487 * @param array|string|bool $groups Query group(s), or false for the generic reader
488 * @param string|bool $wiki Wiki ID, or false for the current wiki
490 * @throws MWException
491 * @return DatabaseBase
493 public function getConnection( $i, $groups = array(), $wiki = false ) {
494 if ( $i === null ||
$i === false ) {
495 throw new MWException( 'Attempt to call ' . __METHOD__
.
496 ' with invalid server index' );
499 if ( $wiki === wfWikiID() ) {
503 $groups = ( $groups === false ||
$groups === array() )
504 ?
array( false ) // check one "group": the generic pool
507 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
508 $oldConnsOpened = $this->connsOpened
; // connections open now
510 if ( $i == DB_MASTER
) {
511 $i = $this->getWriterIndex();
513 # Try to find an available server in any the query groups (in order)
514 foreach ( $groups as $group ) {
515 $groupIndex = $this->getReaderIndex( $group, $wiki );
516 if ( $groupIndex !== false ) {
523 # Operation-based index
524 if ( $i == DB_SLAVE
) {
525 $this->mLastError
= 'Unknown error'; // reset error string
526 # Try the general server pool if $groups are unavailable.
527 $i = in_array( false, $groups, true )
528 ?
false // don't bother with this if that is what was tried above
529 : $this->getReaderIndex( false, $wiki );
530 # Couldn't find a working server in getReaderIndex()?
531 if ( $i === false ) {
532 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
534 return $this->reportConnectionError();
538 # Now we have an explicit index into the servers array
539 $conn = $this->openConnection( $i, $wiki );
541 return $this->reportConnectionError();
544 # Profile any new connections that happen
545 if ( $this->connsOpened
> $oldConnsOpened ) {
546 $host = $conn->getServer();
547 $dbname = $conn->getDBname();
548 $trxProf = Profiler
::instance()->getTransactionProfiler();
549 $trxProf->recordConnection( $host, $dbname, $masterOnly );
556 * Mark a foreign connection as being available for reuse under a different
557 * DB name or prefix. This mechanism is reference-counted, and must be called
558 * the same number of times as getConnection() to work.
560 * @param DatabaseBase $conn
561 * @throws MWException
563 public function reuseConnection( $conn ) {
564 $serverIndex = $conn->getLBInfo( 'serverIndex' );
565 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
566 if ( $serverIndex === null ||
$refCount === null ) {
567 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
570 * This can happen in code like:
571 * foreach ( $dbs as $db ) {
572 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
574 * $lb->reuseConnection( $conn );
576 * When a connection to the local DB is opened in this way, reuseConnection()
583 $dbName = $conn->getDBname();
584 $prefix = $conn->tablePrefix();
585 if ( strval( $prefix ) !== '' ) {
586 $wiki = "$dbName-$prefix";
590 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
591 throw new MWException( __METHOD__
. ": connection not found, has " .
592 "the connection been freed already?" );
594 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
595 if ( $refCount <= 0 ) {
596 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
597 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
598 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
600 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
605 * Get a database connection handle reference
607 * The handle's methods wrap simply wrap those of a DatabaseBase handle
609 * @see LoadBalancer::getConnection() for parameter information
612 * @param array|string|bool $groups Query group(s), or false for the generic reader
613 * @param string|bool $wiki Wiki ID, or false for the current wiki
616 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
617 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
621 * Get a database connection handle reference without connecting yet
623 * The handle's methods wrap simply wrap those of a DatabaseBase handle
625 * @see LoadBalancer::getConnection() for parameter information
628 * @param array|string|bool $groups Query group(s), or false for the generic reader
629 * @param string|bool $wiki Wiki ID, or false for the current wiki
632 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
633 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
637 * Open a connection to the server given by the specified index
638 * Index must be an actual index into the array.
639 * If the server is already open, returns it.
641 * On error, returns false, and the connection which caused the
642 * error will be available via $this->mErrorConnection.
644 * @param int $i Server index
645 * @param string|bool $wiki Wiki ID, or false for the current wiki
646 * @return DatabaseBase
650 public function openConnection( $i, $wiki = false ) {
651 if ( $wiki !== false ) {
652 $conn = $this->openForeignConnection( $i, $wiki );
653 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
654 $conn = $this->mConns
['local'][$i][0];
656 $server = $this->mServers
[$i];
657 $server['serverIndex'] = $i;
658 $conn = $this->reallyOpenConnection( $server, false );
659 $serverName = $this->getServerName( $i );
660 if ( $conn->isOpen() ) {
661 wfDebug( "Connected to database $i at $serverName\n" );
662 $this->mConns
['local'][$i][0] = $conn;
664 wfDebug( "Failed to connect to database $i at $serverName\n" );
665 $this->mErrorConnection
= $conn;
670 if ( $conn && !$conn->isOpen() ) {
671 // Connection was made but later unrecoverably lost for some reason.
672 // Do not return a handle that will just throw exceptions on use,
673 // but let the calling code (e.g. getReaderIndex) try another server.
674 // See DatabaseMyslBase::ping() for how this can happen.
675 $this->mErrorConnection
= $conn;
683 * Open a connection to a foreign DB, or return one if it is already open.
685 * Increments a reference count on the returned connection which locks the
686 * connection to the requested wiki. This reference count can be
687 * decremented by calling reuseConnection().
689 * If a connection is open to the appropriate server already, but with the wrong
690 * database, it will be switched to the right database and returned, as long as
691 * it has been freed first with reuseConnection().
693 * On error, returns false, and the connection which caused the
694 * error will be available via $this->mErrorConnection.
696 * @param int $i Server index
697 * @param string $wiki Wiki ID to open
698 * @return DatabaseBase
700 private function openForeignConnection( $i, $wiki ) {
701 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
702 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
703 // Reuse an already-used connection
704 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
705 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
706 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
707 // Reuse a free connection for the same wiki
708 $conn = $this->mConns
['foreignFree'][$i][$wiki];
709 unset( $this->mConns
['foreignFree'][$i][$wiki] );
710 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
711 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
712 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
713 // Reuse a connection from another wiki
714 $conn = reset( $this->mConns
['foreignFree'][$i] );
715 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
717 // The empty string as a DB name means "don't care".
718 // DatabaseMysqlBase::open() already handle this on connection.
719 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
720 $this->mLastError
= "Error selecting database $dbName on server " .
721 $conn->getServer() . " from client host " . wfHostname() . "\n";
722 $this->mErrorConnection
= $conn;
725 $conn->tablePrefix( $prefix );
726 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
727 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
728 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
731 // Open a new connection
732 $server = $this->mServers
[$i];
733 $server['serverIndex'] = $i;
734 $server['foreignPoolRefCount'] = 0;
735 $server['foreign'] = true;
736 $conn = $this->reallyOpenConnection( $server, $dbName );
737 if ( !$conn->isOpen() ) {
738 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
739 $this->mErrorConnection
= $conn;
742 $conn->tablePrefix( $prefix );
743 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
744 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
748 // Increment reference count
750 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
751 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
758 * Test if the specified index represents an open connection
760 * @param int $index Server index
764 private function isOpen( $index ) {
765 if ( !is_integer( $index ) ) {
769 return (bool)$this->getAnyOpenConnection( $index );
773 * Really opens a connection. Uncached.
774 * Returns a Database object whether or not the connection was successful.
777 * @param array $server
778 * @param bool $dbNameOverride
779 * @throws MWException
780 * @return DatabaseBase
782 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
783 if ( !is_array( $server ) ) {
784 throw new MWException( 'You must update your load-balancing configuration. ' .
785 'See DefaultSettings.php entry for $wgDBservers.' );
788 if ( $dbNameOverride !== false ) {
789 $server['dbname'] = $dbNameOverride;
792 // Log when many connection are made on requests
793 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
794 $masterAddr = $this->getServerName( 0 );
795 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
796 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
797 wfBacktrace( true ) );
802 $db = DatabaseBase
::factory( $server['type'], $server );
803 } catch ( DBConnectionError
$e ) {
804 // FIXME: This is probably the ugliest thing I have ever done to
805 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
809 $db->setLBInfo( $server );
810 if ( isset( $server['fakeSlaveLag'] ) ) {
811 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
813 if ( isset( $server['fakeMaster'] ) ) {
814 $db->setFakeMaster( true );
821 * @throws DBConnectionError
824 private function reportConnectionError() {
825 $conn = $this->mErrorConnection
; // The connection which caused the error
827 'method' => __METHOD__
,
828 'last_error' => $this->mLastError
,
831 if ( !is_object( $conn ) ) {
832 // No last connection, probably due to all servers being too busy
834 "LB failure with no last connection. Connection error: {last_error}",
838 // If all servers were busy, mLastError will contain something sensible
839 throw new DBConnectionError( null, $this->mLastError
);
841 $context['db_server'] = $conn->getProperty( 'mServer' );
843 "Connection error: {last_error} ({db_server})",
846 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" ); // throws DBConnectionError
849 return false; /* not reached */
856 public function getWriterIndex() {
861 * Returns true if the specified index is a valid server index
866 public function haveIndex( $i ) {
867 return array_key_exists( $i, $this->mServers
);
871 * Returns true if the specified index is valid and has non-zero load
876 public function isNonZeroLoad( $i ) {
877 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
881 * Get the number of defined servers (not the number of open connections)
885 public function getServerCount() {
886 return count( $this->mServers
);
890 * Get the host name or IP address of the server with the specified index
891 * Prefer a readable name if available.
895 public function getServerName( $i ) {
896 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
897 $name = $this->mServers
[$i]['hostName'];
898 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
899 $name = $this->mServers
[$i]['host'];
904 return ( $name != '' ) ?
$name : 'localhost';
908 * Return the server info structure for a given index, or false if the index is invalid.
912 public function getServerInfo( $i ) {
913 if ( isset( $this->mServers
[$i] ) ) {
914 return $this->mServers
[$i];
921 * Sets the server info structure for the given index. Entry at index $i
922 * is created if it doesn't exist
924 * @param array $serverInfo
926 public function setServerInfo( $i, array $serverInfo ) {
927 $this->mServers
[$i] = $serverInfo;
931 * Get the current master position for chronology control purposes
934 public function getMasterPos() {
935 # If this entire request was served from a slave without opening a connection to the
936 # master (however unlikely that may be), then we can fetch the position from the slave.
937 $masterConn = $this->getAnyOpenConnection( 0 );
938 if ( !$masterConn ) {
939 $serverCount = count( $this->mServers
);
940 for ( $i = 1; $i < $serverCount; $i++
) {
941 $conn = $this->getAnyOpenConnection( $i );
943 wfDebug( "Master pos fetched from slave\n" );
945 return $conn->getSlavePos();
949 wfDebug( "Master pos fetched from master\n" );
951 return $masterConn->getMasterPos();
958 * Close all open connections
960 public function closeAll() {
961 foreach ( $this->mConns
as $conns2 ) {
962 foreach ( $conns2 as $conns3 ) {
963 /** @var DatabaseBase $conn */
964 foreach ( $conns3 as $conn ) {
969 $this->mConns
= array(
971 'foreignFree' => array(),
972 'foreignUsed' => array(),
974 $this->connsOpened
= 0;
979 * Using this function makes sure the LoadBalancer knows the connection is closed.
980 * If you use $conn->close() directly, the load balancer won't update its state.
981 * @param DatabaseBase $conn
983 public function closeConnection( $conn ) {
985 foreach ( $this->mConns
as $i1 => $conns2 ) {
986 foreach ( $conns2 as $i2 => $conns3 ) {
987 foreach ( $conns3 as $i3 => $candidateConn ) {
988 if ( $conn === $candidateConn ) {
990 unset( $this->mConns
[$i1][$i2][$i3] );
991 --$this->connsOpened
;
1004 * Commit transactions on all open connections
1006 public function commitAll() {
1007 foreach ( $this->mConns
as $conns2 ) {
1008 foreach ( $conns2 as $conns3 ) {
1009 /** @var DatabaseBase[] $conns3 */
1010 foreach ( $conns3 as $conn ) {
1011 if ( $conn->trxLevel() ) {
1012 $conn->commit( __METHOD__
, 'flush' );
1020 * Issue COMMIT only on master, only if queries were done on connection
1022 public function commitMasterChanges() {
1023 $masterIndex = $this->getWriterIndex();
1024 foreach ( $this->mConns
as $conns2 ) {
1025 if ( empty( $conns2[$masterIndex] ) ) {
1028 /** @var DatabaseBase $conn */
1029 foreach ( $conns2[$masterIndex] as $conn ) {
1030 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1031 $conn->commit( __METHOD__
, 'flush' );
1038 * Issue ROLLBACK only on master, only if queries were done on connection
1041 public function rollbackMasterChanges() {
1042 $failedServers = array();
1044 $masterIndex = $this->getWriterIndex();
1045 foreach ( $this->mConns
as $conns2 ) {
1046 if ( empty( $conns2[$masterIndex] ) ) {
1049 /** @var DatabaseBase $conn */
1050 foreach ( $conns2[$masterIndex] as $conn ) {
1051 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1053 $conn->rollback( __METHOD__
, 'flush' );
1054 } catch ( DBError
$e ) {
1055 MWExceptionHandler
::logException( $e );
1056 $failedServers[] = $conn->getServer();
1062 if ( $failedServers ) {
1063 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1064 implode( ', ', array_unique( $failedServers ) ) );
1069 * @return bool Whether a master connection is already open
1072 public function hasMasterConnection() {
1073 return $this->isOpen( $this->getWriterIndex() );
1077 * Determine if there are pending changes in a transaction by this thread
1081 public function hasMasterChanges() {
1082 $masterIndex = $this->getWriterIndex();
1083 foreach ( $this->mConns
as $conns2 ) {
1084 if ( empty( $conns2[$masterIndex] ) ) {
1087 /** @var DatabaseBase $conn */
1088 foreach ( $conns2[$masterIndex] as $conn ) {
1089 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1098 * Get the timestamp of the latest write query done by this thread
1100 * @return float|bool UNIX timestamp or false
1102 public function lastMasterChangeTimestamp() {
1104 $masterIndex = $this->getWriterIndex();
1105 foreach ( $this->mConns
as $conns2 ) {
1106 if ( empty( $conns2[$masterIndex] ) ) {
1109 /** @var DatabaseBase $conn */
1110 foreach ( $conns2[$masterIndex] as $conn ) {
1111 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1118 * Check if this load balancer object had any recent or still
1119 * pending writes issued against it by this PHP thread
1121 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1125 public function hasOrMadeRecentMasterChanges( $age = null ) {
1126 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1128 return ( $this->hasMasterChanges()
1129 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1133 * @param mixed $value
1136 public function waitTimeout( $value = null ) {
1137 return wfSetVar( $this->mWaitTimeout
, $value );
1141 * @return bool Whether the generic connection for reads is highly "lagged"
1143 public function getLaggedSlaveMode() {
1144 # Get a generic reader connection
1145 $this->getConnection( DB_SLAVE
);
1147 return $this->mLaggedSlaveMode
;
1151 * Disables/enables lag checks
1152 * @param null|bool $mode
1155 public function allowLagged( $mode = null ) {
1156 if ( $mode === null ) {
1157 return $this->mAllowLagged
;
1159 $this->mAllowLagged
= $mode;
1161 return $this->mAllowLagged
;
1167 public function pingAll() {
1169 foreach ( $this->mConns
as $conns2 ) {
1170 foreach ( $conns2 as $conns3 ) {
1171 /** @var DatabaseBase[] $conns3 */
1172 foreach ( $conns3 as $conn ) {
1173 if ( !$conn->ping() ) {
1184 * Call a function with each open connection object
1185 * @param callable $callback
1186 * @param array $params
1188 public function forEachOpenConnection( $callback, array $params = array() ) {
1189 foreach ( $this->mConns
as $conns2 ) {
1190 foreach ( $conns2 as $conns3 ) {
1191 foreach ( $conns3 as $conn ) {
1192 $mergedParams = array_merge( array( $conn ), $params );
1193 call_user_func_array( $callback, $mergedParams );
1200 * Get the hostname and lag time of the most-lagged slave
1202 * This is useful for maintenance scripts that need to throttle their updates.
1203 * May attempt to open connections to slaves on the default DB. If there is
1204 * no lag, the maximum lag will be reported as -1.
1206 * @param bool|string $wiki Wiki ID, or false for the default database
1207 * @return array ( host, max lag, index of max lagged host )
1209 public function getMaxLag( $wiki = false ) {
1214 if ( $this->getServerCount() <= 1 ) {
1215 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1218 $lagTimes = $this->getLagTimes( $wiki );
1219 foreach ( $lagTimes as $i => $lag ) {
1220 if ( $lag > $maxLag ) {
1222 $host = $this->mServers
[$i]['host'];
1227 return array( $host, $maxLag, $maxIndex );
1231 * Get lag time for each server
1233 * Results are cached for a short time in memcached/process cache
1235 * @param string|bool $wiki
1236 * @return int[] Map of (server index => seconds)
1238 public function getLagTimes( $wiki = false ) {
1239 if ( $this->getServerCount() <= 1 ) {
1240 return array( 0 => 0 ); // no replication = no lag
1243 if ( $this->mProcCache
->has( 'slave_lag', 'times', 1 ) ) {
1244 return $this->mProcCache
->get( 'slave_lag', 'times' );
1247 # Send the request to the load monitor
1248 $times = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1250 $this->mProcCache
->set( 'slave_lag', 'times', $times );
1256 * Get the lag in seconds for a given connection, or zero if this load
1257 * balancer does not have replication enabled.
1259 * This should be used in preference to Database::getLag() in cases where
1260 * replication may not be in use, since there is no way to determine if
1261 * replication is in use at the connection level without running
1262 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1263 * function instead of Database::getLag() avoids a fatal error in this
1264 * case on many installations.
1266 * @param DatabaseBase $conn
1269 public function safeGetLag( $conn ) {
1270 if ( $this->getServerCount() == 1 ) {
1273 return $conn->getLag();
1278 * Clear the cache for slag lag delay times
1280 public function clearLagTimeCache() {
1281 $this->mProcCache
->clear( 'slave_lag' );