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 $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\n" );
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\n" );
260 wfDebugLog( 'connect', __METHOD__
.
261 ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
263 $conn = $this->openConnection( $i, $wiki );
265 wfDebugLog( 'connect', __METHOD__
. ": Failed connecting to $i/$wiki\n" );
266 unset( $nonErrorLoads[$i] );
267 unset( $currentLoads[$i] );
271 // Decrement reference counter, we are finished with this connection.
272 // It will be incremented for the caller later.
273 if ( $wiki !== false ) {
274 $this->reuseConnection( $conn );
281 # If all servers were down, quit now
282 if ( !count( $nonErrorLoads ) ) {
283 wfDebugLog( 'connect', "All servers down\n" );
286 if ( $i !== false ) {
287 # Slave connection successful
288 # Wait for the session master pos for a short time
289 if ( $this->mWaitForPos
&& $i > 0 ) {
290 if ( !$this->doWait( $i ) ) {
291 $this->mServers
[$i]['slave pos'] = $conn->getSlavePos();
294 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group !== false ) {
295 $this->mReadIndex
= $i;
303 * Wait for a specified number of microseconds, and return the period waited
307 function sleep( $t ) {
308 wfProfileIn( __METHOD__
);
309 wfDebug( __METHOD__
. ": waiting $t us\n" );
311 wfProfileOut( __METHOD__
);
317 * Set the master wait position
318 * If a DB_SLAVE connection has been opened already, waits
319 * Otherwise sets a variable telling it to wait if such a connection is opened
320 * @param DBMasterPos $pos
322 public function waitFor( $pos ) {
323 wfProfileIn( __METHOD__
);
324 $this->mWaitForPos
= $pos;
325 $i = $this->mReadIndex
;
328 if ( !$this->doWait( $i ) ) {
329 $this->mServers
[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
330 $this->mLaggedSlaveMode
= true;
333 wfProfileOut( __METHOD__
);
337 * Set the master wait position and wait for ALL slaves to catch up to it
338 * @param DBMasterPos $pos
340 public function waitForAll( $pos ) {
341 wfProfileIn( __METHOD__
);
342 $this->mWaitForPos
= $pos;
343 $serverCount = count( $this->mServers
);
344 for ( $i = 1; $i < $serverCount; $i++
) {
345 if ( $this->mLoads
[$i] > 0 ) {
346 $this->doWait( $i, true );
349 wfProfileOut( __METHOD__
);
353 * Get any open connection to a given server index, local or foreign
354 * Returns false if there is no connection open
357 * @return DatabaseBase|bool False on failure
359 function getAnyOpenConnection( $i ) {
360 foreach ( $this->mConns
as $conns ) {
361 if ( !empty( $conns[$i] ) ) {
362 return reset( $conns[$i] );
370 * Wait for a given slave to catch up to the master pos stored in $this
375 protected function doWait( $index, $open = false ) {
376 # Find a connection to wait on
377 $conn = $this->getAnyOpenConnection( $index );
380 wfDebug( __METHOD__
. ": no connection open\n" );
384 $conn = $this->openConnection( $index, '' );
386 wfDebug( __METHOD__
. ": failed to open connection\n" );
393 wfDebug( __METHOD__
. ": Waiting for slave #$index to catch up...\n" );
394 $result = $conn->masterPosWait( $this->mWaitForPos
, $this->mWaitTimeout
);
396 if ( $result == -1 ||
is_null( $result ) ) {
397 # Timed out waiting for slave, use master instead
398 wfDebug( __METHOD__
. ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
402 wfDebug( __METHOD__
. ": Done\n" );
409 * Get a connection by index
410 * This is the main entry point for this class.
412 * @param $i Integer: server index
413 * @param array $groups query groups
414 * @param bool|string $wiki Wiki ID
416 * @throws MWException
417 * @return DatabaseBase
419 public function &getConnection( $i, $groups = array(), $wiki = false ) {
420 wfProfileIn( __METHOD__
);
422 if ( $i == DB_LAST
) {
423 wfProfileOut( __METHOD__
);
424 throw new MWException( 'Attempt to call ' . __METHOD__
.
425 ' with deprecated server index DB_LAST' );
426 } elseif ( $i === null ||
$i === false ) {
427 wfProfileOut( __METHOD__
);
428 throw new MWException( 'Attempt to call ' . __METHOD__
.
429 ' with invalid server index' );
432 if ( $wiki === wfWikiID() ) {
437 if ( $i == DB_MASTER
) {
438 $i = $this->getWriterIndex();
439 } elseif ( !is_array( $groups ) ) {
440 $groupIndex = $this->getReaderIndex( $groups, $wiki );
441 if ( $groupIndex !== false ) {
442 $serverName = $this->getServerName( $groupIndex );
443 wfDebug( __METHOD__
. ": using server $serverName for group $groups\n" );
447 foreach ( $groups as $group ) {
448 $groupIndex = $this->getReaderIndex( $group, $wiki );
449 if ( $groupIndex !== false ) {
450 $serverName = $this->getServerName( $groupIndex );
451 wfDebug( __METHOD__
. ": using server $serverName for group $group\n" );
458 # Operation-based index
459 if ( $i == DB_SLAVE
) {
460 $this->mLastError
= 'Unknown error'; // reset error string
461 $i = $this->getReaderIndex( false, $wiki );
462 # Couldn't find a working server in getReaderIndex()?
463 if ( $i === false ) {
464 $this->mLastError
= 'No working slave server: ' . $this->mLastError
;
465 wfProfileOut( __METHOD__
);
467 return $this->reportConnectionError();
471 # Now we have an explicit index into the servers array
472 $conn = $this->openConnection( $i, $wiki );
474 wfProfileOut( __METHOD__
);
476 return $this->reportConnectionError();
479 wfProfileOut( __METHOD__
);
485 * Mark a foreign connection as being available for reuse under a different
486 * DB name or prefix. This mechanism is reference-counted, and must be called
487 * the same number of times as getConnection() to work.
489 * @param DatabaseBase $conn
490 * @throws MWException
492 public function reuseConnection( $conn ) {
493 $serverIndex = $conn->getLBInfo( 'serverIndex' );
494 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
495 $dbName = $conn->getDBname();
496 $prefix = $conn->tablePrefix();
497 if ( strval( $prefix ) !== '' ) {
498 $wiki = "$dbName-$prefix";
502 if ( $serverIndex === null ||
$refCount === null ) {
503 wfDebug( __METHOD__
. ": this connection was not opened as a foreign connection\n" );
506 * This can happen in code like:
507 * foreach ( $dbs as $db ) {
508 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
510 * $lb->reuseConnection( $conn );
512 * When a connection to the local DB is opened in this way, reuseConnection()
518 if ( $this->mConns
['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
519 throw new MWException( __METHOD__
. ": connection not found, has " .
520 "the connection been freed already?" );
522 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
523 if ( $refCount <= 0 ) {
524 $this->mConns
['foreignFree'][$serverIndex][$wiki] = $conn;
525 unset( $this->mConns
['foreignUsed'][$serverIndex][$wiki] );
526 wfDebug( __METHOD__
. ": freed connection $serverIndex/$wiki\n" );
528 wfDebug( __METHOD__
. ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
533 * Get a database connection handle reference
535 * The handle's methods wrap simply wrap those of a DatabaseBase handle
537 * @see LoadBalancer::getConnection() for parameter information
540 * @param mixed $groups
541 * @param bool|string $wiki
544 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
545 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
549 * Get a database connection handle reference without connecting yet
551 * The handle's methods wrap simply wrap those of a DatabaseBase handle
553 * @see LoadBalancer::getConnection() for parameter information
556 * @param mixed $groups
557 * @param bool|string $wiki
560 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
561 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
565 * Open a connection to the server given by the specified index
566 * Index must be an actual index into the array.
567 * If the server is already open, returns it.
569 * On error, returns false, and the connection which caused the
570 * error will be available via $this->mErrorConnection.
572 * @param $i Integer server index
573 * @param bool|string $wiki wiki ID to open
574 * @return DatabaseBase
578 function openConnection( $i, $wiki = false ) {
579 wfProfileIn( __METHOD__
);
580 if ( $wiki !== false ) {
581 $conn = $this->openForeignConnection( $i, $wiki );
582 wfProfileOut( __METHOD__
);
586 if ( isset( $this->mConns
['local'][$i][0] ) ) {
587 $conn = $this->mConns
['local'][$i][0];
589 $server = $this->mServers
[$i];
590 $server['serverIndex'] = $i;
591 $conn = $this->reallyOpenConnection( $server, false );
592 if ( $conn->isOpen() ) {
593 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
594 $this->mConns
['local'][$i][0] = $conn;
596 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
597 $this->mErrorConnection
= $conn;
601 wfProfileOut( __METHOD__
);
607 * Open a connection to a foreign DB, or return one if it is already open.
609 * Increments a reference count on the returned connection which locks the
610 * connection to the requested wiki. This reference count can be
611 * decremented by calling reuseConnection().
613 * If a connection is open to the appropriate server already, but with the wrong
614 * database, it will be switched to the right database and returned, as long as
615 * it has been freed first with reuseConnection().
617 * On error, returns false, and the connection which caused the
618 * error will be available via $this->mErrorConnection.
620 * @param $i Integer: server index
621 * @param string $wiki wiki ID to open
622 * @return DatabaseBase
624 function openForeignConnection( $i, $wiki ) {
625 wfProfileIn( __METHOD__
);
626 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
627 if ( isset( $this->mConns
['foreignUsed'][$i][$wiki] ) ) {
628 // Reuse an already-used connection
629 $conn = $this->mConns
['foreignUsed'][$i][$wiki];
630 wfDebug( __METHOD__
. ": reusing connection $i/$wiki\n" );
631 } elseif ( isset( $this->mConns
['foreignFree'][$i][$wiki] ) ) {
632 // Reuse a free connection for the same wiki
633 $conn = $this->mConns
['foreignFree'][$i][$wiki];
634 unset( $this->mConns
['foreignFree'][$i][$wiki] );
635 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
636 wfDebug( __METHOD__
. ": reusing free connection $i/$wiki\n" );
637 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
638 // Reuse a connection from another wiki
639 $conn = reset( $this->mConns
['foreignFree'][$i] );
640 $oldWiki = key( $this->mConns
['foreignFree'][$i] );
642 if ( !$conn->selectDB( $dbName ) ) {
643 $this->mLastError
= "Error selecting database $dbName on server " .
644 $conn->getServer() . " from client host " . wfHostname() . "\n";
645 $this->mErrorConnection
= $conn;
648 $conn->tablePrefix( $prefix );
649 unset( $this->mConns
['foreignFree'][$i][$oldWiki] );
650 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
651 wfDebug( __METHOD__
. ": reusing free connection from $oldWiki for $wiki\n" );
654 // Open a new connection
655 $server = $this->mServers
[$i];
656 $server['serverIndex'] = $i;
657 $server['foreignPoolRefCount'] = 0;
658 $server['foreign'] = true;
659 $conn = $this->reallyOpenConnection( $server, $dbName );
660 if ( !$conn->isOpen() ) {
661 wfDebug( __METHOD__
. ": error opening connection for $i/$wiki\n" );
662 $this->mErrorConnection
= $conn;
665 $conn->tablePrefix( $prefix );
666 $this->mConns
['foreignUsed'][$i][$wiki] = $conn;
667 wfDebug( __METHOD__
. ": opened new connection for $i/$wiki\n" );
671 // Increment reference count
673 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
674 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
676 wfProfileOut( __METHOD__
);
682 * Test if the specified index represents an open connection
684 * @param $index Integer: server index
688 function isOpen( $index ) {
689 if ( !is_integer( $index ) ) {
693 return (bool)$this->getAnyOpenConnection( $index );
697 * Really opens a connection. Uncached.
698 * Returns a Database object whether or not the connection was successful.
702 * @param $dbNameOverride bool
703 * @throws MWException
704 * @return DatabaseBase
706 function reallyOpenConnection( $server, $dbNameOverride = false ) {
707 if ( !is_array( $server ) ) {
708 throw new MWException( 'You must update your load-balancing configuration. ' .
709 'See DefaultSettings.php entry for $wgDBservers.' );
712 if ( $dbNameOverride !== false ) {
713 $server['dbname'] = $dbNameOverride;
718 $db = DatabaseBase
::factory( $server['type'], $server );
719 } catch ( DBConnectionError
$e ) {
720 // FIXME: This is probably the ugliest thing I have ever done to
721 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
725 $db->setLBInfo( $server );
726 if ( isset( $server['fakeSlaveLag'] ) ) {
727 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
729 if ( isset( $server['fakeMaster'] ) ) {
730 $db->setFakeMaster( true );
737 * @throws DBConnectionError
740 private function reportConnectionError() {
741 $conn = $this->mErrorConnection
; // The connection which caused the error
743 if ( !is_object( $conn ) ) {
744 // No last connection, probably due to all servers being too busy
745 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
747 // If all servers were busy, mLastError will contain something sensible
748 throw new DBConnectionError( null, $this->mLastError
);
750 $server = $conn->getProperty( 'mServer' );
751 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
752 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
755 return false; /* not reached */
761 function getWriterIndex() {
766 * Returns true if the specified index is a valid server index
771 function haveIndex( $i ) {
772 return array_key_exists( $i, $this->mServers
);
776 * Returns true if the specified index is valid and has non-zero load
781 function isNonZeroLoad( $i ) {
782 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
786 * Get the number of defined servers (not the number of open connections)
790 function getServerCount() {
791 return count( $this->mServers
);
795 * Get the host name or IP address of the server with the specified index
796 * Prefer a readable name if available.
800 function getServerName( $i ) {
801 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
802 return $this->mServers
[$i]['hostName'];
803 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
804 return $this->mServers
[$i]['host'];
811 * Return the server info structure for a given index, or false if the index is invalid.
815 function getServerInfo( $i ) {
816 if ( isset( $this->mServers
[$i] ) ) {
817 return $this->mServers
[$i];
824 * Sets the server info structure for the given index. Entry at index $i
825 * is created if it doesn't exist
829 function setServerInfo( $i, $serverInfo ) {
830 $this->mServers
[$i] = $serverInfo;
834 * Get the current master position for chronology control purposes
837 function getMasterPos() {
838 # If this entire request was served from a slave without opening a connection to the
839 # master (however unlikely that may be), then we can fetch the position from the slave.
840 $masterConn = $this->getAnyOpenConnection( 0 );
841 if ( !$masterConn ) {
842 $serverCount = count( $this->mServers
);
843 for ( $i = 1; $i < $serverCount; $i++
) {
844 $conn = $this->getAnyOpenConnection( $i );
846 wfDebug( "Master pos fetched from slave\n" );
848 return $conn->getSlavePos();
852 wfDebug( "Master pos fetched from master\n" );
854 return $masterConn->getMasterPos();
861 * Close all open connections
863 function closeAll() {
864 foreach ( $this->mConns
as $conns2 ) {
865 foreach ( $conns2 as $conns3 ) {
866 /** @var DatabaseBase $conn */
867 foreach ( $conns3 as $conn ) {
872 $this->mConns
= array(
874 'foreignFree' => array(),
875 'foreignUsed' => array(),
880 * Deprecated function, typo in function name
882 * @deprecated in 1.18
883 * @param DatabaseBase $conn
885 function closeConnecton( $conn ) {
886 wfDeprecated( __METHOD__
, '1.18' );
887 $this->closeConnection( $conn );
892 * Using this function makes sure the LoadBalancer knows the connection is closed.
893 * If you use $conn->close() directly, the load balancer won't update its state.
894 * @param DatabaseBase $conn
896 function closeConnection( $conn ) {
898 foreach ( $this->mConns
as $i1 => $conns2 ) {
899 foreach ( $conns2 as $i2 => $conns3 ) {
900 foreach ( $conns3 as $i3 => $candidateConn ) {
901 if ( $conn === $candidateConn ) {
903 unset( $this->mConns
[$i1][$i2][$i3] );
916 * Commit transactions on all open connections
918 function commitAll() {
919 foreach ( $this->mConns
as $conns2 ) {
920 foreach ( $conns2 as $conns3 ) {
921 /** @var DatabaseBase[] $conns3 */
922 foreach ( $conns3 as $conn ) {
923 if ( $conn->trxLevel() ) {
924 $conn->commit( __METHOD__
, 'flush' );
932 * Issue COMMIT only on master, only if queries were done on connection
934 function commitMasterChanges() {
935 // Always 0, but who knows.. :)
936 $masterIndex = $this->getWriterIndex();
937 foreach ( $this->mConns
as $conns2 ) {
938 if ( empty( $conns2[$masterIndex] ) ) {
941 /** @var DatabaseBase $conn */
942 foreach ( $conns2[$masterIndex] as $conn ) {
943 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
944 $conn->commit( __METHOD__
, 'flush' );
954 function waitTimeout( $value = null ) {
955 return wfSetVar( $this->mWaitTimeout
, $value );
961 function getLaggedSlaveMode() {
962 return $this->mLaggedSlaveMode
;
966 * Disables/enables lag checks
967 * @param null|bool $mode
970 function allowLagged( $mode = null ) {
971 if ( $mode === null ) {
972 return $this->mAllowLagged
;
974 $this->mAllowLagged
= $mode;
976 return $this->mAllowLagged
;
984 foreach ( $this->mConns
as $conns2 ) {
985 foreach ( $conns2 as $conns3 ) {
986 /** @var DatabaseBase[] $conns3 */
987 foreach ( $conns3 as $conn ) {
988 if ( !$conn->ping() ) {
999 * Call a function with each open connection object
1000 * @param callable $callback
1001 * @param array $params
1003 function forEachOpenConnection( $callback, $params = array() ) {
1004 foreach ( $this->mConns
as $conns2 ) {
1005 foreach ( $conns2 as $conns3 ) {
1006 foreach ( $conns3 as $conn ) {
1007 $mergedParams = array_merge( array( $conn ), $params );
1008 call_user_func_array( $callback, $mergedParams );
1015 * Get the hostname and lag time of the most-lagged slave.
1016 * This is useful for maintenance scripts that need to throttle their updates.
1017 * May attempt to open connections to slaves on the default DB. If there is
1018 * no lag, the maximum lag will be reported as -1.
1020 * @param bool|string $wiki Wiki ID, or false for the default database
1021 * @return array ( host, max lag, index of max lagged host )
1023 function getMaxLag( $wiki = false ) {
1027 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1028 foreach ( $this->mServers
as $i => $conn ) {
1030 if ( $wiki === false ) {
1031 $conn = $this->getAnyOpenConnection( $i );
1034 $conn = $this->openConnection( $i, $wiki );
1039 $lag = $conn->getLag();
1040 if ( $lag > $maxLag ) {
1042 $host = $this->mServers
[$i]['host'];
1048 return array( $host, $maxLag, $maxIndex );
1052 * Get lag time for each server
1053 * Results are cached for a short time in memcached, and indefinitely in the process cache
1055 * @param string|bool $wiki
1058 function getLagTimes( $wiki = false ) {
1060 if ( isset( $this->mLagTimes
) ) {
1061 return $this->mLagTimes
;
1063 if ( $this->getServerCount() == 1 ) {
1065 $this->mLagTimes
= array( 0 => 0 );
1067 # Send the request to the load monitor
1068 $this->mLagTimes
= $this->getLoadMonitor()->getLagTimes(
1069 array_keys( $this->mServers
), $wiki );
1072 return $this->mLagTimes
;
1076 * Get the lag in seconds for a given connection, or zero if this load
1077 * balancer does not have replication enabled.
1079 * This should be used in preference to Database::getLag() in cases where
1080 * replication may not be in use, since there is no way to determine if
1081 * replication is in use at the connection level without running
1082 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1083 * function instead of Database::getLag() avoids a fatal error in this
1084 * case on many installations.
1086 * @param DatabaseBase $conn
1089 function safeGetLag( $conn ) {
1090 if ( $this->getServerCount() == 1 ) {
1093 return $conn->getLag();
1098 * Clear the cache for getLagTimes
1100 function clearLagTimeCache() {
1101 $this->mLagTimes
= null;
1106 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1107 * as well handling deferring the actual network connection until the handle is used
1112 class DBConnRef
implements IDatabase
{
1113 /** @var LoadBalancer */
1116 /** @var DatabaseBase|null */
1119 /** @var array|null */
1123 * @param LoadBalancer $lb
1124 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1126 public function __construct( LoadBalancer
$lb, $conn ) {
1128 if ( $conn instanceof DatabaseBase
) {
1129 $this->conn
= $conn;
1131 $this->params
= $conn;
1135 public function __call( $name, $arguments ) {
1136 if ( $this->conn
=== null ) {
1137 list( $db, $groups, $wiki ) = $this->params
;
1138 $this->conn
= $this->lb
->getConnection( $db, $groups, $wiki );
1141 return call_user_func_array( array( $this->conn
, $name ), $arguments );
1144 function __destruct() {
1145 if ( $this->conn
!== null ) {
1146 $this->lb
->reuseConnection( $this->conn
);