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" );
149 } elseif ( isset( $this->mServers
[$i]['max lag'] ) && $lag > $this->mServers
[$i]['max lag'] ) {
150 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
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 $section = new ProfileSection( __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" );
219 $nonErrorLoads = $this->mLoads
;
222 if ( !count( $nonErrorLoads ) ) {
223 throw new MWException( "Empty server array given to LoadBalancer" );
226 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
227 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
229 $laggedSlaveMode = false;
231 # No server found yet
233 # First try quickly looking through the available servers for a server that
235 $currentLoads = $nonErrorLoads;
236 while ( count( $currentLoads ) ) {
237 if ( $wgReadOnly ||
$this->mAllowLagged ||
$laggedSlaveMode ) {
238 $i = ArrayUtils
::pickRandom( $currentLoads );
240 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
241 if ( $i === false && count( $currentLoads ) != 0 ) {
242 # All slaves lagged. Switch to read-only mode
243 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
244 $wgReadOnly = 'The database has been automatically locked ' .
245 'while the slave database servers catch up to the master';
246 $i = ArrayUtils
::pickRandom( $currentLoads );
247 $laggedSlaveMode = true;
251 if ( $i === false ) {
252 # pickRandom() returned false
253 # This is permanent and means the configuration or the load monitor
254 # wants us to return false.
255 wfDebugLog( 'connect', __METHOD__
. ": pickRandom() returned false" );
260 wfDebugLog( 'connect', __METHOD__
.
261 ": Using reader #$i: {$this->mServers[$i]['host']}..." );
263 $conn = $this->openConnection( $i, $wiki );
265 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki" );
266 unset( $nonErrorLoads[$i] );
267 unset( $currentLoads[$i] );
272 // Decrement reference counter, we are finished with this connection.
273 // It will be incremented for the caller later.
274 if ( $wiki !== false ) {
275 $this->reuseConnection( $conn );
282 # If all servers were down, quit now
283 if ( !count( $nonErrorLoads ) ) {
284 wfDebugLog( 'connect', "All servers down" );
287 if ( $i !== false ) {
288 # Slave connection successful
289 # Wait for the session master pos for a short time
290 if ( $this->mWaitForPos
&& $i > 0 ) {
291 if ( !$this->doWait( $i ) ) {
292 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
295 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group !== false ) {
296 $this->mReadIndex
= $i;
304 * Wait for a specified number of microseconds, and return the period waited
308 function sleep( $t ) {
309 wfProfileIn( __METHOD__
);
310 wfDebug( __METHOD__
. ": waiting $t us\n" );
312 wfProfileOut( __METHOD__
);
318 * Set the master wait position
319 * If a DB_SLAVE connection has been opened already, waits
320 * Otherwise sets a variable telling it to wait if such a connection is opened
321 * @param DBMasterPos $pos
323 public function waitFor( $pos ) {
324 wfProfileIn( __METHOD__
);
325 $this->mWaitForPos
= $pos;
326 $i = $this->mReadIndex
;
329 if ( !$this->doWait( $i ) ) {
330 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
331 $this->mLaggedSlaveMode
= true;
334 wfProfileOut( __METHOD__
);
338 * Set the master wait position and wait for ALL slaves to catch up to it
339 * @param DBMasterPos $pos
341 public function waitForAll( $pos ) {
342 wfProfileIn( __METHOD__
);
343 $this->mWaitForPos
= $pos;
344 $serverCount = count( $this->mServers
);
345 for ( $i = 1; $i < $serverCount; $i++
) {
346 if ( $this->mLoads
[$i] > 0 ) {
347 $this->doWait( $i, true );
350 wfProfileOut( __METHOD__
);
354 * Get any open connection to a given server index, local or foreign
355 * Returns false if there is no connection open
358 * @return DatabaseBase|bool False on failure
360 function getAnyOpenConnection( $i ) {
361 foreach ( $this->mConns
as $conns ) {
362 if ( !empty( $conns[$i] ) ) {
363 return reset( $conns[$i] );
371 * Wait for a given slave to catch up to the master pos stored in $this
376 protected function doWait( $index, $open = false ) {
377 # Find a connection to wait on
378 $conn = $this->getAnyOpenConnection( $index );
381 wfDebug( __METHOD__
. ": no connection open\n" );
385 $conn = $this->openConnection( $index, '' );
387 wfDebug( __METHOD__
. ": failed to open connection\n" );
394 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
395 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
397 if ( $result == -1 ||
is_null( $result ) ) {
398 # Timed out waiting for slave, use master instead
399 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
403 wfDebug( __METHOD__
. ": Done\n" );
410 * Get a connection by index
411 * This is the main entry point for this class.
413 * @param $i Integer: server index
414 * @param array $groups query groups
415 * @param bool|string $wiki Wiki ID
417 * @throws MWException
418 * @return DatabaseBase
420 public function &getConnection( $i, $groups = array(), $wiki = false ) {
421 wfProfileIn( __METHOD__
);
423 if ( $i == DB_LAST
) {
424 wfProfileOut( __METHOD__
);
425 throw new MWException( 'Attempt to call ' . __METHOD__
.
426 ' with deprecated server index DB_LAST' );
427 } elseif ( $i === null ||
$i === false ) {
428 wfProfileOut( __METHOD__
);
429 throw new MWException( 'Attempt to call ' . __METHOD__
.
430 ' with invalid server index' );
433 if ( $wiki === wfWikiID() ) {
438 if ( $i == DB_MASTER
) {
439 $i = $this->getWriterIndex();
440 } elseif ( !is_array( $groups ) ) {
441 $groupIndex = $this->getReaderIndex( $groups, $wiki );
442 if ( $groupIndex !== false ) {
443 $serverName = $this->getServerName( $groupIndex );
444 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
448 foreach ( $groups as $group ) {
449 $groupIndex = $this->getReaderIndex( $group, $wiki );
450 if ( $groupIndex !== false ) {
451 $serverName = $this->getServerName( $groupIndex );
452 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
459 # Operation-based index
460 if ( $i == DB_SLAVE
) {
461 $this->mLastError
= 'Unknown error'; // reset error string
462 $i = $this->getReaderIndex( false, $wiki );
463 # Couldn't find a working server in getReaderIndex()?
464 if ( $i === false ) {
465 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
466 wfProfileOut( __METHOD__
);
468 return $this->reportConnectionError();
472 # Now we have an explicit index into the servers array
473 $conn = $this->openConnection( $i, $wiki );
475 wfProfileOut( __METHOD__
);
477 return $this->reportConnectionError();
480 wfProfileOut( __METHOD__
);
486 * Mark a foreign connection as being available for reuse under a different
487 * DB name or prefix. This mechanism is reference-counted, and must be called
488 * the same number of times as getConnection() to work.
490 * @param DatabaseBase $conn
491 * @throws MWException
493 public function reuseConnection( $conn ) {
494 $serverIndex = $conn->getLBInfo( 'serverIndex' );
495 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
496 $dbName = $conn->getDBname();
497 $prefix = $conn->tablePrefix();
498 if ( strval( $prefix ) !== '' ) {
499 $wiki = "$dbName-$prefix";
503 if ( $serverIndex === null ||
$refCount === null ) {
504 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
507 * This can happen in code like:
508 * foreach ( $dbs as $db ) {
509 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
511 * $lb->reuseConnection( $conn );
513 * When a connection to the local DB is opened in this way, reuseConnection()
519 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
520 throw new MWException( __METHOD__
. ": connection not found, has " .
521 "the connection been freed already?" );
523 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
524 if ( $refCount <= 0 ) {
525 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
526 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
527 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
529 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
534 * Get a database connection handle reference
536 * The handle's methods wrap simply wrap those of a DatabaseBase handle
538 * @see LoadBalancer::getConnection() for parameter information
541 * @param mixed $groups
542 * @param bool|string $wiki
545 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
546 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
550 * Get a database connection handle reference without connecting yet
552 * The handle's methods wrap simply wrap those of a DatabaseBase handle
554 * @see LoadBalancer::getConnection() for parameter information
557 * @param mixed $groups
558 * @param bool|string $wiki
561 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
562 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
566 * Open a connection to the server given by the specified index
567 * Index must be an actual index into the array.
568 * If the server is already open, returns it.
570 * On error, returns false, and the connection which caused the
571 * error will be available via $this->mErrorConnection.
573 * @param $i Integer server index
574 * @param bool|string $wiki wiki ID to open
575 * @return DatabaseBase
579 function openConnection( $i, $wiki = false ) {
580 wfProfileIn( __METHOD__
);
581 if ( $wiki !== false ) {
582 $conn = $this->openForeignConnection( $i, $wiki );
583 wfProfileOut( __METHOD__
);
587 if ( isset( $this->mConns
['local'][$i][0] ) ) {
588 $conn = $this->mConns
['local'][$i][0];
590 $server = $this->mServers
[$i];
591 $server['serverIndex'] = $i;
592 $conn = $this->reallyOpenConnection( $server, false );
593 if ( $conn->isOpen() ) {
594 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
595 $this->mConns
['local'][$i][0] = $conn;
597 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
598 $this->mErrorConnection
= $conn;
602 wfProfileOut( __METHOD__
);
608 * Open a connection to a foreign DB, or return one if it is already open.
610 * Increments a reference count on the returned connection which locks the
611 * connection to the requested wiki. This reference count can be
612 * decremented by calling reuseConnection().
614 * If a connection is open to the appropriate server already, but with the wrong
615 * database, it will be switched to the right database and returned, as long as
616 * it has been freed first with reuseConnection().
618 * On error, returns false, and the connection which caused the
619 * error will be available via $this->mErrorConnection.
621 * @param $i Integer: server index
622 * @param string $wiki wiki ID to open
623 * @return DatabaseBase
625 function openForeignConnection( $i, $wiki ) {
626 wfProfileIn( __METHOD__
);
627 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
628 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
629 // Reuse an already-used connection
630 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
631 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
632 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
633 // Reuse a free connection for the same wiki
634 $conn = $this->mConns
['foreignFree'][$i][$wiki];
635 unset( $this->mConns
['foreignFree'][$i][$wiki] );
636 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
637 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
638 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
639 // Reuse a connection from another wiki
640 $conn = reset( $this->mConns
['foreignFree'][$i] );
641 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
643 if ( !$conn->selectDB( $dbName ) ) {
644 $this->mLastError
= "Error selecting database $dbName on server " .
645 $conn->getServer() . " from client host " . wfHostname() . "\n";
646 $this->mErrorConnection
= $conn;
649 $conn->tablePrefix( $prefix );
650 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
651 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
652 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
655 // Open a new connection
656 $server = $this->mServers
[$i];
657 $server['serverIndex'] = $i;
658 $server['foreignPoolRefCount'] = 0;
659 $server['foreign'] = true;
660 $conn = $this->reallyOpenConnection( $server, $dbName );
661 if ( !$conn->isOpen() ) {
662 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
663 $this->mErrorConnection
= $conn;
666 $conn->tablePrefix( $prefix );
667 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
668 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
672 // Increment reference count
674 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
675 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
677 wfProfileOut( __METHOD__
);
683 * Test if the specified index represents an open connection
685 * @param $index Integer: server index
689 function isOpen( $index ) {
690 if ( !is_integer( $index ) ) {
694 return (bool)$this->getAnyOpenConnection( $index );
698 * Really opens a connection. Uncached.
699 * Returns a Database object whether or not the connection was successful.
703 * @param $dbNameOverride bool
704 * @throws MWException
705 * @return DatabaseBase
707 function reallyOpenConnection( $server, $dbNameOverride = false ) {
708 if ( !is_array( $server ) ) {
709 throw new MWException( 'You must update your load-balancing configuration. ' .
710 'See DefaultSettings.php entry for $wgDBservers.' );
713 if ( $dbNameOverride !== false ) {
714 $server['dbname'] = $dbNameOverride;
719 $db = DatabaseBase
::factory( $server['type'], $server );
720 } catch ( DBConnectionError
$e ) {
721 // FIXME: This is probably the ugliest thing I have ever done to
722 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
726 $db->setLBInfo( $server );
727 if ( isset( $server['fakeSlaveLag'] ) ) {
728 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
730 if ( isset( $server['fakeMaster'] ) ) {
731 $db->setFakeMaster( true );
738 * @throws DBConnectionError
741 private function reportConnectionError() {
742 $conn = $this->mErrorConnection
; // The connection which caused the error
744 if ( !is_object( $conn ) ) {
745 // No last connection, probably due to all servers being too busy
746 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
748 // If all servers were busy, mLastError will contain something sensible
749 throw new DBConnectionError( null, $this->mLastError
);
751 $server = $conn->getProperty( 'mServer' );
752 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
753 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
756 return false; /* not reached */
762 function getWriterIndex() {
767 * Returns true if the specified index is a valid server index
772 function haveIndex( $i ) {
773 return array_key_exists( $i, $this->mServers
);
777 * Returns true if the specified index is valid and has non-zero load
782 function isNonZeroLoad( $i ) {
783 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
787 * Get the number of defined servers (not the number of open connections)
791 function getServerCount() {
792 return count( $this->mServers
);
796 * Get the host name or IP address of the server with the specified index
797 * Prefer a readable name if available.
801 function getServerName( $i ) {
802 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
803 return $this->mServers
[$i]['hostName'];
804 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
805 return $this->mServers
[$i]['host'];
812 * Return the server info structure for a given index, or false if the index is invalid.
816 function getServerInfo( $i ) {
817 if ( isset( $this->mServers
[$i] ) ) {
818 return $this->mServers
[$i];
825 * Sets the server info structure for the given index. Entry at index $i
826 * is created if it doesn't exist
830 function setServerInfo( $i, $serverInfo ) {
831 $this->mServers
[$i] = $serverInfo;
835 * Get the current master position for chronology control purposes
838 function getMasterPos() {
839 # If this entire request was served from a slave without opening a connection to the
840 # master (however unlikely that may be), then we can fetch the position from the slave.
841 $masterConn = $this->getAnyOpenConnection( 0 );
842 if ( !$masterConn ) {
843 $serverCount = count( $this->mServers
);
844 for ( $i = 1; $i < $serverCount; $i++
) {
845 $conn = $this->getAnyOpenConnection( $i );
847 wfDebug( "Master pos fetched from slave\n" );
849 return $conn->getSlavePos();
853 wfDebug( "Master pos fetched from master\n" );
855 return $masterConn->getMasterPos();
862 * Close all open connections
864 function closeAll() {
865 foreach ( $this->mConns
as $conns2 ) {
866 foreach ( $conns2 as $conns3 ) {
867 /** @var DatabaseBase $conn */
868 foreach ( $conns3 as $conn ) {
873 $this->mConns
= array(
875 'foreignFree' => array(),
876 'foreignUsed' => array(),
881 * Deprecated function, typo in function name
883 * @deprecated in 1.18
884 * @param DatabaseBase $conn
886 function closeConnecton( $conn ) {
887 wfDeprecated( __METHOD__
, '1.18' );
888 $this->closeConnection( $conn );
893 * Using this function makes sure the LoadBalancer knows the connection is closed.
894 * If you use $conn->close() directly, the load balancer won't update its state.
895 * @param DatabaseBase $conn
897 function closeConnection( $conn ) {
899 foreach ( $this->mConns
as $i1 => $conns2 ) {
900 foreach ( $conns2 as $i2 => $conns3 ) {
901 foreach ( $conns3 as $i3 => $candidateConn ) {
902 if ( $conn === $candidateConn ) {
904 unset( $this->mConns
[$i1][$i2][$i3] );
917 * Commit transactions on all open connections
919 function commitAll() {
920 foreach ( $this->mConns
as $conns2 ) {
921 foreach ( $conns2 as $conns3 ) {
922 /** @var DatabaseBase[] $conns3 */
923 foreach ( $conns3 as $conn ) {
924 if ( $conn->trxLevel() ) {
925 $conn->commit( __METHOD__
, 'flush' );
933 * Issue COMMIT only on master, only if queries were done on connection
935 function commitMasterChanges() {
936 // Always 0, but who knows.. :)
937 $masterIndex = $this->getWriterIndex();
938 foreach ( $this->mConns
as $conns2 ) {
939 if ( empty( $conns2[$masterIndex] ) ) {
942 /** @var DatabaseBase $conn */
943 foreach ( $conns2[$masterIndex] as $conn ) {
944 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
945 $conn->commit( __METHOD__
, 'flush' );
955 function waitTimeout( $value = null ) {
956 return wfSetVar( $this->mWaitTimeout
, $value );
962 function getLaggedSlaveMode() {
963 return $this->mLaggedSlaveMode
;
967 * Disables/enables lag checks
968 * @param null|bool $mode
971 function allowLagged( $mode = null ) {
972 if ( $mode === null ) {
973 return $this->mAllowLagged
;
975 $this->mAllowLagged
= $mode;
977 return $this->mAllowLagged
;
985 foreach ( $this->mConns
as $conns2 ) {
986 foreach ( $conns2 as $conns3 ) {
987 /** @var DatabaseBase[] $conns3 */
988 foreach ( $conns3 as $conn ) {
989 if ( !$conn->ping() ) {
1000 * Call a function with each open connection object
1001 * @param callable $callback
1002 * @param array $params
1004 function forEachOpenConnection( $callback, $params = array() ) {
1005 foreach ( $this->mConns
as $conns2 ) {
1006 foreach ( $conns2 as $conns3 ) {
1007 foreach ( $conns3 as $conn ) {
1008 $mergedParams = array_merge( array( $conn ), $params );
1009 call_user_func_array( $callback, $mergedParams );
1016 * Get the hostname and lag time of the most-lagged slave.
1017 * This is useful for maintenance scripts that need to throttle their updates.
1018 * May attempt to open connections to slaves on the default DB. If there is
1019 * no lag, the maximum lag will be reported as -1.
1021 * @param bool|string $wiki Wiki ID, or false for the default database
1022 * @return array ( host, max lag, index of max lagged host )
1024 function getMaxLag( $wiki = false ) {
1028 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1029 foreach ( $this->mServers
as $i => $conn ) {
1031 if ( $wiki === false ) {
1032 $conn = $this->getAnyOpenConnection( $i );
1035 $conn = $this->openConnection( $i, $wiki );
1040 $lag = $conn->getLag();
1041 if ( $lag > $maxLag ) {
1043 $host = $this->mServers
[$i]['host'];
1049 return array( $host, $maxLag, $maxIndex );
1053 * Get lag time for each server
1054 * Results are cached for a short time in memcached, and indefinitely in the process cache
1056 * @param string|bool $wiki
1059 function getLagTimes( $wiki = false ) {
1061 if ( isset( $this->mLagTimes
) ) {
1062 return $this->mLagTimes
;
1064 if ( $this->getServerCount() == 1 ) {
1066 $this->mLagTimes
= array( 0 => 0 );
1068 # Send the request to the load monitor
1069 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1070 array_keys( $this->mServers
), $wiki );
1073 return $this->mLagTimes
;
1077 * Get the lag in seconds for a given connection, or zero if this load
1078 * balancer does not have replication enabled.
1080 * This should be used in preference to Database::getLag() in cases where
1081 * replication may not be in use, since there is no way to determine if
1082 * replication is in use at the connection level without running
1083 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1084 * function instead of Database::getLag() avoids a fatal error in this
1085 * case on many installations.
1087 * @param DatabaseBase $conn
1090 function safeGetLag( $conn ) {
1091 if ( $this->getServerCount() == 1 ) {
1094 return $conn->getLag();
1099 * Clear the cache for getLagTimes
1101 function clearLagTimeCache() {
1102 $this->mLagTimes
= null;
1107 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1108 * as well handling deferring the actual network connection until the handle is used
1113 class DBConnRef
implements IDatabase
{
1114 /** @var LoadBalancer */
1117 /** @var DatabaseBase|null */
1120 /** @var array|null */
1124 * @param LoadBalancer $lb
1125 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1127 public function __construct( LoadBalancer
$lb, $conn ) {
1129 if ( $conn instanceof DatabaseBase
) {
1130 $this->conn
= $conn;
1132 $this->params
= $conn;
1136 public function __call( $name, $arguments ) {
1137 if ( $this->conn
=== null ) {
1138 list( $db, $groups, $wiki ) = $this->params
;
1139 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1142 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1145 function __destruct() {
1146 if ( $this->conn
!== null ) {
1147 $this->lb
->reuseConnection( $this->conn
);