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;
64 /** @var integer Warn when this many connection are held */
65 const CONN_HELD_WARN_THRESHOLD
= 10;
68 * @param array $params Array with keys:
69 * servers Required. Array of server info structures.
70 * loadMonitor Name of a class used to fetch server lag and load.
73 public function __construct( array $params ) {
74 if ( !isset( $params['servers'] ) ) {
75 throw new MWException( __CLASS__
. ': missing servers parameter' );
77 $this->mServers
= $params['servers'];
78 $this->mWaitTimeout
= 10;
80 $this->mReadIndex
= -1;
81 $this->mWriteIndex
= -1;
82 $this->mConns
= array(
84 'foreignUsed' => array(),
85 'foreignFree' => array() );
86 $this->mLoads
= array();
87 $this->mWaitForPos
= false;
88 $this->mLaggedSlaveMode
= false;
89 $this->mErrorConnection
= false;
90 $this->mAllowLagged
= false;
92 if ( isset( $params['loadMonitor'] ) ) {
93 $this->mLoadMonitorClass
= $params['loadMonitor'];
95 $master = reset( $params['servers'] );
96 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
97 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
99 $this->mLoadMonitorClass
= 'LoadMonitorNull';
103 foreach ( $params['servers'] as $i => $server ) {
104 $this->mLoads
[$i] = $server['load'];
105 if ( isset( $server['groupLoads'] ) ) {
106 foreach ( $server['groupLoads'] as $group => $ratio ) {
107 if ( !isset( $this->mGroupLoads
[$group] ) ) {
108 $this->mGroupLoads
[$group] = array();
110 $this->mGroupLoads
[$group][$i] = $ratio;
117 * Get a LoadMonitor instance
119 * @return LoadMonitor
121 private function getLoadMonitor() {
122 if ( !isset( $this->mLoadMonitor
) ) {
123 $class = $this->mLoadMonitorClass
;
124 $this->mLoadMonitor
= new $class( $this );
127 return $this->mLoadMonitor
;
131 * Get or set arbitrary data used by the parent object, usually an LBFactory
135 public function parentInfo( $x = null ) {
136 return wfSetVar( $this->mParentInfo
, $x );
140 * Given an array of non-normalised probabilities, this function will select
141 * an element and return the appropriate key
143 * @deprecated since 1.21, use ArrayUtils::pickRandom()
145 * @param array $weights
146 * @return bool|int|string
148 public function pickRandom( array $weights ) {
149 return ArrayUtils
::pickRandom( $weights );
153 * @param array $loads
154 * @param bool|string $wiki Wiki to get non-lagged for
155 * @param float $maxLag Restrict the maximum allowed lag to this many seconds
156 * @return bool|int|string
158 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = INF
) {
159 $lags = $this->getLagTimes( $wiki );
161 # Unset excessively lagged servers
162 foreach ( $lags as $i => $lag ) {
164 $maxServerLag = $maxLag;
165 if ( isset( $this->mServers
[$i]['max lag'] ) ) {
166 $maxServerLag = min( $maxServerLag, $this->mServers
[$i]['max lag'] );
168 if ( $lag === false ) {
169 wfDebugLog( 'replication', "Server #$i is not replicating" );
171 } elseif ( $lag > $maxServerLag ) {
172 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
178 # Find out if all the slaves with non-zero load are lagged
180 foreach ( $loads as $load ) {
184 # No appropriate DB servers except maybe the master and some slaves with zero load
185 # Do NOT use the master
186 # Instead, this function will return false, triggering read-only mode,
187 # and a lagged slave will be used instead.
191 if ( count( $loads ) == 0 ) {
195 # wfDebugLog( 'connect', var_export( $loads, true ) );
197 # Return a random representative of the remainder
198 return ArrayUtils
::pickRandom( $loads );
202 * Get the index of the reader connection, which may be a slave
203 * This takes into account load ratios and lag times. It should
204 * always return a consistent index during a given invocation
206 * Side effect: opens connections to databases
207 * @param string|bool $group Query group, or false for the generic reader
208 * @param string|bool $wiki Wiki ID, or false for the current wiki
209 * @throws MWException
210 * @return bool|int|string
212 public function getReaderIndex( $group = false, $wiki = false ) {
215 # @todo FIXME: For now, only go through all this for mysql databases
216 if ( $wgDBtype != 'mysql' ) {
217 return $this->getWriterIndex();
220 if ( count( $this->mServers
) == 1 ) {
221 # Skip the load balancing if there's only one server
223 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
224 # Shortcut if generic reader exists already
225 return $this->mReadIndex
;
228 # Find the relevant load array
229 if ( $group !== false ) {
230 if ( isset( $this->mGroupLoads
[$group] ) ) {
231 $nonErrorLoads = $this->mGroupLoads
[$group];
233 # No loads for this group, return false and the caller can use some other group
234 wfDebug( __METHOD__
. ": no loads for group $group\n" );
239 $nonErrorLoads = $this->mLoads
;
242 if ( !count( $nonErrorLoads ) ) {
243 throw new MWException( "Empty server array given to LoadBalancer" );
246 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
247 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
249 $laggedSlaveMode = false;
251 # No server found yet
254 # First try quickly looking through the available servers for a server that
256 $currentLoads = $nonErrorLoads;
257 while ( count( $currentLoads ) ) {
258 if ( $this->mAllowLagged ||
$laggedSlaveMode ) {
259 $i = ArrayUtils
::pickRandom( $currentLoads );
262 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
263 # ChronologyProtecter causes mWaitForPos to be set via sessions.
264 # This triggers doWait() after connect, so it's especially good to
265 # avoid lagged servers so as to avoid just blocking in that method.
266 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
267 # Aim for <= 1 second of waiting (being too picky can backfire)
268 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago +
1 );
270 if ( $i === false ) {
271 # Any server with less lag than it's 'max lag' param is preferable
272 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
274 if ( $i === false && count( $currentLoads ) != 0 ) {
275 # All slaves lagged. Switch to read-only mode
276 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
277 $i = ArrayUtils
::pickRandom( $currentLoads );
278 $laggedSlaveMode = true;
282 if ( $i === false ) {
283 # pickRandom() returned false
284 # This is permanent and means the configuration or the load monitor
285 # wants us to return false.
286 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
291 $serverName = $this->getServerName( $i );
292 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: $serverName..." );
294 $conn = $this->openConnection( $i, $wiki );
296 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
297 unset( $nonErrorLoads[$i] );
298 unset( $currentLoads[$i] );
303 // Decrement reference counter, we are finished with this connection.
304 // It will be incremented for the caller later.
305 if ( $wiki !== false ) {
306 $this->reuseConnection( $conn );
313 # If all servers were down, quit now
314 if ( !count( $nonErrorLoads ) ) {
315 wfDebugLog( 'connect', "All servers down" );
318 if ( $i !== false ) {
319 # Slave connection successful
320 # Wait for the session master pos for a short time
321 if ( $this->mWaitForPos
&& $i > 0 ) {
322 if ( !$this->doWait( $i ) ) {
323 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
326 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
327 $this->mReadIndex
= $i;
328 # Record if the generic reader index is in "lagged slave" mode
329 if ( $laggedSlaveMode ) {
330 $this->mLaggedSlaveMode
= true;
333 $serverName = $this->getServerName( $i );
334 wfDebug( __METHOD__
. ": using server $serverName for group '$group'\n" );
341 * Set the master wait position
342 * If a DB_SLAVE connection has been opened already, waits
343 * Otherwise sets a variable telling it to wait if such a connection is opened
344 * @param DBMasterPos $pos
346 public function waitFor( $pos ) {
347 $this->mWaitForPos
= $pos;
348 $i = $this->mReadIndex
;
351 if ( !$this->doWait( $i ) ) {
352 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
353 $this->mLaggedSlaveMode
= true;
359 * Set the master wait position and wait for a "generic" slave to catch up to it
361 * This can be used a faster proxy for waitForAll()
363 * @param DBMasterPos $pos
364 * @param int $timeout Max seconds to wait; default is mWaitTimeout
365 * @return bool Success (able to connect and no timeouts reached)
368 public function waitForOne( $pos, $timeout = null ) {
369 $this->mWaitForPos
= $pos;
371 $i = $this->mReadIndex
;
373 // Pick a generic slave if there isn't one yet
374 $readLoads = $this->mLoads
;
375 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
376 $readLoads = array_filter( $readLoads ); // with non-zero load
377 $i = ArrayUtils
::pickRandom( $readLoads );
381 $ok = $this->doWait( $i, true, $timeout );
383 $ok = true; // no applicable loads
390 * Set the master wait position and wait for ALL slaves to catch up to it
391 * @param DBMasterPos $pos
392 * @param int $timeout Max seconds to wait; default is mWaitTimeout
393 * @return bool Success (able to connect and no timeouts reached)
395 public function waitForAll( $pos, $timeout = null ) {
396 $this->mWaitForPos
= $pos;
397 $serverCount = count( $this->mServers
);
400 for ( $i = 1; $i < $serverCount; $i++
) {
401 if ( $this->mLoads
[$i] > 0 ) {
402 $ok = $this->doWait( $i, true, $timeout ) && $ok;
410 * Get any open connection to a given server index, local or foreign
411 * Returns false if there is no connection open
414 * @return DatabaseBase|bool False on failure
416 public function getAnyOpenConnection( $i ) {
417 foreach ( $this->mConns
as $conns ) {
418 if ( !empty( $conns[$i] ) ) {
419 return reset( $conns[$i] );
427 * Wait for a given slave to catch up to the master pos stored in $this
428 * @param int $index Server index
429 * @param bool $open Check the server even if a new connection has to be made
430 * @param int $timeout Max seconds to wait; default is mWaitTimeout
433 protected function doWait( $index, $open = false, $timeout = null ) {
434 $close = false; // close the connection afterwards
436 # Find a connection to wait on, creating one if needed and allowed
437 $conn = $this->getAnyOpenConnection( $index );
440 wfDebug( __METHOD__
. ": no connection open\n" );
444 $conn = $this->openConnection( $index, '' );
446 wfDebug( __METHOD__
. ": failed to open connection\n" );
450 // Avoid connection spam in waitForAll() when connections
451 // are made just for the sake of doing this lag check.
456 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
457 $timeout = $timeout ?
: $this->mWaitTimeout
;
458 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
460 if ( $result == -1 ||
is_null( $result ) ) {
461 # Timed out waiting for slave, use master instead
462 $server = $server = $this->getServerName( $index );
463 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
465 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
468 wfDebug( __METHOD__
. ": Done\n" );
473 $this->closeConnection( $conn );
480 * Get a connection by index
481 * This is the main entry point for this class.
483 * @param int $i Server index
484 * @param array|string|bool $groups Query group(s), or false for the generic reader
485 * @param string|bool $wiki Wiki ID, or false for the current wiki
487 * @throws MWException
488 * @return DatabaseBase
490 public function getConnection( $i, $groups = array(), $wiki = false ) {
491 if ( $i === null ||
$i === false ) {
492 throw new MWException( 'Attempt to call ' . __METHOD__
.
493 ' with invalid server index' );
496 if ( $wiki === wfWikiID() ) {
500 $groups = ( $groups === false ||
$groups === array() )
501 ?
array( false ) // check one "group": the generic pool
504 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
505 $oldConnsOpened = $this->connsOpened
; // connections open now
507 if ( $i == DB_MASTER
) {
508 $i = $this->getWriterIndex();
510 # Try to find an available server in any the query groups (in order)
511 foreach ( $groups as $group ) {
512 $groupIndex = $this->getReaderIndex( $group, $wiki );
513 if ( $groupIndex !== false ) {
520 # Operation-based index
521 if ( $i == DB_SLAVE
) {
522 $this->mLastError
= 'Unknown error'; // reset error string
523 # Try the general server pool if $groups are unavailable.
524 $i = in_array( false, $groups, true )
525 ?
false // don't bother with this if that is what was tried above
526 : $this->getReaderIndex( false, $wiki );
527 # Couldn't find a working server in getReaderIndex()?
528 if ( $i === false ) {
529 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
531 return $this->reportConnectionError();
535 # Now we have an explicit index into the servers array
536 $conn = $this->openConnection( $i, $wiki );
538 return $this->reportConnectionError();
541 # Profile any new connections that happen
542 if ( $this->connsOpened
> $oldConnsOpened ) {
543 $host = $conn->getServer();
544 $dbname = $conn->getDBname();
545 $trxProf = Profiler
::instance()->getTransactionProfiler();
546 $trxProf->recordConnection( $host, $dbname, $masterOnly );
549 # Make master connections read only if in lagged slave mode
550 if ( $masterOnly && $this->getServerCount() > 1 && $this->getLaggedSlaveMode() ) {
551 $conn->setLBInfo( 'readOnlyReason',
552 'The database has been automatically locked ' .
553 'while the slave database servers catch up to the master'
561 * Mark a foreign connection as being available for reuse under a different
562 * DB name or prefix. This mechanism is reference-counted, and must be called
563 * the same number of times as getConnection() to work.
565 * @param DatabaseBase $conn
566 * @throws MWException
568 public function reuseConnection( $conn ) {
569 $serverIndex = $conn->getLBInfo( 'serverIndex' );
570 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
571 if ( $serverIndex === null ||
$refCount === null ) {
572 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
575 * This can happen in code like:
576 * foreach ( $dbs as $db ) {
577 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
579 * $lb->reuseConnection( $conn );
581 * When a connection to the local DB is opened in this way, reuseConnection()
588 $dbName = $conn->getDBname();
589 $prefix = $conn->tablePrefix();
590 if ( strval( $prefix ) !== '' ) {
591 $wiki = "$dbName-$prefix";
595 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
596 throw new MWException( __METHOD__
. ": connection not found, has " .
597 "the connection been freed already?" );
599 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
600 if ( $refCount <= 0 ) {
601 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
602 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
603 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
605 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
610 * Get a database connection handle reference
612 * The handle's methods wrap simply wrap those of a DatabaseBase handle
614 * @see LoadBalancer::getConnection() for parameter information
617 * @param array|string|bool $groups Query group(s), or false for the generic reader
618 * @param string|bool $wiki Wiki ID, or false for the current wiki
621 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
622 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
626 * Get a database connection handle reference without connecting yet
628 * The handle's methods wrap simply wrap those of a DatabaseBase handle
630 * @see LoadBalancer::getConnection() for parameter information
633 * @param array|string|bool $groups Query group(s), or false for the generic reader
634 * @param string|bool $wiki Wiki ID, or false for the current wiki
637 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
638 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
642 * Open a connection to the server given by the specified index
643 * Index must be an actual index into the array.
644 * If the server is already open, returns it.
646 * On error, returns false, and the connection which caused the
647 * error will be available via $this->mErrorConnection.
649 * @param int $i Server index
650 * @param string|bool $wiki Wiki ID, or false for the current wiki
651 * @return DatabaseBase
655 public function openConnection( $i, $wiki = false ) {
656 if ( $wiki !== false ) {
657 $conn = $this->openForeignConnection( $i, $wiki );
658 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
659 $conn = $this->mConns
['local'][$i][0];
661 $server = $this->mServers
[$i];
662 $server['serverIndex'] = $i;
663 $conn = $this->reallyOpenConnection( $server, false );
664 $serverName = $this->getServerName( $i );
665 if ( $conn->isOpen() ) {
666 wfDebug( "Connected to database $i at $serverName\n" );
667 $this->mConns
['local'][$i][0] = $conn;
669 wfDebug( "Failed to connect to database $i at $serverName\n" );
670 $this->mErrorConnection
= $conn;
675 if ( $conn && !$conn->isOpen() ) {
676 // Connection was made but later unrecoverably lost for some reason.
677 // Do not return a handle that will just throw exceptions on use,
678 // but let the calling code (e.g. getReaderIndex) try another server.
679 // See DatabaseMyslBase::ping() for how this can happen.
680 $this->mErrorConnection
= $conn;
688 * Open a connection to a foreign DB, or return one if it is already open.
690 * Increments a reference count on the returned connection which locks the
691 * connection to the requested wiki. This reference count can be
692 * decremented by calling reuseConnection().
694 * If a connection is open to the appropriate server already, but with the wrong
695 * database, it will be switched to the right database and returned, as long as
696 * it has been freed first with reuseConnection().
698 * On error, returns false, and the connection which caused the
699 * error will be available via $this->mErrorConnection.
701 * @param int $i Server index
702 * @param string $wiki Wiki ID to open
703 * @return DatabaseBase
705 private function openForeignConnection( $i, $wiki ) {
706 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
707 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
708 // Reuse an already-used connection
709 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
710 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
711 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
712 // Reuse a free connection for the same wiki
713 $conn = $this->mConns
['foreignFree'][$i][$wiki];
714 unset( $this->mConns
['foreignFree'][$i][$wiki] );
715 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
716 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
717 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
718 // Reuse a connection from another wiki
719 $conn = reset( $this->mConns
['foreignFree'][$i] );
720 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
722 // The empty string as a DB name means "don't care".
723 // DatabaseMysqlBase::open() already handle this on connection.
724 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
725 $this->mLastError
= "Error selecting database $dbName on server " .
726 $conn->getServer() . " from client host " . wfHostname() . "\n";
727 $this->mErrorConnection
= $conn;
730 $conn->tablePrefix( $prefix );
731 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
732 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
733 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
736 // Open a new connection
737 $server = $this->mServers
[$i];
738 $server['serverIndex'] = $i;
739 $server['foreignPoolRefCount'] = 0;
740 $server['foreign'] = true;
741 $conn = $this->reallyOpenConnection( $server, $dbName );
742 if ( !$conn->isOpen() ) {
743 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
744 $this->mErrorConnection
= $conn;
747 $conn->tablePrefix( $prefix );
748 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
749 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
753 // Increment reference count
755 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
756 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
763 * Test if the specified index represents an open connection
765 * @param int $index Server index
769 private function isOpen( $index ) {
770 if ( !is_integer( $index ) ) {
774 return (bool)$this->getAnyOpenConnection( $index );
778 * Really opens a connection. Uncached.
779 * Returns a Database object whether or not the connection was successful.
782 * @param array $server
783 * @param bool $dbNameOverride
784 * @throws MWException
785 * @return DatabaseBase
787 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
788 if ( !is_array( $server ) ) {
789 throw new MWException( 'You must update your load-balancing configuration. ' .
790 'See DefaultSettings.php entry for $wgDBservers.' );
793 if ( $dbNameOverride !== false ) {
794 $server['dbname'] = $dbNameOverride;
797 // Log when many connection are made on requests
798 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
799 $masterAddr = $this->getServerName( 0 );
800 wfDebugLog( 'DBPerformance', __METHOD__
. ": " .
801 "{$this->connsOpened}+ connections made (master=$masterAddr)\n" .
802 wfBacktrace( true ) );
807 $db = DatabaseBase
::factory( $server['type'], $server );
808 } catch ( DBConnectionError
$e ) {
809 // FIXME: This is probably the ugliest thing I have ever done to
810 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
814 $db->setLBInfo( $server );
820 * @throws DBConnectionError
823 private function reportConnectionError() {
824 $conn = $this->mErrorConnection
; // The connection which caused the error
826 'method' => __METHOD__
,
827 'last_error' => $this->mLastError
,
830 if ( !is_object( $conn ) ) {
831 // No last connection, probably due to all servers being too busy
833 "LB failure with no last connection. Connection error: {last_error}",
837 // If all servers were busy, mLastError will contain something sensible
838 throw new DBConnectionError( null, $this->mLastError
);
840 $context['db_server'] = $conn->getProperty( 'mServer' );
842 "Connection error: {last_error} ({db_server})",
846 // throws DBConnectionError
847 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
850 return false; /* not reached */
857 public function getWriterIndex() {
862 * Returns true if the specified index is a valid server index
867 public function haveIndex( $i ) {
868 return array_key_exists( $i, $this->mServers
);
872 * Returns true if the specified index is valid and has non-zero load
877 public function isNonZeroLoad( $i ) {
878 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
882 * Get the number of defined servers (not the number of open connections)
886 public function getServerCount() {
887 return count( $this->mServers
);
891 * Get the host name or IP address of the server with the specified index
892 * Prefer a readable name if available.
896 public function getServerName( $i ) {
897 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
898 $name = $this->mServers
[$i]['hostName'];
899 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
900 $name = $this->mServers
[$i]['host'];
905 return ( $name != '' ) ?
$name : 'localhost';
909 * Return the server info structure for a given index, or false if the index is invalid.
913 public function getServerInfo( $i ) {
914 if ( isset( $this->mServers
[$i] ) ) {
915 return $this->mServers
[$i];
922 * Sets the server info structure for the given index. Entry at index $i
923 * is created if it doesn't exist
925 * @param array $serverInfo
927 public function setServerInfo( $i, array $serverInfo ) {
928 $this->mServers
[$i] = $serverInfo;
932 * Get the current master position for chronology control purposes
935 public function getMasterPos() {
936 # If this entire request was served from a slave without opening a connection to the
937 # master (however unlikely that may be), then we can fetch the position from the slave.
938 $masterConn = $this->getAnyOpenConnection( 0 );
939 if ( !$masterConn ) {
940 $serverCount = count( $this->mServers
);
941 for ( $i = 1; $i < $serverCount; $i++
) {
942 $conn = $this->getAnyOpenConnection( $i );
944 wfDebug( "Master pos fetched from slave\n" );
946 return $conn->getSlavePos();
950 wfDebug( "Master pos fetched from master\n" );
952 return $masterConn->getMasterPos();
959 * Close all open connections
961 public function closeAll() {
962 foreach ( $this->mConns
as $conns2 ) {
963 foreach ( $conns2 as $conns3 ) {
964 /** @var DatabaseBase $conn */
965 foreach ( $conns3 as $conn ) {
970 $this->mConns
= array(
972 'foreignFree' => array(),
973 'foreignUsed' => array(),
975 $this->connsOpened
= 0;
980 * Using this function makes sure the LoadBalancer knows the connection is closed.
981 * If you use $conn->close() directly, the load balancer won't update its state.
982 * @param DatabaseBase $conn
984 public function closeConnection( $conn ) {
986 foreach ( $this->mConns
as $i1 => $conns2 ) {
987 foreach ( $conns2 as $i2 => $conns3 ) {
988 foreach ( $conns3 as $i3 => $candidateConn ) {
989 if ( $conn === $candidateConn ) {
991 unset( $this->mConns
[$i1][$i2][$i3] );
992 --$this->connsOpened
;
1005 * Commit transactions on all open connections
1007 public function commitAll() {
1008 foreach ( $this->mConns
as $conns2 ) {
1009 foreach ( $conns2 as $conns3 ) {
1010 /** @var DatabaseBase[] $conns3 */
1011 foreach ( $conns3 as $conn ) {
1012 if ( $conn->trxLevel() ) {
1013 $conn->commit( __METHOD__
, 'flush' );
1021 * Issue COMMIT only on master, only if queries were done on connection
1023 public function commitMasterChanges() {
1024 $masterIndex = $this->getWriterIndex();
1025 foreach ( $this->mConns
as $conns2 ) {
1026 if ( empty( $conns2[$masterIndex] ) ) {
1029 /** @var DatabaseBase $conn */
1030 foreach ( $conns2[$masterIndex] as $conn ) {
1031 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1032 $conn->commit( __METHOD__
, 'flush' );
1039 * Issue ROLLBACK only on master, only if queries were done on connection
1042 public function rollbackMasterChanges() {
1043 $failedServers = array();
1045 $masterIndex = $this->getWriterIndex();
1046 foreach ( $this->mConns
as $conns2 ) {
1047 if ( empty( $conns2[$masterIndex] ) ) {
1050 /** @var DatabaseBase $conn */
1051 foreach ( $conns2[$masterIndex] as $conn ) {
1052 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1054 $conn->rollback( __METHOD__
, 'flush' );
1055 } catch ( DBError
$e ) {
1056 MWExceptionHandler
::logException( $e );
1057 $failedServers[] = $conn->getServer();
1063 if ( $failedServers ) {
1064 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1065 implode( ', ', array_unique( $failedServers ) ) );
1070 * @return bool Whether a master connection is already open
1073 public function hasMasterConnection() {
1074 return $this->isOpen( $this->getWriterIndex() );
1078 * Determine if there are pending changes in a transaction by this thread
1082 public function hasMasterChanges() {
1083 $masterIndex = $this->getWriterIndex();
1084 foreach ( $this->mConns
as $conns2 ) {
1085 if ( empty( $conns2[$masterIndex] ) ) {
1088 /** @var DatabaseBase $conn */
1089 foreach ( $conns2[$masterIndex] as $conn ) {
1090 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1099 * Get the timestamp of the latest write query done by this thread
1101 * @return float|bool UNIX timestamp or false
1103 public function lastMasterChangeTimestamp() {
1105 $masterIndex = $this->getWriterIndex();
1106 foreach ( $this->mConns
as $conns2 ) {
1107 if ( empty( $conns2[$masterIndex] ) ) {
1110 /** @var DatabaseBase $conn */
1111 foreach ( $conns2[$masterIndex] as $conn ) {
1112 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1119 * Check if this load balancer object had any recent or still
1120 * pending writes issued against it by this PHP thread
1122 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1126 public function hasOrMadeRecentMasterChanges( $age = null ) {
1127 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1129 return ( $this->hasMasterChanges()
1130 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1134 * @param mixed $value
1137 public function waitTimeout( $value = null ) {
1138 return wfSetVar( $this->mWaitTimeout
, $value );
1142 * @note This method will trigger a DB connection if not yet done
1143 * @return bool Whether the generic connection for reads is highly "lagged"
1145 public function getLaggedSlaveMode() {
1146 # Get a generic reader connection
1147 $this->getConnection( DB_SLAVE
);
1149 return $this->mLaggedSlaveMode
;
1153 * @note This method will never cause a new DB connection
1154 * @return bool Whether any generic connection used for reads was highly "lagged"
1157 public function laggedSlaveUsed() {
1158 return $this->mLaggedSlaveMode
;
1162 * Disables/enables lag checks
1163 * @param null|bool $mode
1166 public function allowLagged( $mode = null ) {
1167 if ( $mode === null ) {
1168 return $this->mAllowLagged
;
1170 $this->mAllowLagged
= $mode;
1172 return $this->mAllowLagged
;
1178 public function pingAll() {
1180 foreach ( $this->mConns
as $conns2 ) {
1181 foreach ( $conns2 as $conns3 ) {
1182 /** @var DatabaseBase[] $conns3 */
1183 foreach ( $conns3 as $conn ) {
1184 if ( !$conn->ping() ) {
1195 * Call a function with each open connection object
1196 * @param callable $callback
1197 * @param array $params
1199 public function forEachOpenConnection( $callback, array $params = array() ) {
1200 foreach ( $this->mConns
as $conns2 ) {
1201 foreach ( $conns2 as $conns3 ) {
1202 foreach ( $conns3 as $conn ) {
1203 $mergedParams = array_merge( array( $conn ), $params );
1204 call_user_func_array( $callback, $mergedParams );
1211 * Get the hostname and lag time of the most-lagged slave
1213 * This is useful for maintenance scripts that need to throttle their updates.
1214 * May attempt to open connections to slaves on the default DB. If there is
1215 * no lag, the maximum lag will be reported as -1.
1217 * @param bool|string $wiki Wiki ID, or false for the default database
1218 * @return array ( host, max lag, index of max lagged host )
1220 public function getMaxLag( $wiki = false ) {
1225 if ( $this->getServerCount() <= 1 ) {
1226 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1229 $lagTimes = $this->getLagTimes( $wiki );
1230 foreach ( $lagTimes as $i => $lag ) {
1231 if ( $lag > $maxLag ) {
1233 $host = $this->mServers
[$i]['host'];
1238 return array( $host, $maxLag, $maxIndex );
1242 * Get an estimate of replication lag (in seconds) for each server
1244 * Results are cached for a short time in memcached/process cache
1246 * Values may be "false" if replication is too broken to estimate
1248 * @param string|bool $wiki
1249 * @return int[] Map of (server index => float|int|bool)
1251 public function getLagTimes( $wiki = false ) {
1252 if ( $this->getServerCount() <= 1 ) {
1253 return array( 0 => 0 ); // no replication = no lag
1256 # Send the request to the load monitor
1257 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers
), $wiki );
1261 * Get the lag in seconds for a given connection, or zero if this load
1262 * balancer does not have replication enabled.
1264 * This should be used in preference to Database::getLag() in cases where
1265 * replication may not be in use, since there is no way to determine if
1266 * replication is in use at the connection level without running
1267 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1268 * function instead of Database::getLag() avoids a fatal error in this
1269 * case on many installations.
1271 * @param DatabaseBase $conn
1274 public function safeGetLag( $conn ) {
1275 if ( $this->getServerCount() == 1 ) {
1278 return $conn->getLag();
1283 * Clear the cache for slag lag delay times
1285 * This is only used for testing
1287 public function clearLagTimeCache() {
1288 $this->getLoadMonitor()->clearCaches();