3 * Database load balancing.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Database load balancing object
31 private $mServers, $mConns, $mLoads, $mGroupLoads;
32 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
40 * @param array $params with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__
. ': missing servers parameter' );
50 $this->mServers
= $params['servers'];
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout
= $params['waitTimeout'];
55 $this->mWaitTimeout
= 10;
58 $this->mReadIndex
= -1;
59 $this->mWriteIndex
= -1;
60 $this->mConns
= array(
62 'foreignUsed' => array(),
63 'foreignFree' => array() );
64 $this->mLoads
= array();
65 $this->mWaitForPos
= false;
66 $this->mLaggedSlaveMode
= false;
67 $this->mErrorConnection
= false;
68 $this->mAllowLagged
= false;
70 if ( isset( $params['loadMonitor'] ) ) {
71 $this->mLoadMonitorClass
= $params['loadMonitor'];
73 $master = reset( $params['servers'] );
74 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
75 $this->mLoadMonitorClass
= 'LoadMonitor_MySQL';
77 $this->mLoadMonitorClass
= 'LoadMonitor_Null';
81 foreach ( $params['servers'] as $i => $server ) {
82 $this->mLoads
[$i] = $server['load'];
83 if ( isset( $server['groupLoads'] ) ) {
84 foreach ( $server['groupLoads'] as $group => $ratio ) {
85 if ( !isset( $this->mGroupLoads
[$group] ) ) {
86 $this->mGroupLoads
[$group] = array();
88 $this->mGroupLoads
[$group][$i] = $ratio;
95 * Get a LoadMonitor instance
99 function getLoadMonitor() {
100 if ( !isset( $this->mLoadMonitor
) ) {
101 $class = $this->mLoadMonitorClass
;
102 $this->mLoadMonitor
= new $class( $this );
105 return $this->mLoadMonitor
;
109 * Get or set arbitrary data used by the parent object, usually an LBFactory
113 function parentInfo( $x = null ) {
114 return wfSetVar( $this->mParentInfo
, $x );
118 * Given an array of non-normalised probabilities, this function will select
119 * an element and return the appropriate key
121 * @deprecated since 1.21, use ArrayUtils::pickRandom()
123 * @param $weights array
125 * @return bool|int|string
127 function pickRandom( $weights ) {
128 return ArrayUtils
::pickRandom( $weights );
132 * @param $loads array
134 * @return bool|int|string
136 function getRandomNonLagged( $loads, $wiki = false ) {
137 # Unset excessively lagged servers
138 $lags = $this->getLagTimes( $wiki );
139 foreach ( $lags as $i => $lag ) {
141 if ( $lag === false ) {
142 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
144 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
145 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
151 # Find out if all the slaves with non-zero load are lagged
153 foreach ( $loads as $load ) {
157 # No appropriate DB servers except maybe the master and some slaves with zero load
158 # Do NOT use the master
159 # Instead, this function will return false, triggering read-only mode,
160 # and a lagged slave will be used instead.
164 if ( count( $loads ) == 0 ) {
168 #wfDebugLog( 'connect', var_export( $loads, true ) );
170 # Return a random representative of the remainder
171 return ArrayUtils
::pickRandom( $loads );
175 * Get the index of the reader connection, which may be a slave
176 * This takes into account load ratios and lag times. It should
177 * always return a consistent index during a given invocation
179 * Side effect: opens connections to databases
182 * @throws MWException
183 * @return bool|int|string
185 function getReaderIndex( $group = false, $wiki = false ) {
186 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
188 # @todo FIXME: For now, only go through all this for mysql databases
189 if ( $wgDBtype != 'mysql' ) {
190 return $this->getWriterIndex();
193 if ( count( $this->mServers
) == 1 ) {
194 # Skip the load balancing if there's only one server
196 } elseif ( $group === false and $this->mReadIndex
>= 0 ) {
197 # Shortcut if generic reader exists already
198 return $this->mReadIndex
;
201 wfProfileIn( __METHOD__
);
205 # convert from seconds to microseconds
206 $timeout = $wgDBClusterTimeout * 1e6
;
208 # Find the relevant load array
209 if ( $group !== false ) {
210 if ( isset( $this->mGroupLoads
[$group] ) ) {
211 $nonErrorLoads = $this->mGroupLoads
[$group];
213 # No loads for this group, return false and the caller can use some other group
214 wfDebug( __METHOD__
. ": no loads for group $group\n" );
215 wfProfileOut( __METHOD__
);
220 $nonErrorLoads = $this->mLoads
;
223 if ( !$nonErrorLoads ) {
224 wfProfileOut( __METHOD__
);
225 throw new MWException( "Empty server array given to LoadBalancer" );
228 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
229 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
231 $laggedSlaveMode = false;
233 # First try quickly looking through the available servers for a server that
236 $totalThreadsConnected = 0;
237 $overloadedServers = 0;
238 $currentLoads = $nonErrorLoads;
239 while ( count( $currentLoads ) ) {
240 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
241 $i = ArrayUtils
::pickRandom( $currentLoads );
243 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
244 if ( $i === false && count( $currentLoads ) != 0 ) {
245 # All slaves lagged. Switch to read-only mode
246 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
247 $wgReadOnly = 'The database has been automatically locked ' .
248 'while the slave database servers catch up to the master';
249 $i = ArrayUtils
::pickRandom( $currentLoads );
250 $laggedSlaveMode = true;
254 if ( $i === false ) {
255 # pickRandom() returned false
256 # This is permanent and means the configuration or the load monitor
257 # wants us to return false.
258 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false\n" );
259 wfProfileOut( __METHOD__
);
264 wfDebugLog( 'connect', __METHOD__
. ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
265 $conn = $this->openConnection( $i, $wiki );
268 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki\n" );
269 unset( $nonErrorLoads[$i] );
270 unset( $currentLoads[$i] );
274 // Perform post-connection backoff
275 $threshold = isset( $this->mServers
[$i]['max threads'] )
276 ?
$this->mServers
[$i]['max threads'] : false;
277 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
279 // Decrement reference counter, we are finished with this connection.
280 // It will be incremented for the caller later.
281 if ( $wiki !== false ) {
282 $this->reuseConnection( $conn );
286 # Post-connection overload, don't use this server for now
287 $totalThreadsConnected +
= $backoff;
288 $overloadedServers++
;
289 unset( $currentLoads[$i] );
296 # No server found yet
299 # If all servers were down, quit now
300 if ( !count( $nonErrorLoads ) ) {
301 wfDebugLog( 'connect', "All servers down\n" );
305 # Some servers must have been overloaded
306 if ( $overloadedServers == 0 ) {
307 throw new MWException( __METHOD__
. ": unexpectedly found no overloaded servers" );
309 # Back off for a while
310 # Scale the sleep time by the number of connected threads, to produce a
311 # roughly constant global poll rate
312 $avgThreads = $totalThreadsConnected / $overloadedServers;
313 $totalElapsed +
= $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
314 } while ( $totalElapsed < $timeout );
316 if ( $totalElapsed >= $timeout ) {
317 wfDebugLog( 'connect', "All servers busy\n" );
318 $this->mErrorConnection
= false;
319 $this->mLastError
= 'All servers busy';
322 if ( $i !== false ) {
323 # Slave connection successful
324 # Wait for the session master pos for a short time
325 if ( $this->mWaitForPos
&& $i > 0 ) {
326 if ( !$this->doWait( $i ) ) {
327 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
330 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $i !== false ) {
331 $this->mReadIndex
= $i;
334 wfProfileOut( __METHOD__
);
340 * Wait for a specified number of microseconds, and return the period waited
344 function sleep( $t ) {
345 wfProfileIn( __METHOD__
);
346 wfDebug( __METHOD__
. ": waiting $t us\n" );
348 wfProfileOut( __METHOD__
);
354 * Set the master wait position
355 * If a DB_SLAVE connection has been opened already, waits
356 * Otherwise sets a variable telling it to wait if such a connection is opened
357 * @param $pos DBMasterPos
359 public function waitFor( $pos ) {
360 wfProfileIn( __METHOD__
);
361 $this->mWaitForPos
= $pos;
362 $i = $this->mReadIndex
;
365 if ( !$this->doWait( $i ) ) {
366 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
367 $this->mLaggedSlaveMode
= true;
370 wfProfileOut( __METHOD__
);
374 * Set the master wait position and wait for ALL slaves to catch up to it
375 * @param $pos DBMasterPos
377 public function waitForAll( $pos ) {
378 wfProfileIn( __METHOD__
);
379 $this->mWaitForPos
= $pos;
380 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
381 if ( $this->mLoads
[$i] > 0 ) {
382 $this->doWait( $i, true );
385 wfProfileOut( __METHOD__
);
389 * Get any open connection to a given server index, local or foreign
390 * Returns false if there is no connection open
393 * @return DatabaseBase|bool False on failure
395 function getAnyOpenConnection( $i ) {
396 foreach ( $this->mConns
as $conns ) {
397 if ( !empty( $conns[$i] ) ) {
398 return reset( $conns[$i] );
406 * Wait for a given slave to catch up to the master pos stored in $this
411 protected function doWait( $index, $open = false ) {
412 # Find a connection to wait on
413 $conn = $this->getAnyOpenConnection( $index );
416 wfDebug( __METHOD__
. ": no connection open\n" );
420 $conn = $this->openConnection( $index, '' );
422 wfDebug( __METHOD__
. ": failed to open connection\n" );
429 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
430 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
432 if ( $result == -1 ||
is_null( $result ) ) {
433 # Timed out waiting for slave, use master instead
434 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
438 wfDebug( __METHOD__
. ": Done\n" );
445 * Get a connection by index
446 * This is the main entry point for this class.
448 * @param $i Integer: server index
449 * @param array $groups query groups
450 * @param bool|string $wiki Wiki ID
452 * @throws MWException
453 * @return DatabaseBase
455 public function &getConnection( $i, $groups = array(), $wiki = false ) {
456 wfProfileIn( __METHOD__
);
458 if ( $i == DB_LAST
) {
459 wfProfileOut( __METHOD__
);
460 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with deprecated server index DB_LAST' );
461 } elseif ( $i === null ||
$i === false ) {
462 wfProfileOut( __METHOD__
);
463 throw new MWException( 'Attempt to call ' . __METHOD__
. ' with invalid server index' );
466 if ( $wiki === wfWikiID() ) {
471 if ( $i == DB_MASTER
) {
472 $i = $this->getWriterIndex();
473 } elseif ( !is_array( $groups ) ) {
474 $groupIndex = $this->getReaderIndex( $groups, $wiki );
475 if ( $groupIndex !== false ) {
476 $serverName = $this->getServerName( $groupIndex );
477 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
481 foreach ( $groups as $group ) {
482 $groupIndex = $this->getReaderIndex( $group, $wiki );
483 if ( $groupIndex !== false ) {
484 $serverName = $this->getServerName( $groupIndex );
485 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
492 # Operation-based index
493 if ( $i == DB_SLAVE
) {
494 $this->mLastError
= 'Unknown error'; // reset error string
495 $i = $this->getReaderIndex( false, $wiki );
496 # Couldn't find a working server in getReaderIndex()?
497 if ( $i === false ) {
498 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
499 wfProfileOut( __METHOD__
);
501 return $this->reportConnectionError();
505 # Now we have an explicit index into the servers array
506 $conn = $this->openConnection( $i, $wiki );
508 wfProfileOut( __METHOD__
);
510 return $this->reportConnectionError();
513 wfProfileOut( __METHOD__
);
519 * Mark a foreign connection as being available for reuse under a different
520 * DB name or prefix. This mechanism is reference-counted, and must be called
521 * the same number of times as getConnection() to work.
523 * @param DatabaseBase $conn
524 * @throws MWException
526 public function reuseConnection( $conn ) {
527 $serverIndex = $conn->getLBInfo( 'serverIndex' );
528 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
529 $dbName = $conn->getDBname();
530 $prefix = $conn->tablePrefix();
531 if ( strval( $prefix ) !== '' ) {
532 $wiki = "$dbName-$prefix";
536 if ( $serverIndex === null ||
$refCount === null ) {
537 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
540 * This can happen in code like:
541 * foreach ( $dbs as $db ) {
542 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
544 * $lb->reuseConnection( $conn );
546 * When a connection to the local DB is opened in this way, reuseConnection()
552 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
553 throw new MWException( __METHOD__
. ": connection not found, has the connection been freed already?" );
555 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
556 if ( $refCount <= 0 ) {
557 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
558 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
559 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
561 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
566 * Get a database connection handle reference
568 * The handle's methods wrap simply wrap those of a DatabaseBase handle
570 * @see LoadBalancer::getConnection() for parameter information
573 * @param mixed $groups
574 * @param string $wiki
577 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
578 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
582 * Get a database connection handle reference without connecting yet
584 * The handle's methods wrap simply wrap those of a DatabaseBase handle
586 * @see LoadBalancer::getConnection() for parameter information
589 * @param mixed $groups
590 * @param string $wiki
593 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
594 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
598 * Open a connection to the server given by the specified index
599 * Index must be an actual index into the array.
600 * If the server is already open, returns it.
602 * On error, returns false, and the connection which caused the
603 * error will be available via $this->mErrorConnection.
605 * @param $i Integer server index
606 * @param string $wiki wiki ID to open
607 * @return DatabaseBase
611 function openConnection( $i, $wiki = false ) {
612 wfProfileIn( __METHOD__
);
613 if ( $wiki !== false ) {
614 $conn = $this->openForeignConnection( $i, $wiki );
615 wfProfileOut( __METHOD__
);
619 if ( isset( $this->mConns
['local'][$i][0] ) ) {
620 $conn = $this->mConns
['local'][$i][0];
622 $server = $this->mServers
[$i];
623 $server['serverIndex'] = $i;
624 $conn = $this->reallyOpenConnection( $server, false );
625 if ( $conn->isOpen() ) {
626 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
627 $this->mConns
['local'][$i][0] = $conn;
629 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
630 $this->mErrorConnection
= $conn;
634 wfProfileOut( __METHOD__
);
640 * Open a connection to a foreign DB, or return one if it is already open.
642 * Increments a reference count on the returned connection which locks the
643 * connection to the requested wiki. This reference count can be
644 * decremented by calling reuseConnection().
646 * If a connection is open to the appropriate server already, but with the wrong
647 * database, it will be switched to the right database and returned, as long as
648 * it has been freed first with reuseConnection().
650 * On error, returns false, and the connection which caused the
651 * error will be available via $this->mErrorConnection.
653 * @param $i Integer: server index
654 * @param string $wiki wiki ID to open
655 * @return DatabaseBase
657 function openForeignConnection( $i, $wiki ) {
658 wfProfileIn( __METHOD__
);
659 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
660 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
661 // Reuse an already-used connection
662 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
663 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
664 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
665 // Reuse a free connection for the same wiki
666 $conn = $this->mConns
['foreignFree'][$i][$wiki];
667 unset( $this->mConns
['foreignFree'][$i][$wiki] );
668 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
669 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
670 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
671 // Reuse a connection from another wiki
672 $conn = reset( $this->mConns
['foreignFree'][$i] );
673 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
675 if ( !$conn->selectDB( $dbName ) ) {
676 $this->mLastError
= "Error selecting database $dbName on server " .
677 $conn->getServer() . " from client host " . wfHostname() . "\n";
678 $this->mErrorConnection
= $conn;
681 $conn->tablePrefix( $prefix );
682 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
683 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
684 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
687 // Open a new connection
688 $server = $this->mServers
[$i];
689 $server['serverIndex'] = $i;
690 $server['foreignPoolRefCount'] = 0;
691 $server['foreign'] = true;
692 $conn = $this->reallyOpenConnection( $server, $dbName );
693 if ( !$conn->isOpen() ) {
694 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
695 $this->mErrorConnection
= $conn;
698 $conn->tablePrefix( $prefix );
699 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
700 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
704 // Increment reference count
706 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
707 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
709 wfProfileOut( __METHOD__
);
715 * Test if the specified index represents an open connection
717 * @param $index Integer: server index
721 function isOpen( $index ) {
722 if ( !is_integer( $index ) ) {
726 return (bool)$this->getAnyOpenConnection( $index );
730 * Really opens a connection. Uncached.
731 * Returns a Database object whether or not the connection was successful.
735 * @param $dbNameOverride bool
736 * @throws MWException
737 * @return DatabaseBase
739 function reallyOpenConnection( $server, $dbNameOverride = false ) {
740 if ( !is_array( $server ) ) {
741 throw new MWException( 'You must update your load-balancing configuration. ' .
742 'See DefaultSettings.php entry for $wgDBservers.' );
745 if ( $dbNameOverride !== false ) {
746 $server['dbname'] = $dbNameOverride;
751 $db = DatabaseBase
::factory( $server['type'], $server );
752 } catch ( DBConnectionError
$e ) {
753 // FIXME: This is probably the ugliest thing I have ever done to
754 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
758 $db->setLBInfo( $server );
759 if ( isset( $server['fakeSlaveLag'] ) ) {
760 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
762 if ( isset( $server['fakeMaster'] ) ) {
763 $db->setFakeMaster( true );
770 * @throws DBConnectionError
773 private function reportConnectionError() {
774 $conn = $this->mErrorConnection
; // The connection which caused the error
776 if ( !is_object( $conn ) ) {
777 // No last connection, probably due to all servers being too busy
778 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
780 // If all servers were busy, mLastError will contain something sensible
781 throw new DBConnectionError( null, $this->mLastError
);
783 $server = $conn->getProperty( 'mServer' );
784 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
785 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
788 return false; /* not reached */
794 function getWriterIndex() {
799 * Returns true if the specified index is a valid server index
804 function haveIndex( $i ) {
805 return array_key_exists( $i, $this->mServers
);
809 * Returns true if the specified index is valid and has non-zero load
814 function isNonZeroLoad( $i ) {
815 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
819 * Get the number of defined servers (not the number of open connections)
823 function getServerCount() {
824 return count( $this->mServers
);
828 * Get the host name or IP address of the server with the specified index
829 * Prefer a readable name if available.
833 function getServerName( $i ) {
834 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
835 return $this->mServers
[$i]['hostName'];
836 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
837 return $this->mServers
[$i]['host'];
844 * Return the server info structure for a given index, or false if the index is invalid.
848 function getServerInfo( $i ) {
849 if ( isset( $this->mServers
[$i] ) ) {
850 return $this->mServers
[$i];
857 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
861 function setServerInfo( $i, $serverInfo ) {
862 $this->mServers
[$i] = $serverInfo;
866 * Get the current master position for chronology control purposes
869 function getMasterPos() {
870 # If this entire request was served from a slave without opening a connection to the
871 # master (however unlikely that may be), then we can fetch the position from the slave.
872 $masterConn = $this->getAnyOpenConnection( 0 );
873 if ( !$masterConn ) {
874 for ( $i = 1; $i < count( $this->mServers
); $i++
) {
875 $conn = $this->getAnyOpenConnection( $i );
877 wfDebug( "Master pos fetched from slave\n" );
879 return $conn->getSlavePos();
883 wfDebug( "Master pos fetched from master\n" );
885 return $masterConn->getMasterPos();
892 * Close all open connections
894 function closeAll() {
895 foreach ( $this->mConns
as $conns2 ) {
896 foreach ( $conns2 as $conns3 ) {
897 foreach ( $conns3 as $conn ) {
902 $this->mConns
= array(
904 'foreignFree' => array(),
905 'foreignUsed' => array(),
910 * Deprecated function, typo in function name
912 * @deprecated in 1.18
915 function closeConnecton( $conn ) {
916 wfDeprecated( __METHOD__
, '1.18' );
917 $this->closeConnection( $conn );
922 * Using this function makes sure the LoadBalancer knows the connection is closed.
923 * If you use $conn->close() directly, the load balancer won't update its state.
924 * @param $conn DatabaseBase
926 function closeConnection( $conn ) {
928 foreach ( $this->mConns
as $i1 => $conns2 ) {
929 foreach ( $conns2 as $i2 => $conns3 ) {
930 foreach ( $conns3 as $i3 => $candidateConn ) {
931 if ( $conn === $candidateConn ) {
933 unset( $this->mConns
[$i1][$i2][$i3] );
946 * Commit transactions on all open connections
948 function commitAll() {
949 foreach ( $this->mConns
as $conns2 ) {
950 foreach ( $conns2 as $conns3 ) {
951 foreach ( $conns3 as $conn ) {
952 if ( $conn->trxLevel() ) {
953 $conn->commit( __METHOD__
, 'flush' );
961 * Issue COMMIT only on master, only if queries were done on connection
963 function commitMasterChanges() {
964 // Always 0, but who knows.. :)
965 $masterIndex = $this->getWriterIndex();
966 foreach ( $this->mConns
as $conns2 ) {
967 if ( empty( $conns2[$masterIndex] ) ) {
970 foreach ( $conns2[$masterIndex] as $conn ) {
971 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
972 $conn->commit( __METHOD__
, 'flush' );
982 function waitTimeout( $value = null ) {
983 return wfSetVar( $this->mWaitTimeout
, $value );
989 function getLaggedSlaveMode() {
990 return $this->mLaggedSlaveMode
;
994 * Disables/enables lag checks
998 function allowLagged( $mode = null ) {
999 if ( $mode === null ) {
1000 return $this->mAllowLagged
;
1002 $this->mAllowLagged
= $mode;
1004 return $this->mAllowLagged
;
1010 function pingAll() {
1012 foreach ( $this->mConns
as $conns2 ) {
1013 foreach ( $conns2 as $conns3 ) {
1014 foreach ( $conns3 as $conn ) {
1015 if ( !$conn->ping() ) {
1026 * Call a function with each open connection object
1028 * @param array $params
1030 function forEachOpenConnection( $callback, $params = array() ) {
1031 foreach ( $this->mConns
as $conns2 ) {
1032 foreach ( $conns2 as $conns3 ) {
1033 foreach ( $conns3 as $conn ) {
1034 $mergedParams = array_merge( array( $conn ), $params );
1035 call_user_func_array( $callback, $mergedParams );
1042 * Get the hostname and lag time of the most-lagged slave.
1043 * This is useful for maintenance scripts that need to throttle their updates.
1044 * May attempt to open connections to slaves on the default DB. If there is
1045 * no lag, the maximum lag will be reported as -1.
1047 * @param string $wiki Wiki ID, or false for the default database
1049 * @return array ( host, max lag, index of max lagged host )
1051 function getMaxLag( $wiki = false ) {
1055 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1056 foreach ( $this->mServers
as $i => $conn ) {
1058 if ( $wiki === false ) {
1059 $conn = $this->getAnyOpenConnection( $i );
1062 $conn = $this->openConnection( $i, $wiki );
1067 $lag = $conn->getLag();
1068 if ( $lag > $maxLag ) {
1070 $host = $this->mServers
[$i]['host'];
1076 return array( $host, $maxLag, $maxIndex );
1080 * Get lag time for each server
1081 * Results are cached for a short time in memcached, and indefinitely in the process cache
1087 function getLagTimes( $wiki = false ) {
1089 if ( isset( $this->mLagTimes
) ) {
1090 return $this->mLagTimes
;
1092 if ( $this->getServerCount() == 1 ) {
1094 $this->mLagTimes
= array( 0 => 0 );
1096 # Send the request to the load monitor
1097 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1098 array_keys( $this->mServers
), $wiki );
1101 return $this->mLagTimes
;
1105 * Get the lag in seconds for a given connection, or zero if this load
1106 * balancer does not have replication enabled.
1108 * This should be used in preference to Database::getLag() in cases where
1109 * replication may not be in use, since there is no way to determine if
1110 * replication is in use at the connection level without running
1111 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1112 * function instead of Database::getLag() avoids a fatal error in this
1113 * case on many installations.
1115 * @param $conn DatabaseBase
1119 function safeGetLag( $conn ) {
1120 if ( $this->getServerCount() == 1 ) {
1123 return $conn->getLag();
1128 * Clear the cache for getLagTimes
1130 function clearLagTimeCache() {
1131 $this->mLagTimes
= null;
1136 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1137 * as well handling deferring the actual network connection until the handle is used
1142 class DBConnRef
implements IDatabase
{
1143 /** @var LoadBalancer */
1145 /** @var DatabaseBase|null */
1147 /** @var Array|null */
1151 * @param $lb LoadBalancer
1152 * @param $conn DatabaseBase|array Connection or (server index, group, wiki ID) array
1154 public function __construct( LoadBalancer
$lb, $conn ) {
1156 if ( $conn instanceof DatabaseBase
) {
1157 $this->conn
= $conn;
1159 $this->params
= $conn;
1163 public function __call( $name, $arguments ) {
1164 if ( $this->conn
=== null ) {
1165 list( $db, $groups, $wiki ) = $this->params
;
1166 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1169 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1172 function __destruct() {
1173 if ( $this->conn
!== null ) {
1174 $this->lb
->reuseConnection( $this->conn
);