3 * Database load balancing manager
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
23 use Psr\Log\LoggerInterface
;
26 * Database connection, tracking, load balancing, and transaction manager for a cluster
30 class LoadBalancer
implements ILoadBalancer
{
31 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => IDatabase array) */
35 /** @var array Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
39 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
42 private $mWaitTimeout;
43 /** @var string The LoadMonitor subclass name */
44 private $mLoadMonitorClass;
45 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
46 private $tableAliases = [];
48 /** @var ILoadMonitor */
49 private $mLoadMonitor;
54 /** @var WANObjectCache */
56 /** @var object|string Class name or object With profileIn/profileOut methods */
58 /** @var TransactionProfiler */
59 protected $trxProfiler;
60 /** @var LoggerInterface */
61 protected $replLogger;
62 /** @var LoggerInterface */
63 protected $connLogger;
64 /** @var LoggerInterface */
65 protected $queryLogger;
66 /** @var LoggerInterface */
67 protected $perfLogger;
69 /** @var bool|IDatabase Database connection that caused a problem */
70 private $mErrorConnection;
71 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
73 /** @var bool|DBMasterPos False if not set */
75 /** @var bool Whether the generic reader fell back to a lagged replica DB */
76 private $laggedReplicaMode = false;
77 /** @var bool Whether the generic reader fell back to a lagged replica DB */
78 private $allReplicasDownMode = false;
79 /** @var string The last DB selection or connection error */
80 private $mLastError = 'Unknown error';
81 /** @var string|bool Reason the LB is read-only or false if not */
82 private $readOnlyReason = false;
83 /** @var integer Total connections opened */
84 private $connsOpened = 0;
85 /** @var string|bool String if a requested DBO_TRX transaction round is active */
86 private $trxRoundId = false;
87 /** @var array[] Map of (name => callable) */
88 private $trxRecurringCallbacks = [];
89 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
91 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
92 private $localDomainIdAlias;
93 /** @var string Current server name */
95 /** @var bool Whether this PHP instance is for a CLI script */
97 /** @var string Agent name for query profiling */
100 /** @var callable Exception logger */
101 private $errorLogger;
104 private $disabled = false;
106 /** @var integer Warn when this many connection are held */
107 const CONN_HELD_WARN_THRESHOLD
= 10;
108 /** @var integer Default 'max lag' when unspecified */
109 const MAX_LAG_DEFAULT
= 10;
110 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
111 const POS_WAIT_TIMEOUT
= 10;
112 /** @var integer Seconds to cache master server read-only status */
113 const TTL_CACHE_READONLY
= 5;
115 public function __construct( array $params ) {
116 if ( !isset( $params['servers'] ) ) {
117 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
119 $this->mServers
= $params['servers'];
121 $this->localDomain
= isset( $params['localDomain'] )
122 ? DatabaseDomain
::newFromId( $params['localDomain'] )
123 : DatabaseDomain
::newUnspecified();
124 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
125 // always true, gracefully handle the case when they fail to account for escaping.
126 if ( $this->localDomain
->getTablePrefix() != '' ) {
127 $this->localDomainIdAlias
=
128 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
130 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
133 $this->mWaitTimeout
= isset( $params['waitTimeout'] )
134 ?
$params['waitTimeout']
135 : self
::POS_WAIT_TIMEOUT
;
137 $this->mReadIndex
= -1;
141 'foreignFree' => [] ];
143 $this->mWaitForPos
= false;
144 $this->mErrorConnection
= false;
145 $this->mAllowLagged
= false;
147 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
148 $this->readOnlyReason
= $params['readOnlyReason'];
151 if ( isset( $params['loadMonitor'] ) ) {
152 $this->mLoadMonitorClass
= $params['loadMonitor'];
154 $master = reset( $params['servers'] );
155 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
156 $this->mLoadMonitorClass
= 'LoadMonitorMySQL';
158 $this->mLoadMonitorClass
= 'LoadMonitorNull';
162 foreach ( $params['servers'] as $i => $server ) {
163 $this->mLoads
[$i] = $server['load'];
164 if ( isset( $server['groupLoads'] ) ) {
165 foreach ( $server['groupLoads'] as $group => $ratio ) {
166 if ( !isset( $this->mGroupLoads
[$group] ) ) {
167 $this->mGroupLoads
[$group] = [];
169 $this->mGroupLoads
[$group][$i] = $ratio;
174 if ( isset( $params['srvCache'] ) ) {
175 $this->srvCache
= $params['srvCache'];
177 $this->srvCache
= new EmptyBagOStuff();
179 if ( isset( $params['memCache'] ) ) {
180 $this->memCache
= $params['memCache'];
182 $this->memCache
= new EmptyBagOStuff();
184 if ( isset( $params['wanCache'] ) ) {
185 $this->wanCache
= $params['wanCache'];
187 $this->wanCache
= WANObjectCache
::newEmpty();
189 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
190 if ( isset( $params['trxProfiler'] ) ) {
191 $this->trxProfiler
= $params['trxProfiler'];
193 $this->trxProfiler
= new TransactionProfiler();
196 $this->errorLogger
= isset( $params['errorLogger'] )
197 ?
$params['errorLogger']
198 : function ( Exception
$e ) {
199 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
202 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
203 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
206 $this->host
= isset( $params['hostname'] )
207 ?
$params['hostname']
208 : ( gethostname() ?
: 'unknown' );
209 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
210 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
214 * Get a LoadMonitor instance
216 * @return ILoadMonitor
218 private function getLoadMonitor() {
219 if ( !isset( $this->mLoadMonitor
) ) {
220 $class = $this->mLoadMonitorClass
;
221 $this->mLoadMonitor
= new $class( $this, $this->srvCache
, $this->memCache
);
222 $this->mLoadMonitor
->setLogger( $this->replLogger
);
225 return $this->mLoadMonitor
;
229 * @param array $loads
230 * @param bool|string $domain Domain to get non-lagged for
231 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
232 * @return bool|int|string
234 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
235 $lags = $this->getLagTimes( $domain );
237 # Unset excessively lagged servers
238 foreach ( $lags as $i => $lag ) {
240 # How much lag this server nominally is allowed to have
241 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
242 ?
$this->mServers
[$i]['max lag']
243 : self
::MAX_LAG_DEFAULT
; // default
244 # Constrain that futher by $maxLag argument
245 $maxServerLag = min( $maxServerLag, $maxLag );
247 $host = $this->getServerName( $i );
248 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
249 $this->replLogger
->error( "Server $host (#$i) is not replicating?" );
251 } elseif ( $lag > $maxServerLag ) {
252 $this->replLogger
->warning( "Server $host (#$i) has >= $lag seconds of lag" );
258 # Find out if all the replica DBs with non-zero load are lagged
260 foreach ( $loads as $load ) {
264 # No appropriate DB servers except maybe the master and some replica DBs with zero load
265 # Do NOT use the master
266 # Instead, this function will return false, triggering read-only mode,
267 # and a lagged replica DB will be used instead.
271 if ( count( $loads ) == 0 ) {
275 # Return a random representative of the remainder
276 return ArrayUtils
::pickRandom( $loads );
279 public function getReaderIndex( $group = false, $domain = false ) {
280 if ( count( $this->mServers
) == 1 ) {
281 # Skip the load balancing if there's only one server
282 return $this->getWriterIndex();
283 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
284 # Shortcut if generic reader exists already
285 return $this->mReadIndex
;
288 # Find the relevant load array
289 if ( $group !== false ) {
290 if ( isset( $this->mGroupLoads
[$group] ) ) {
291 $nonErrorLoads = $this->mGroupLoads
[$group];
293 # No loads for this group, return false and the caller can use some other group
294 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
299 $nonErrorLoads = $this->mLoads
;
302 if ( !count( $nonErrorLoads ) ) {
303 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
306 # Scale the configured load ratios according to the dynamic load if supported
307 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $domain );
309 $laggedReplicaMode = false;
311 # No server found yet
313 # First try quickly looking through the available servers for a server that
315 $currentLoads = $nonErrorLoads;
316 while ( count( $currentLoads ) ) {
317 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
318 $i = ArrayUtils
::pickRandom( $currentLoads );
321 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
322 # ChronologyProtecter causes mWaitForPos to be set via sessions.
323 # This triggers doWait() after connect, so it's especially good to
324 # avoid lagged servers so as to avoid just blocking in that method.
325 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
326 # Aim for <= 1 second of waiting (being too picky can backfire)
327 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
329 if ( $i === false ) {
330 # Any server with less lag than it's 'max lag' param is preferable
331 $i = $this->getRandomNonLagged( $currentLoads, $domain );
333 if ( $i === false && count( $currentLoads ) != 0 ) {
334 # All replica DBs lagged. Switch to read-only mode
335 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
336 $i = ArrayUtils
::pickRandom( $currentLoads );
337 $laggedReplicaMode = true;
341 if ( $i === false ) {
342 # pickRandom() returned false
343 # This is permanent and means the configuration or the load monitor
344 # wants us to return false.
345 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
350 $serverName = $this->getServerName( $i );
351 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
353 $conn = $this->openConnection( $i, $domain );
355 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
356 unset( $nonErrorLoads[$i] );
357 unset( $currentLoads[$i] );
362 // Decrement reference counter, we are finished with this connection.
363 // It will be incremented for the caller later.
364 if ( $domain !== false ) {
365 $this->reuseConnection( $conn );
372 # If all servers were down, quit now
373 if ( !count( $nonErrorLoads ) ) {
374 $this->connLogger
->error( "All servers down" );
377 if ( $i !== false ) {
378 # Replica DB connection successful.
379 # Wait for the session master pos for a short time.
380 if ( $this->mWaitForPos
&& $i > 0 ) {
383 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
384 $this->mReadIndex
= $i;
385 # Record if the generic reader index is in "lagged replica DB" mode
386 if ( $laggedReplicaMode ) {
387 $this->laggedReplicaMode
= true;
390 $serverName = $this->getServerName( $i );
391 $this->connLogger
->debug(
392 __METHOD__
. ": using server $serverName for group '$group'" );
398 public function waitFor( $pos ) {
399 $this->mWaitForPos
= $pos;
400 $i = $this->mReadIndex
;
403 if ( !$this->doWait( $i ) ) {
404 $this->laggedReplicaMode
= true;
409 public function waitForOne( $pos, $timeout = null ) {
410 $this->mWaitForPos
= $pos;
412 $i = $this->mReadIndex
;
414 // Pick a generic replica DB if there isn't one yet
415 $readLoads = $this->mLoads
;
416 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
417 $readLoads = array_filter( $readLoads ); // with non-zero load
418 $i = ArrayUtils
::pickRandom( $readLoads );
422 $ok = $this->doWait( $i, true, $timeout );
424 $ok = true; // no applicable loads
430 public function waitForAll( $pos, $timeout = null ) {
431 $this->mWaitForPos
= $pos;
432 $serverCount = count( $this->mServers
);
435 for ( $i = 1; $i < $serverCount; $i++
) {
436 if ( $this->mLoads
[$i] > 0 ) {
437 $ok = $this->doWait( $i, true, $timeout ) && $ok;
444 public function getAnyOpenConnection( $i ) {
445 foreach ( $this->mConns
as $connsByServer ) {
446 if ( !empty( $connsByServer[$i] ) ) {
447 return reset( $connsByServer[$i] );
455 * Wait for a given replica DB to catch up to the master pos stored in $this
456 * @param int $index Server index
457 * @param bool $open Check the server even if a new connection has to be made
458 * @param int $timeout Max seconds to wait; default is mWaitTimeout
461 protected function doWait( $index, $open = false, $timeout = null ) {
462 $close = false; // close the connection afterwards
464 // Check if we already know that the DB has reached this point
465 $server = $this->getServerName( $index );
466 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
467 /** @var DBMasterPos $knownReachedPos */
468 $knownReachedPos = $this->srvCache
->get( $key );
469 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
470 $this->replLogger
->debug( __METHOD__
.
471 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
475 // Find a connection to wait on, creating one if needed and allowed
476 $conn = $this->getAnyOpenConnection( $index );
479 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
483 $conn = $this->openConnection( $index, '' );
485 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
489 // Avoid connection spam in waitForAll() when connections
490 // are made just for the sake of doing this lag check.
495 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
496 $timeout = $timeout ?
: $this->mWaitTimeout
;
497 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
499 if ( $result == -1 ||
is_null( $result ) ) {
500 // Timed out waiting for replica DB, use master instead
501 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
502 $this->replLogger
->warning( "$msg" );
505 $this->replLogger
->info( __METHOD__
. ": Done" );
507 // Remember that the DB reached this point
508 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
512 $this->closeConnection( $conn );
518 public function getConnection( $i, $groups = [], $domain = false ) {
519 if ( $i === null ||
$i === false ) {
520 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
521 ' with invalid server index' );
524 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
525 $domain = false; // local connection requested
528 $groups = ( $groups === false ||
$groups === [] )
529 ?
[ false ] // check one "group": the generic pool
532 $masterOnly = ( $i == DB_MASTER ||
$i == $this->getWriterIndex() );
533 $oldConnsOpened = $this->connsOpened
; // connections open now
535 if ( $i == DB_MASTER
) {
536 $i = $this->getWriterIndex();
538 # Try to find an available server in any the query groups (in order)
539 foreach ( $groups as $group ) {
540 $groupIndex = $this->getReaderIndex( $group, $domain );
541 if ( $groupIndex !== false ) {
548 # Operation-based index
549 if ( $i == DB_REPLICA
) {
550 $this->mLastError
= 'Unknown error'; // reset error string
551 # Try the general server pool if $groups are unavailable.
552 $i = in_array( false, $groups, true )
553 ?
false // don't bother with this if that is what was tried above
554 : $this->getReaderIndex( false, $domain );
555 # Couldn't find a working server in getReaderIndex()?
556 if ( $i === false ) {
557 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
559 return $this->reportConnectionError();
563 # Now we have an explicit index into the servers array
564 $conn = $this->openConnection( $i, $domain );
566 return $this->reportConnectionError();
569 # Profile any new connections that happen
570 if ( $this->connsOpened
> $oldConnsOpened ) {
571 $host = $conn->getServer();
572 $dbname = $conn->getDBname();
573 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
577 # Make master-requested DB handles inherit any read-only mode setting
578 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
584 public function reuseConnection( $conn ) {
585 $serverIndex = $conn->getLBInfo( 'serverIndex' );
586 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
587 if ( $serverIndex === null ||
$refCount === null ) {
589 * This can happen in code like:
590 * foreach ( $dbs as $db ) {
591 * $conn = $lb->getConnection( DB_REPLICA, [], $db );
593 * $lb->reuseConnection( $conn );
595 * When a connection to the local DB is opened in this way, reuseConnection()
601 $dbName = $conn->getDBname();
602 $prefix = $conn->tablePrefix();
603 if ( strval( $prefix ) !== '' ) {
604 $domain = "$dbName-$prefix";
608 if ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
609 throw new InvalidArgumentException( __METHOD__
. ": connection not found, has " .
610 "the connection been freed already?" );
612 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
613 if ( $refCount <= 0 ) {
614 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
615 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
616 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
618 $this->connLogger
->debug( __METHOD__
.
619 ": reference count for $serverIndex/$domain reduced to $refCount" );
623 public function getConnectionRef( $db, $groups = [], $domain = false ) {
624 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
626 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
629 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
630 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
632 return new DBConnRef( $this, [ $db, $groups, $domain ] );
635 public function openConnection( $i, $domain = false ) {
636 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
637 $domain = false; // local connection requested
640 if ( $domain !== false ) {
641 $conn = $this->openForeignConnection( $i, $domain );
642 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
643 $conn = $this->mConns
['local'][$i][0];
645 $server = $this->mServers
[$i];
646 $server['serverIndex'] = $i;
647 $conn = $this->reallyOpenConnection( $server, false );
648 $serverName = $this->getServerName( $i );
649 if ( $conn->isOpen() ) {
650 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
651 $this->mConns
['local'][$i][0] = $conn;
653 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
654 $this->mErrorConnection
= $conn;
659 if ( $conn && !$conn->isOpen() ) {
660 // Connection was made but later unrecoverably lost for some reason.
661 // Do not return a handle that will just throw exceptions on use,
662 // but let the calling code (e.g. getReaderIndex) try another server.
663 // See DatabaseMyslBase::ping() for how this can happen.
664 $this->mErrorConnection
= $conn;
672 * Open a connection to a foreign DB, or return one if it is already open.
674 * Increments a reference count on the returned connection which locks the
675 * connection to the requested domain. This reference count can be
676 * decremented by calling reuseConnection().
678 * If a connection is open to the appropriate server already, but with the wrong
679 * database, it will be switched to the right database and returned, as long as
680 * it has been freed first with reuseConnection().
682 * On error, returns false, and the connection which caused the
683 * error will be available via $this->mErrorConnection.
685 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
687 * @param int $i Server index
688 * @param string $domain Domain ID to open
691 private function openForeignConnection( $i, $domain ) {
692 $domainInstance = DatabaseDomain
::newFromId( $domain );
693 $dbName = $domainInstance->getDatabase();
694 $prefix = $domainInstance->getTablePrefix();
696 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
697 // Reuse an already-used connection
698 $conn = $this->mConns
['foreignUsed'][$i][$domain];
699 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
700 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
701 // Reuse a free connection for the same domain
702 $conn = $this->mConns
['foreignFree'][$i][$domain];
703 unset( $this->mConns
['foreignFree'][$i][$domain] );
704 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
705 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
706 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
707 // Reuse a connection from another domain
708 $conn = reset( $this->mConns
['foreignFree'][$i] );
709 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
711 // The empty string as a DB name means "don't care".
712 // DatabaseMysqlBase::open() already handle this on connection.
713 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
714 $this->mLastError
= "Error selecting database $dbName on server " .
715 $conn->getServer() . " from client host {$this->host}";
716 $this->mErrorConnection
= $conn;
719 $conn->tablePrefix( $prefix );
720 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
721 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
722 $this->connLogger
->debug( __METHOD__
.
723 ": reusing free connection from $oldDomain for $domain" );
726 // Open a new connection
727 $server = $this->mServers
[$i];
728 $server['serverIndex'] = $i;
729 $server['foreignPoolRefCount'] = 0;
730 $server['foreign'] = true;
731 $conn = $this->reallyOpenConnection( $server, $dbName );
732 if ( !$conn->isOpen() ) {
733 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
734 $this->mErrorConnection
= $conn;
737 $conn->tablePrefix( $prefix );
738 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
739 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
743 // Increment reference count
745 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
746 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
753 * Test if the specified index represents an open connection
755 * @param int $index Server index
759 private function isOpen( $index ) {
760 if ( !is_integer( $index ) ) {
764 return (bool)$this->getAnyOpenConnection( $index );
768 * Really opens a connection. Uncached.
769 * Returns a Database object whether or not the connection was successful.
772 * @param array $server
773 * @param bool $dbNameOverride
775 * @throws DBAccessError
776 * @throws InvalidArgumentException
778 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
779 if ( $this->disabled
) {
780 throw new DBAccessError();
783 if ( !is_array( $server ) ) {
784 throw new InvalidArgumentException(
785 'You must update your load-balancing configuration. ' .
786 'See DefaultSettings.php entry for $wgDBservers.' );
789 if ( $dbNameOverride !== false ) {
790 $server['dbname'] = $dbNameOverride;
793 // Let the handle know what the cluster master is (e.g. "db1052")
794 $masterName = $this->getServerName( $this->getWriterIndex() );
795 $server['clusterMasterHost'] = $masterName;
797 // Log when many connection are made on requests
798 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
799 $this->perfLogger
->warning( __METHOD__
. ": " .
800 "{$this->connsOpened}+ connections made (master=$masterName)" );
803 $server['srvCache'] = $this->srvCache
;
804 // Set loggers and profilers
805 $server['connLogger'] = $this->connLogger
;
806 $server['queryLogger'] = $this->queryLogger
;
807 $server['errorLogger'] = $this->errorLogger
;
808 $server['profiler'] = $this->profiler
;
809 $server['trxProfiler'] = $this->trxProfiler
;
810 // Use the same agent and PHP mode for all DB handles
811 $server['cliMode'] = $this->cliMode
;
812 $server['agent'] = $this->agent
;
813 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
814 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
815 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : DBO_DEFAULT
;
817 // Create a live connection object
819 $db = Database
::factory( $server['type'], $server );
820 } catch ( DBConnectionError
$e ) {
821 // FIXME: This is probably the ugliest thing I have ever done to
822 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
826 $db->setLBInfo( $server );
827 $db->setLazyMasterHandle(
828 $this->getLazyConnectionRef( DB_MASTER
, [], $db->getDomainID() )
830 $db->setTableAliases( $this->tableAliases
);
832 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
833 if ( $this->trxRoundId
!== false ) {
834 $this->applyTransactionRoundFlags( $db );
836 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
837 $db->setTransactionListener( $name, $callback );
845 * @throws DBConnectionError
848 private function reportConnectionError() {
849 $conn = $this->mErrorConnection
; // The connection which caused the error
851 'method' => __METHOD__
,
852 'last_error' => $this->mLastError
,
855 if ( !is_object( $conn ) ) {
856 // No last connection, probably due to all servers being too busy
857 $this->connLogger
->error(
858 "LB failure with no last connection. Connection error: {last_error}",
862 // If all servers were busy, mLastError will contain something sensible
863 throw new DBConnectionError( null, $this->mLastError
);
865 $context['db_server'] = $conn->getProperty( 'mServer' );
866 $this->connLogger
->warning(
867 "Connection error: {last_error} ({db_server})",
871 // throws DBConnectionError
872 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
875 return false; /* not reached */
878 public function getWriterIndex() {
882 public function haveIndex( $i ) {
883 return array_key_exists( $i, $this->mServers
);
886 public function isNonZeroLoad( $i ) {
887 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
890 public function getServerCount() {
891 return count( $this->mServers
);
894 public function getServerName( $i ) {
895 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
896 $name = $this->mServers
[$i]['hostName'];
897 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
898 $name = $this->mServers
[$i]['host'];
903 return ( $name != '' ) ?
$name : 'localhost';
906 public function getServerInfo( $i ) {
907 if ( isset( $this->mServers
[$i] ) ) {
908 return $this->mServers
[$i];
914 public function setServerInfo( $i, array $serverInfo ) {
915 $this->mServers
[$i] = $serverInfo;
918 public function getMasterPos() {
919 # If this entire request was served from a replica DB without opening a connection to the
920 # master (however unlikely that may be), then we can fetch the position from the replica DB.
921 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
922 if ( !$masterConn ) {
923 $serverCount = count( $this->mServers
);
924 for ( $i = 1; $i < $serverCount; $i++
) {
925 $conn = $this->getAnyOpenConnection( $i );
927 return $conn->getSlavePos();
931 return $masterConn->getMasterPos();
937 public function disable() {
939 $this->disabled
= true;
942 public function closeAll() {
943 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
952 $this->connsOpened
= 0;
955 public function closeConnection( IDatabase
$conn ) {
956 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
957 foreach ( $this->mConns
as $type => $connsByServer ) {
958 if ( !isset( $connsByServer[$serverIndex] ) ) {
962 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
963 if ( $conn === $trackedConn ) {
964 unset( $this->mConns
[$type][$serverIndex][$i] );
965 --$this->connsOpened
;
974 public function commitAll( $fname = __METHOD__
) {
977 $restore = ( $this->trxRoundId
!== false );
978 $this->trxRoundId
= false;
979 $this->forEachOpenConnection(
980 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
982 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
983 } catch ( DBError
$e ) {
984 call_user_func( $this->errorLogger
, $e );
985 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
987 if ( $restore && $conn->getLBInfo( 'master' ) ) {
988 $this->undoTransactionRoundFlags( $conn );
994 throw new DBExpectedError(
996 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1001 public function finalizeMasterChanges() {
1002 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1003 // Any error should cause all DB transactions to be rolled back together
1004 $conn->setTrxEndCallbackSuppression( false );
1005 $conn->runOnTransactionPreCommitCallbacks();
1006 // Defer post-commit callbacks until COMMIT finishes for all DBs
1007 $conn->setTrxEndCallbackSuppression( true );
1011 public function approveMasterChanges( array $options ) {
1012 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1013 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1014 // If atomic sections or explicit transactions are still open, some caller must have
1015 // caught an exception but failed to properly rollback any changes. Detect that and
1016 // throw and error (causing rollback).
1017 if ( $conn->explicitTrxActive() ) {
1018 throw new DBTransactionError(
1020 "Explicit transaction still active. A caller may have caught an error."
1023 // Assert that the time to replicate the transaction will be sane.
1024 // If this fails, then all DB transactions will be rollback back together.
1025 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1026 if ( $limit > 0 && $time > $limit ) {
1027 throw new DBTransactionSizeError(
1029 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1033 // If a connection sits idle while slow queries execute on another, that connection
1034 // may end up dropped before the commit round is reached. Ping servers to detect this.
1035 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1036 throw new DBTransactionError(
1038 "A connection to the {$conn->getDBname()} database was lost before commit."
1044 public function beginMasterChanges( $fname = __METHOD__
) {
1045 if ( $this->trxRoundId
!== false ) {
1046 throw new DBTransactionError(
1048 "$fname: Transaction round '{$this->trxRoundId}' already started."
1051 $this->trxRoundId
= $fname;
1054 $this->forEachOpenMasterConnection(
1055 function ( DatabaseBase
$conn ) use ( $fname, &$failures ) {
1056 $conn->setTrxEndCallbackSuppression( true );
1058 $conn->flushSnapshot( $fname );
1059 } catch ( DBError
$e ) {
1060 call_user_func( $this->errorLogger
, $e );
1061 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1063 $conn->setTrxEndCallbackSuppression( false );
1064 $this->applyTransactionRoundFlags( $conn );
1069 throw new DBExpectedError(
1071 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1076 public function commitMasterChanges( $fname = __METHOD__
) {
1079 $restore = ( $this->trxRoundId
!== false );
1080 $this->trxRoundId
= false;
1081 $this->forEachOpenMasterConnection(
1082 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1084 if ( $conn->writesOrCallbacksPending() ) {
1085 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1086 } elseif ( $restore ) {
1087 $conn->flushSnapshot( $fname );
1089 } catch ( DBError
$e ) {
1090 call_user_func( $this->errorLogger
, $e );
1091 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1094 $this->undoTransactionRoundFlags( $conn );
1100 throw new DBExpectedError(
1102 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1107 public function runMasterPostTrxCallbacks( $type ) {
1108 $e = null; // first exception
1109 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) use ( $type, &$e ) {
1110 $conn->setTrxEndCallbackSuppression( false );
1111 if ( $conn->writesOrCallbacksPending() ) {
1112 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1113 // (which finished its callbacks already). Warn and recover in this case. Let the
1114 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1115 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1117 } elseif ( $conn->trxLevel() ) {
1118 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1119 // thus leaving an implicit read-only transaction open at this point. It
1120 // also happens if onTransactionIdle() callbacks leave implicit transactions
1121 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1122 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1126 $conn->runOnTransactionIdleCallbacks( $type );
1127 } catch ( Exception
$ex ) {
1131 $conn->runTransactionListenerCallbacks( $type );
1132 } catch ( Exception
$ex ) {
1140 public function rollbackMasterChanges( $fname = __METHOD__
) {
1141 $restore = ( $this->trxRoundId
!== false );
1142 $this->trxRoundId
= false;
1143 $this->forEachOpenMasterConnection(
1144 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1145 if ( $conn->writesOrCallbacksPending() ) {
1146 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1149 $this->undoTransactionRoundFlags( $conn );
1155 public function suppressTransactionEndCallbacks() {
1156 $this->forEachOpenMasterConnection( function ( DatabaseBase
$conn ) {
1157 $conn->setTrxEndCallbackSuppression( true );
1162 * @param IDatabase $conn
1164 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1165 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1166 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1167 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1168 $conn->setFlag( DBO_TRX
, $conn::REMEMBER_PRIOR
);
1169 // If config has explicitly requested DBO_TRX be either on or off by not
1170 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1171 // for things like blob stores (ExternalStore) which want auto-commit mode.
1176 * @param IDatabase $conn
1178 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1179 if ( $conn->getFlag( DBO_DEFAULT
) ) {
1180 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1184 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1185 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1186 $conn->flushSnapshot( __METHOD__
);
1190 public function hasMasterConnection() {
1191 return $this->isOpen( $this->getWriterIndex() );
1194 public function hasMasterChanges() {
1196 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1197 $pending |
= $conn->writesOrCallbacksPending();
1200 return (bool)$pending;
1203 public function lastMasterChangeTimestamp() {
1205 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1206 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1212 public function hasOrMadeRecentMasterChanges( $age = null ) {
1213 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1215 return ( $this->hasMasterChanges()
1216 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1219 public function pendingMasterChangeCallers() {
1221 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1222 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1228 public function getLaggedReplicaMode( $domain = false ) {
1229 // No-op if there is only one DB (also avoids recursion)
1230 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1232 // See if laggedReplicaMode gets set
1233 $conn = $this->getConnection( DB_REPLICA
, false, $domain );
1234 $this->reuseConnection( $conn );
1235 } catch ( DBConnectionError
$e ) {
1236 // Avoid expensive re-connect attempts and failures
1237 $this->allReplicasDownMode
= true;
1238 $this->laggedReplicaMode
= true;
1242 return $this->laggedReplicaMode
;
1246 * @param bool $domain
1248 * @deprecated 1.28; use getLaggedReplicaMode()
1250 public function getLaggedSlaveMode( $domain = false ) {
1251 return $this->getLaggedReplicaMode( $domain );
1254 public function laggedReplicaUsed() {
1255 return $this->laggedReplicaMode
;
1261 * @deprecated Since 1.28; use laggedReplicaUsed()
1263 public function laggedSlaveUsed() {
1264 return $this->laggedReplicaUsed();
1267 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1268 if ( $this->readOnlyReason
!== false ) {
1269 return $this->readOnlyReason
;
1270 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1271 if ( $this->allReplicasDownMode
) {
1272 return 'The database has been automatically locked ' .
1273 'until the replica database servers become available';
1275 return 'The database has been automatically locked ' .
1276 'while the replica database servers catch up to the master.';
1278 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1279 return 'The database master is running in read-only mode.';
1286 * @param string $domain Domain ID, or false for the current domain
1287 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1290 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1291 $cache = $this->wanCache
;
1292 $masterServer = $this->getServerName( $this->getWriterIndex() );
1294 return (bool)$cache->getWithSetCallback(
1295 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1296 self
::TTL_CACHE_READONLY
,
1297 function () use ( $domain, $conn ) {
1298 $this->trxProfiler
->setSilenced( true );
1300 $dbw = $conn ?
: $this->getConnection( DB_MASTER
, [], $domain );
1301 $readOnly = (int)$dbw->serverIsReadOnly();
1302 } catch ( DBError
$e ) {
1305 $this->trxProfiler
->setSilenced( false );
1308 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1312 public function allowLagged( $mode = null ) {
1313 if ( $mode === null ) {
1314 return $this->mAllowLagged
;
1316 $this->mAllowLagged
= $mode;
1318 return $this->mAllowLagged
;
1321 public function pingAll() {
1323 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1324 if ( !$conn->ping() ) {
1332 public function forEachOpenConnection( $callback, array $params = [] ) {
1333 foreach ( $this->mConns
as $connsByServer ) {
1334 foreach ( $connsByServer as $serverConns ) {
1335 foreach ( $serverConns as $conn ) {
1336 $mergedParams = array_merge( [ $conn ], $params );
1337 call_user_func_array( $callback, $mergedParams );
1343 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1344 $masterIndex = $this->getWriterIndex();
1345 foreach ( $this->mConns
as $connsByServer ) {
1346 if ( isset( $connsByServer[$masterIndex] ) ) {
1347 /** @var IDatabase $conn */
1348 foreach ( $connsByServer[$masterIndex] as $conn ) {
1349 $mergedParams = array_merge( [ $conn ], $params );
1350 call_user_func_array( $callback, $mergedParams );
1356 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1357 foreach ( $this->mConns
as $connsByServer ) {
1358 foreach ( $connsByServer as $i => $serverConns ) {
1359 if ( $i === $this->getWriterIndex() ) {
1360 continue; // skip master
1362 foreach ( $serverConns as $conn ) {
1363 $mergedParams = array_merge( [ $conn ], $params );
1364 call_user_func_array( $callback, $mergedParams );
1370 public function getMaxLag( $domain = false ) {
1375 if ( $this->getServerCount() <= 1 ) {
1376 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1379 $lagTimes = $this->getLagTimes( $domain );
1380 foreach ( $lagTimes as $i => $lag ) {
1381 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1383 $host = $this->mServers
[$i]['host'];
1388 return [ $host, $maxLag, $maxIndex ];
1391 public function getLagTimes( $domain = false ) {
1392 if ( $this->getServerCount() <= 1 ) {
1393 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1396 $knownLagTimes = []; // map of (server index => 0 seconds)
1397 $indexesWithLag = [];
1398 foreach ( $this->mServers
as $i => $server ) {
1399 if ( empty( $server['is static'] ) ) {
1400 $indexesWithLag[] = $i; // DB server might have replication lag
1402 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1406 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1409 public function safeGetLag( IDatabase
$conn ) {
1410 if ( $this->getServerCount() == 1 ) {
1413 return $conn->getLag();
1417 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1418 if ( $this->getServerCount() == 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1419 return true; // server is not a replica DB
1422 $pos = $pos ?
: $this->getConnection( DB_MASTER
)->getMasterPos();
1423 if ( !( $pos instanceof DBMasterPos
) ) {
1424 return false; // something is misconfigured
1427 $result = $conn->masterPosWait( $pos, $timeout );
1428 if ( $result == -1 ||
is_null( $result ) ) {
1429 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1430 $this->replLogger
->warning( "$msg" );
1433 $this->replLogger
->info( __METHOD__
. ": Done" );
1440 public function clearLagTimeCache() {
1441 $this->getLoadMonitor()->clearCaches();
1444 public function setTransactionListener( $name, callable
$callback = null ) {
1446 $this->trxRecurringCallbacks
[$name] = $callback;
1448 unset( $this->trxRecurringCallbacks
[$name] );
1450 $this->forEachOpenMasterConnection(
1451 function ( IDatabase
$conn ) use ( $name, $callback ) {
1452 $conn->setTransactionListener( $name, $callback );
1457 public function setTableAliases( array $aliases ) {
1458 $this->tableAliases
= $aliases;
1461 public function setDomainPrefix( $prefix ) {
1462 $this->localDomain
= new DatabaseDomain(
1463 $this->localDomain
->getDatabase(),
1468 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1469 $db->tablePrefix( $prefix );