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;
33 /** @var bool|DatabaseBase Database connection that caused a problem */
34 private $mErrorConnection;
35 private $mReadIndex, $mAllowLagged;
37 /** @var bool|DBMasterPos False if not set */
40 private $mWaitTimeout;
41 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
42 private $mParentInfo, $mLagTimes;
43 private $mLoadMonitorClass, $mLoadMonitor;
46 * @param array $params with keys:
47 * servers Required. Array of server info structures.
48 * masterWaitTimeout Replication lag wait timeout
49 * loadMonitor Name of a class used to fetch server lag and load.
52 function __construct( $params ) {
53 if ( !isset( $params['servers'] ) ) {
54 throw new MWException( __CLASS__
. ': missing servers parameter' );
56 $this->mServers
= $params['servers'];
58 if ( isset( $params['waitTimeout'] ) ) {
59 $this->mWaitTimeout
= $params['waitTimeout'];
61 $this->mWaitTimeout
= 10;
64 $this->mReadIndex
= -1;
65 $this->mWriteIndex
= -1;
66 $this->mConns
= array(
68 'foreignUsed' => array(),
69 'foreignFree' => array() );
70 $this->mLoads
= array();
71 $this->mWaitForPos
= false;
72 $this->mLaggedSlaveMode
= false;
73 $this->mErrorConnection
= false;
74 $this->mAllowLagged
= false;
76 if ( isset( $params['loadMonitor'] ) ) {
77 $this->mLoadMonitorClass
= $params['loadMonitor'];
79 $master = reset( $params['servers'] );
80 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
81 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
83 $this->mLoadMonitorClass
= 'LoadMonitorNull';
87 foreach ( $params['servers'] as $i => $server ) {
88 $this->mLoads
[$i] = $server['load'];
89 if ( isset( $server['groupLoads'] ) ) {
90 foreach ( $server['groupLoads'] as $group => $ratio ) {
91 if ( !isset( $this->mGroupLoads
[$group] ) ) {
92 $this->mGroupLoads
[$group] = array();
94 $this->mGroupLoads
[$group][$i] = $ratio;
101 * Get a LoadMonitor instance
103 * @return LoadMonitor
105 function getLoadMonitor() {
106 if ( !isset( $this->mLoadMonitor
) ) {
107 $class = $this->mLoadMonitorClass
;
108 $this->mLoadMonitor
= new $class( $this );
111 return $this->mLoadMonitor
;
115 * Get or set arbitrary data used by the parent object, usually an LBFactory
119 function parentInfo( $x = null ) {
120 return wfSetVar( $this->mParentInfo
, $x );
124 * Given an array of non-normalised probabilities, this function will select
125 * an element and return the appropriate key
127 * @deprecated since 1.21, use ArrayUtils::pickRandom()
129 * @param array $weights
130 * @return bool|int|string
132 function pickRandom( $weights ) {
133 return ArrayUtils
::pickRandom( $weights );
137 * @param array $loads
138 * @param bool|string $wiki Wiki to get non-lagged for
139 * @return bool|int|string
141 function getRandomNonLagged( $loads, $wiki = false ) {
142 # Unset excessively lagged servers
143 $lags = $this->getLagTimes( $wiki );
144 foreach ( $lags as $i => $lag ) {
146 if ( $lag === false ) {
147 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
149 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
150 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
156 # Find out if all the slaves with non-zero load are lagged
158 foreach ( $loads as $load ) {
162 # No appropriate DB servers except maybe the master and some slaves with zero load
163 # Do NOT use the master
164 # Instead, this function will return false, triggering read-only mode,
165 # and a lagged slave will be used instead.
169 if ( count( $loads ) == 0 ) {
173 #wfDebugLog( 'connect', var_export( $loads, true ) );
175 # Return a random representative of the remainder
176 return ArrayUtils
::pickRandom( $loads );
180 * Get the index of the reader connection, which may be a slave
181 * This takes into account load ratios and lag times. It should
182 * always return a consistent index during a given invocation
184 * Side effect: opens connections to databases
185 * @param bool|string $group
186 * @param bool|string $wiki
187 * @throws MWException
188 * @return bool|int|string
190 function getReaderIndex( $group = false, $wiki = false ) {
191 global $wgReadOnly, $wgDBtype;
193 # @todo FIXME: For now, only go through all this for mysql databases
194 if ( $wgDBtype != 'mysql' ) {
195 return $this->getWriterIndex();
198 if ( count( $this->mServers
) == 1 ) {
199 # Skip the load balancing if there's only one server
201 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
202 # Shortcut if generic reader exists already
203 return $this->mReadIndex
;
206 wfProfileIn( __METHOD__
);
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 ( !count( $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 # No server found yet
235 # First try quickly looking through the available servers for a server that
237 $currentLoads = $nonErrorLoads;
238 while ( count( $currentLoads ) ) {
239 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
240 $i = ArrayUtils
::pickRandom( $currentLoads );
242 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
243 if ( $i === false && count( $currentLoads ) != 0 ) {
244 # All slaves lagged. Switch to read-only mode
245 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
246 $wgReadOnly = 'The database has been automatically locked ' .
247 'while the slave database servers catch up to the master';
248 $i = ArrayUtils
::pickRandom( $currentLoads );
249 $laggedSlaveMode = true;
253 if ( $i === false ) {
254 # pickRandom() returned false
255 # This is permanent and means the configuration or the load monitor
256 # wants us to return false.
257 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false\n" );
258 wfProfileOut( __METHOD__
);
263 wfDebugLog( 'connect', __METHOD__
.
264 ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
266 $conn = $this->openConnection( $i, $wiki );
268 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki\n" );
269 unset( $nonErrorLoads[$i] );
270 unset( $currentLoads[$i] );
274 // Decrement reference counter, we are finished with this connection.
275 // It will be incremented for the caller later.
276 if ( $wiki !== false ) {
277 $this->reuseConnection( $conn );
284 # If all servers were down, quit now
285 if ( !count( $nonErrorLoads ) ) {
286 wfDebugLog( 'connect', "All servers down\n" );
289 if ( $i !== false ) {
290 # Slave connection successful
291 # Wait for the session master pos for a short time
292 if ( $this->mWaitForPos
&& $i > 0 ) {
293 if ( !$this->doWait( $i ) ) {
294 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
297 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $i !== false ) {
298 $this->mReadIndex
= $i;
301 wfProfileOut( __METHOD__
);
307 * Wait for a specified number of microseconds, and return the period waited
311 function sleep( $t ) {
312 wfProfileIn( __METHOD__
);
313 wfDebug( __METHOD__
. ": waiting $t us\n" );
315 wfProfileOut( __METHOD__
);
321 * Set the master wait position
322 * If a DB_SLAVE connection has been opened already, waits
323 * Otherwise sets a variable telling it to wait if such a connection is opened
324 * @param DBMasterPos $pos
326 public function waitFor( $pos ) {
327 wfProfileIn( __METHOD__
);
328 $this->mWaitForPos
= $pos;
329 $i = $this->mReadIndex
;
332 if ( !$this->doWait( $i ) ) {
333 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
334 $this->mLaggedSlaveMode
= true;
337 wfProfileOut( __METHOD__
);
341 * Set the master wait position and wait for ALL slaves to catch up to it
342 * @param DBMasterPos $pos
344 public function waitForAll( $pos ) {
345 wfProfileIn( __METHOD__
);
346 $this->mWaitForPos
= $pos;
347 $serverCount = count( $this->mServers
);
348 for ( $i = 1; $i < $serverCount; $i++
) {
349 if ( $this->mLoads
[$i] > 0 ) {
350 $this->doWait( $i, true );
353 wfProfileOut( __METHOD__
);
357 * Get any open connection to a given server index, local or foreign
358 * Returns false if there is no connection open
361 * @return DatabaseBase|bool False on failure
363 function getAnyOpenConnection( $i ) {
364 foreach ( $this->mConns
as $conns ) {
365 if ( !empty( $conns[$i] ) ) {
366 return reset( $conns[$i] );
374 * Wait for a given slave to catch up to the master pos stored in $this
379 protected function doWait( $index, $open = false ) {
380 # Find a connection to wait on
381 $conn = $this->getAnyOpenConnection( $index );
384 wfDebug( __METHOD__
. ": no connection open\n" );
388 $conn = $this->openConnection( $index, '' );
390 wfDebug( __METHOD__
. ": failed to open connection\n" );
397 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
398 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
400 if ( $result == -1 ||
is_null( $result ) ) {
401 # Timed out waiting for slave, use master instead
402 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
406 wfDebug( __METHOD__
. ": Done\n" );
413 * Get a connection by index
414 * This is the main entry point for this class.
416 * @param $i Integer: server index
417 * @param array $groups query groups
418 * @param bool|string $wiki Wiki ID
420 * @throws MWException
421 * @return DatabaseBase
423 public function &getConnection( $i, $groups = array(), $wiki = false ) {
424 wfProfileIn( __METHOD__
);
426 if ( $i == DB_LAST
) {
427 wfProfileOut( __METHOD__
);
428 throw new MWException( 'Attempt to call ' . __METHOD__
.
429 ' with deprecated server index DB_LAST' );
430 } elseif ( $i === null ||
$i === false ) {
431 wfProfileOut( __METHOD__
);
432 throw new MWException( 'Attempt to call ' . __METHOD__
.
433 ' with invalid server index' );
436 if ( $wiki === wfWikiID() ) {
441 if ( $i == DB_MASTER
) {
442 $i = $this->getWriterIndex();
443 } elseif ( !is_array( $groups ) ) {
444 $groupIndex = $this->getReaderIndex( $groups, $wiki );
445 if ( $groupIndex !== false ) {
446 $serverName = $this->getServerName( $groupIndex );
447 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
451 foreach ( $groups as $group ) {
452 $groupIndex = $this->getReaderIndex( $group, $wiki );
453 if ( $groupIndex !== false ) {
454 $serverName = $this->getServerName( $groupIndex );
455 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
462 # Operation-based index
463 if ( $i == DB_SLAVE
) {
464 $this->mLastError
= 'Unknown error'; // reset error string
465 $i = $this->getReaderIndex( false, $wiki );
466 # Couldn't find a working server in getReaderIndex()?
467 if ( $i === false ) {
468 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
469 wfProfileOut( __METHOD__
);
471 return $this->reportConnectionError();
475 # Now we have an explicit index into the servers array
476 $conn = $this->openConnection( $i, $wiki );
478 wfProfileOut( __METHOD__
);
480 return $this->reportConnectionError();
483 wfProfileOut( __METHOD__
);
489 * Mark a foreign connection as being available for reuse under a different
490 * DB name or prefix. This mechanism is reference-counted, and must be called
491 * the same number of times as getConnection() to work.
493 * @param DatabaseBase $conn
494 * @throws MWException
496 public function reuseConnection( $conn ) {
497 $serverIndex = $conn->getLBInfo( 'serverIndex' );
498 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
499 $dbName = $conn->getDBname();
500 $prefix = $conn->tablePrefix();
501 if ( strval( $prefix ) !== '' ) {
502 $wiki = "$dbName-$prefix";
506 if ( $serverIndex === null ||
$refCount === null ) {
507 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
510 * This can happen in code like:
511 * foreach ( $dbs as $db ) {
512 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
514 * $lb->reuseConnection( $conn );
516 * When a connection to the local DB is opened in this way, reuseConnection()
522 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
523 throw new MWException( __METHOD__
. ": connection not found, has " .
524 "the connection been freed already?" );
526 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
527 if ( $refCount <= 0 ) {
528 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
529 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
530 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
532 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
537 * Get a database connection handle reference
539 * The handle's methods wrap simply wrap those of a DatabaseBase handle
541 * @see LoadBalancer::getConnection() for parameter information
544 * @param mixed $groups
545 * @param bool|string $wiki
548 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
549 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
553 * Get a database connection handle reference without connecting yet
555 * The handle's methods wrap simply wrap those of a DatabaseBase handle
557 * @see LoadBalancer::getConnection() for parameter information
560 * @param mixed $groups
561 * @param bool|string $wiki
564 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
565 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
569 * Open a connection to the server given by the specified index
570 * Index must be an actual index into the array.
571 * If the server is already open, returns it.
573 * On error, returns false, and the connection which caused the
574 * error will be available via $this->mErrorConnection.
576 * @param $i Integer server index
577 * @param bool|string $wiki wiki ID to open
578 * @return DatabaseBase
582 function openConnection( $i, $wiki = false ) {
583 wfProfileIn( __METHOD__
);
584 if ( $wiki !== false ) {
585 $conn = $this->openForeignConnection( $i, $wiki );
586 wfProfileOut( __METHOD__
);
590 if ( isset( $this->mConns
['local'][$i][0] ) ) {
591 $conn = $this->mConns
['local'][$i][0];
593 $server = $this->mServers
[$i];
594 $server['serverIndex'] = $i;
595 $conn = $this->reallyOpenConnection( $server, false );
596 if ( $conn->isOpen() ) {
597 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
598 $this->mConns
['local'][$i][0] = $conn;
600 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
601 $this->mErrorConnection
= $conn;
605 wfProfileOut( __METHOD__
);
611 * Open a connection to a foreign DB, or return one if it is already open.
613 * Increments a reference count on the returned connection which locks the
614 * connection to the requested wiki. This reference count can be
615 * decremented by calling reuseConnection().
617 * If a connection is open to the appropriate server already, but with the wrong
618 * database, it will be switched to the right database and returned, as long as
619 * it has been freed first with reuseConnection().
621 * On error, returns false, and the connection which caused the
622 * error will be available via $this->mErrorConnection.
624 * @param $i Integer: server index
625 * @param string $wiki wiki ID to open
626 * @return DatabaseBase
628 function openForeignConnection( $i, $wiki ) {
629 wfProfileIn( __METHOD__
);
630 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
631 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
632 // Reuse an already-used connection
633 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
634 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
635 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
636 // Reuse a free connection for the same wiki
637 $conn = $this->mConns
['foreignFree'][$i][$wiki];
638 unset( $this->mConns
['foreignFree'][$i][$wiki] );
639 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
640 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
641 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
642 // Reuse a connection from another wiki
643 $conn = reset( $this->mConns
['foreignFree'][$i] );
644 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
646 if ( !$conn->selectDB( $dbName ) ) {
647 $this->mLastError
= "Error selecting database $dbName on server " .
648 $conn->getServer() . " from client host " . wfHostname() . "\n";
649 $this->mErrorConnection
= $conn;
652 $conn->tablePrefix( $prefix );
653 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
654 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
655 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
658 // Open a new connection
659 $server = $this->mServers
[$i];
660 $server['serverIndex'] = $i;
661 $server['foreignPoolRefCount'] = 0;
662 $server['foreign'] = true;
663 $conn = $this->reallyOpenConnection( $server, $dbName );
664 if ( !$conn->isOpen() ) {
665 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
666 $this->mErrorConnection
= $conn;
669 $conn->tablePrefix( $prefix );
670 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
671 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
675 // Increment reference count
677 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
678 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
680 wfProfileOut( __METHOD__
);
686 * Test if the specified index represents an open connection
688 * @param $index Integer: server index
692 function isOpen( $index ) {
693 if ( !is_integer( $index ) ) {
697 return (bool)$this->getAnyOpenConnection( $index );
701 * Really opens a connection. Uncached.
702 * Returns a Database object whether or not the connection was successful.
706 * @param $dbNameOverride bool
707 * @throws MWException
708 * @return DatabaseBase
710 function reallyOpenConnection( $server, $dbNameOverride = false ) {
711 if ( !is_array( $server ) ) {
712 throw new MWException( 'You must update your load-balancing configuration. ' .
713 'See DefaultSettings.php entry for $wgDBservers.' );
716 if ( $dbNameOverride !== false ) {
717 $server['dbname'] = $dbNameOverride;
722 $db = DatabaseBase
::factory( $server['type'], $server );
723 } catch ( DBConnectionError
$e ) {
724 // FIXME: This is probably the ugliest thing I have ever done to
725 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
729 $db->setLBInfo( $server );
730 if ( isset( $server['fakeSlaveLag'] ) ) {
731 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
733 if ( isset( $server['fakeMaster'] ) ) {
734 $db->setFakeMaster( true );
741 * @throws DBConnectionError
744 private function reportConnectionError() {
745 $conn = $this->mErrorConnection
; // The connection which caused the error
747 if ( !is_object( $conn ) ) {
748 // No last connection, probably due to all servers being too busy
749 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
751 // If all servers were busy, mLastError will contain something sensible
752 throw new DBConnectionError( null, $this->mLastError
);
754 $server = $conn->getProperty( 'mServer' );
755 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
756 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
759 return false; /* not reached */
765 function getWriterIndex() {
770 * Returns true if the specified index is a valid server index
775 function haveIndex( $i ) {
776 return array_key_exists( $i, $this->mServers
);
780 * Returns true if the specified index is valid and has non-zero load
785 function isNonZeroLoad( $i ) {
786 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
790 * Get the number of defined servers (not the number of open connections)
794 function getServerCount() {
795 return count( $this->mServers
);
799 * Get the host name or IP address of the server with the specified index
800 * Prefer a readable name if available.
804 function getServerName( $i ) {
805 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
806 return $this->mServers
[$i]['hostName'];
807 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
808 return $this->mServers
[$i]['host'];
815 * Return the server info structure for a given index, or false if the index is invalid.
819 function getServerInfo( $i ) {
820 if ( isset( $this->mServers
[$i] ) ) {
821 return $this->mServers
[$i];
828 * Sets the server info structure for the given index. Entry at index $i
829 * is created if it doesn't exist
833 function setServerInfo( $i, $serverInfo ) {
834 $this->mServers
[$i] = $serverInfo;
838 * Get the current master position for chronology control purposes
841 function getMasterPos() {
842 # If this entire request was served from a slave without opening a connection to the
843 # master (however unlikely that may be), then we can fetch the position from the slave.
844 $masterConn = $this->getAnyOpenConnection( 0 );
845 if ( !$masterConn ) {
846 $serverCount = count( $this->mServers
);
847 for ( $i = 1; $i < $serverCount; $i++
) {
848 $conn = $this->getAnyOpenConnection( $i );
850 wfDebug( "Master pos fetched from slave\n" );
852 return $conn->getSlavePos();
856 wfDebug( "Master pos fetched from master\n" );
858 return $masterConn->getMasterPos();
865 * Close all open connections
867 function closeAll() {
868 foreach ( $this->mConns
as $conns2 ) {
869 foreach ( $conns2 as $conns3 ) {
870 /** @var DatabaseBase $conn */
871 foreach ( $conns3 as $conn ) {
876 $this->mConns
= array(
878 'foreignFree' => array(),
879 'foreignUsed' => array(),
884 * Deprecated function, typo in function name
886 * @deprecated in 1.18
887 * @param DatabaseBase $conn
889 function closeConnecton( $conn ) {
890 wfDeprecated( __METHOD__
, '1.18' );
891 $this->closeConnection( $conn );
896 * Using this function makes sure the LoadBalancer knows the connection is closed.
897 * If you use $conn->close() directly, the load balancer won't update its state.
898 * @param DatabaseBase $conn
900 function closeConnection( $conn ) {
902 foreach ( $this->mConns
as $i1 => $conns2 ) {
903 foreach ( $conns2 as $i2 => $conns3 ) {
904 foreach ( $conns3 as $i3 => $candidateConn ) {
905 if ( $conn === $candidateConn ) {
907 unset( $this->mConns
[$i1][$i2][$i3] );
920 * Commit transactions on all open connections
922 function commitAll() {
923 foreach ( $this->mConns
as $conns2 ) {
924 foreach ( $conns2 as $conns3 ) {
925 /** @var DatabaseBase[] $conns3 */
926 foreach ( $conns3 as $conn ) {
927 if ( $conn->trxLevel() ) {
928 $conn->commit( __METHOD__
, 'flush' );
936 * Issue COMMIT only on master, only if queries were done on connection
938 function commitMasterChanges() {
939 // Always 0, but who knows.. :)
940 $masterIndex = $this->getWriterIndex();
941 foreach ( $this->mConns
as $conns2 ) {
942 if ( empty( $conns2[$masterIndex] ) ) {
945 /** @var DatabaseBase $conn */
946 foreach ( $conns2[$masterIndex] as $conn ) {
947 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
948 $conn->commit( __METHOD__
, 'flush' );
958 function waitTimeout( $value = null ) {
959 return wfSetVar( $this->mWaitTimeout
, $value );
965 function getLaggedSlaveMode() {
966 return $this->mLaggedSlaveMode
;
970 * Disables/enables lag checks
971 * @param null|bool $mode
974 function allowLagged( $mode = null ) {
975 if ( $mode === null ) {
976 return $this->mAllowLagged
;
978 $this->mAllowLagged
= $mode;
980 return $this->mAllowLagged
;
988 foreach ( $this->mConns
as $conns2 ) {
989 foreach ( $conns2 as $conns3 ) {
990 /** @var DatabaseBase[] $conns3 */
991 foreach ( $conns3 as $conn ) {
992 if ( !$conn->ping() ) {
1003 * Call a function with each open connection object
1004 * @param callable $callback
1005 * @param array $params
1007 function forEachOpenConnection( $callback, $params = array() ) {
1008 foreach ( $this->mConns
as $conns2 ) {
1009 foreach ( $conns2 as $conns3 ) {
1010 foreach ( $conns3 as $conn ) {
1011 $mergedParams = array_merge( array( $conn ), $params );
1012 call_user_func_array( $callback, $mergedParams );
1019 * Get the hostname and lag time of the most-lagged slave.
1020 * This is useful for maintenance scripts that need to throttle their updates.
1021 * May attempt to open connections to slaves on the default DB. If there is
1022 * no lag, the maximum lag will be reported as -1.
1024 * @param bool|string $wiki Wiki ID, or false for the default database
1025 * @return array ( host, max lag, index of max lagged host )
1027 function getMaxLag( $wiki = false ) {
1031 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1032 foreach ( $this->mServers
as $i => $conn ) {
1034 if ( $wiki === false ) {
1035 $conn = $this->getAnyOpenConnection( $i );
1038 $conn = $this->openConnection( $i, $wiki );
1043 $lag = $conn->getLag();
1044 if ( $lag > $maxLag ) {
1046 $host = $this->mServers
[$i]['host'];
1052 return array( $host, $maxLag, $maxIndex );
1056 * Get lag time for each server
1057 * Results are cached for a short time in memcached, and indefinitely in the process cache
1059 * @param string|bool $wiki
1062 function getLagTimes( $wiki = false ) {
1064 if ( isset( $this->mLagTimes
) ) {
1065 return $this->mLagTimes
;
1067 if ( $this->getServerCount() == 1 ) {
1069 $this->mLagTimes
= array( 0 => 0 );
1071 # Send the request to the load monitor
1072 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1073 array_keys( $this->mServers
), $wiki );
1076 return $this->mLagTimes
;
1080 * Get the lag in seconds for a given connection, or zero if this load
1081 * balancer does not have replication enabled.
1083 * This should be used in preference to Database::getLag() in cases where
1084 * replication may not be in use, since there is no way to determine if
1085 * replication is in use at the connection level without running
1086 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1087 * function instead of Database::getLag() avoids a fatal error in this
1088 * case on many installations.
1090 * @param DatabaseBase $conn
1093 function safeGetLag( $conn ) {
1094 if ( $this->getServerCount() == 1 ) {
1097 return $conn->getLag();
1102 * Clear the cache for getLagTimes
1104 function clearLagTimeCache() {
1105 $this->mLagTimes
= null;
1110 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1111 * as well handling deferring the actual network connection until the handle is used
1116 class DBConnRef
implements IDatabase
{
1117 /** @var LoadBalancer */
1120 /** @var DatabaseBase|null */
1123 /** @var array|null */
1127 * @param LoadBalancer $lb
1128 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1130 public function __construct( LoadBalancer
$lb, $conn ) {
1132 if ( $conn instanceof DatabaseBase
) {
1133 $this->conn
= $conn;
1135 $this->params
= $conn;
1139 public function __call( $name, $arguments ) {
1140 if ( $this->conn
=== null ) {
1141 list( $db, $groups, $wiki ) = $this->params
;
1142 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1145 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1148 function __destruct() {
1149 if ( $this->conn
!== null ) {
1150 $this->lb
->reuseConnection( $this->conn
);