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 namespace Wikimedia\Rdbms
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
27 use Wikimedia\ScopedCallback
;
30 use MaintainableDBConnRef
;
38 use DBUnexpectedError
;
39 use DBTransactionError
;
40 use DBTransactionSizeError
;
41 use DBConnectionError
;
42 use InvalidArgumentException
;
47 * Database connection, tracking, load balancing, and transaction manager for a cluster
51 class LoadBalancer
implements ILoadBalancer
{
52 /** @var array[] Map of (server index => server config array) */
54 /** @var \Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
56 /** @var float[] Map of (server index => weight) */
58 /** @var array[] Map of (group => server index => weight) */
60 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
61 private $mAllowLagged;
62 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
63 private $mWaitTimeout;
64 /** @var array The LoadMonitor configuration */
65 private $loadMonitorConfig;
66 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
67 private $tableAliases = [];
69 /** @var ILoadMonitor */
71 /** @var ChronologyProtector|null */
77 /** @var WANObjectCache */
79 /** @var object|string Class name or object With profileIn/profileOut methods */
81 /** @var TransactionProfiler */
82 protected $trxProfiler;
83 /** @var LoggerInterface */
84 protected $replLogger;
85 /** @var LoggerInterface */
86 protected $connLogger;
87 /** @var LoggerInterface */
88 protected $queryLogger;
89 /** @var LoggerInterface */
90 protected $perfLogger;
92 /** @var \Database Database connection that caused a problem */
93 private $errorConnection;
94 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
96 /** @var bool|DBMasterPos False if not set */
98 /** @var bool Whether the generic reader fell back to a lagged replica DB */
99 private $laggedReplicaMode = false;
100 /** @var bool Whether the generic reader fell back to a lagged replica DB */
101 private $allReplicasDownMode = false;
102 /** @var string The last DB selection or connection error */
103 private $mLastError = 'Unknown error';
104 /** @var string|bool Reason the LB is read-only or false if not */
105 private $readOnlyReason = false;
106 /** @var integer Total connections opened */
107 private $connsOpened = 0;
108 /** @var string|bool String if a requested DBO_TRX transaction round is active */
109 private $trxRoundId = false;
110 /** @var array[] Map of (name => callable) */
111 private $trxRecurringCallbacks = [];
112 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
113 private $localDomain;
114 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
115 private $localDomainIdAlias;
116 /** @var string Current server name */
118 /** @var bool Whether this PHP instance is for a CLI script */
120 /** @var string Agent name for query profiling */
123 /** @var callable Exception logger */
124 private $errorLogger;
127 private $disabled = false;
129 private $chronProtInitialized = false;
131 /** @var integer Warn when this many connection are held */
132 const CONN_HELD_WARN_THRESHOLD
= 10;
134 /** @var integer Default 'max lag' when unspecified */
135 const MAX_LAG_DEFAULT
= 10;
136 /** @var integer Seconds to cache master server read-only status */
137 const TTL_CACHE_READONLY
= 5;
139 public function __construct( array $params ) {
140 if ( !isset( $params['servers'] ) ) {
141 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
143 $this->mServers
= $params['servers'];
145 $this->localDomain
= isset( $params['localDomain'] )
146 ? DatabaseDomain
::newFromId( $params['localDomain'] )
147 : DatabaseDomain
::newUnspecified();
148 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
149 // always true, gracefully handle the case when they fail to account for escaping.
150 if ( $this->localDomain
->getTablePrefix() != '' ) {
151 $this->localDomainIdAlias
=
152 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
154 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
157 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
159 $this->mReadIndex
= -1;
166 $this->mWaitForPos
= false;
167 $this->mAllowLagged
= false;
169 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
170 $this->readOnlyReason
= $params['readOnlyReason'];
173 if ( isset( $params['loadMonitor'] ) ) {
174 $this->loadMonitorConfig
= $params['loadMonitor'];
176 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
179 foreach ( $params['servers'] as $i => $server ) {
180 $this->mLoads
[$i] = $server['load'];
181 if ( isset( $server['groupLoads'] ) ) {
182 foreach ( $server['groupLoads'] as $group => $ratio ) {
183 if ( !isset( $this->mGroupLoads
[$group] ) ) {
184 $this->mGroupLoads
[$group] = [];
186 $this->mGroupLoads
[$group][$i] = $ratio;
191 if ( isset( $params['srvCache'] ) ) {
192 $this->srvCache
= $params['srvCache'];
194 $this->srvCache
= new EmptyBagOStuff();
196 if ( isset( $params['memCache'] ) ) {
197 $this->memCache
= $params['memCache'];
199 $this->memCache
= new EmptyBagOStuff();
201 if ( isset( $params['wanCache'] ) ) {
202 $this->wanCache
= $params['wanCache'];
204 $this->wanCache
= WANObjectCache
::newEmpty();
206 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
207 if ( isset( $params['trxProfiler'] ) ) {
208 $this->trxProfiler
= $params['trxProfiler'];
210 $this->trxProfiler
= new TransactionProfiler();
213 $this->errorLogger
= isset( $params['errorLogger'] )
214 ?
$params['errorLogger']
215 : function ( Exception
$e ) {
216 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
219 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
220 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
223 $this->host
= isset( $params['hostname'] )
224 ?
$params['hostname']
225 : ( gethostname() ?
: 'unknown' );
226 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
227 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
229 if ( isset( $params['chronologyProtector'] ) ) {
230 $this->chronProt
= $params['chronologyProtector'];
235 * Get a LoadMonitor instance
237 * @return ILoadMonitor
239 private function getLoadMonitor() {
240 if ( !isset( $this->loadMonitor
) ) {
242 'LoadMonitor' => LoadMonitor
::class,
243 'LoadMonitorNull' => LoadMonitorNull
::class,
244 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
247 $class = $this->loadMonitorConfig
['class'];
248 if ( isset( $compat[$class] ) ) {
249 $class = $compat[$class];
252 $this->loadMonitor
= new $class(
253 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
254 $this->loadMonitor
->setLogger( $this->replLogger
);
257 return $this->loadMonitor
;
261 * @param array $loads
262 * @param bool|string $domain Domain to get non-lagged for
263 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
264 * @return bool|int|string
266 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
267 $lags = $this->getLagTimes( $domain );
269 # Unset excessively lagged servers
270 foreach ( $lags as $i => $lag ) {
272 # How much lag this server nominally is allowed to have
273 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
274 ?
$this->mServers
[$i]['max lag']
275 : self
::MAX_LAG_DEFAULT
; // default
276 # Constrain that futher by $maxLag argument
277 $maxServerLag = min( $maxServerLag, $maxLag );
279 $host = $this->getServerName( $i );
280 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
281 $this->replLogger
->error(
282 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
284 } elseif ( $lag > $maxServerLag ) {
285 $this->replLogger
->warning(
286 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
287 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
294 # Find out if all the replica DBs with non-zero load are lagged
296 foreach ( $loads as $load ) {
300 # No appropriate DB servers except maybe the master and some replica DBs with zero load
301 # Do NOT use the master
302 # Instead, this function will return false, triggering read-only mode,
303 # and a lagged replica DB will be used instead.
307 if ( count( $loads ) == 0 ) {
311 # Return a random representative of the remainder
312 return ArrayUtils
::pickRandom( $loads );
315 public function getReaderIndex( $group = false, $domain = false ) {
316 if ( count( $this->mServers
) == 1 ) {
317 # Skip the load balancing if there's only one server
318 return $this->getWriterIndex();
319 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
320 # Shortcut if generic reader exists already
321 return $this->mReadIndex
;
324 # Find the relevant load array
325 if ( $group !== false ) {
326 if ( isset( $this->mGroupLoads
[$group] ) ) {
327 $nonErrorLoads = $this->mGroupLoads
[$group];
329 # No loads for this group, return false and the caller can use some other group
330 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
335 $nonErrorLoads = $this->mLoads
;
338 if ( !count( $nonErrorLoads ) ) {
339 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
342 # Scale the configured load ratios according to the dynamic load if supported
343 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
345 $laggedReplicaMode = false;
347 # No server found yet
349 # First try quickly looking through the available servers for a server that
351 $currentLoads = $nonErrorLoads;
352 while ( count( $currentLoads ) ) {
353 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
354 $i = ArrayUtils
::pickRandom( $currentLoads );
357 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
358 # ChronologyProtecter causes mWaitForPos to be set via sessions.
359 # This triggers doWait() after connect, so it's especially good to
360 # avoid lagged servers so as to avoid just blocking in that method.
361 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
362 # Aim for <= 1 second of waiting (being too picky can backfire)
363 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
365 if ( $i === false ) {
366 # Any server with less lag than it's 'max lag' param is preferable
367 $i = $this->getRandomNonLagged( $currentLoads, $domain );
369 if ( $i === false && count( $currentLoads ) != 0 ) {
370 # All replica DBs lagged. Switch to read-only mode
371 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
372 $i = ArrayUtils
::pickRandom( $currentLoads );
373 $laggedReplicaMode = true;
377 if ( $i === false ) {
378 # pickRandom() returned false
379 # This is permanent and means the configuration or the load monitor
380 # wants us to return false.
381 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
386 $serverName = $this->getServerName( $i );
387 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
389 $conn = $this->openConnection( $i, $domain );
391 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
392 unset( $nonErrorLoads[$i] );
393 unset( $currentLoads[$i] );
398 // Decrement reference counter, we are finished with this connection.
399 // It will be incremented for the caller later.
400 if ( $domain !== false ) {
401 $this->reuseConnection( $conn );
408 # If all servers were down, quit now
409 if ( !count( $nonErrorLoads ) ) {
410 $this->connLogger
->error( "All servers down" );
413 if ( $i !== false ) {
414 # Replica DB connection successful.
415 # Wait for the session master pos for a short time.
416 if ( $this->mWaitForPos
&& $i > 0 ) {
419 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
420 $this->mReadIndex
= $i;
421 # Record if the generic reader index is in "lagged replica DB" mode
422 if ( $laggedReplicaMode ) {
423 $this->laggedReplicaMode
= true;
426 $serverName = $this->getServerName( $i );
427 $this->connLogger
->debug(
428 __METHOD__
. ": using server $serverName for group '$group'" );
434 public function waitFor( $pos ) {
435 $oldPos = $this->mWaitForPos
;
436 $this->mWaitForPos
= $pos;
438 // If a generic reader connection was already established, then wait now
439 $i = $this->mReadIndex
;
441 if ( !$this->doWait( $i ) ) {
442 $this->laggedReplicaMode
= true;
446 // Restore the older position if it was higher
447 $this->setWaitForPositionIfHigher( $oldPos );
450 public function waitForOne( $pos, $timeout = null ) {
451 $oldPos = $this->mWaitForPos
;
452 $this->mWaitForPos
= $pos;
454 $i = $this->mReadIndex
;
456 // Pick a generic replica DB if there isn't one yet
457 $readLoads = $this->mLoads
;
458 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
459 $readLoads = array_filter( $readLoads ); // with non-zero load
460 $i = ArrayUtils
::pickRandom( $readLoads );
464 $ok = $this->doWait( $i, true, $timeout );
466 $ok = true; // no applicable loads
469 // Restore the older position if it was higher
470 $this->setWaitForPositionIfHigher( $oldPos );
475 public function waitForAll( $pos, $timeout = null ) {
476 $oldPos = $this->mWaitForPos
;
477 $this->mWaitForPos
= $pos;
478 $serverCount = count( $this->mServers
);
481 for ( $i = 1; $i < $serverCount; $i++
) {
482 if ( $this->mLoads
[$i] > 0 ) {
483 $ok = $this->doWait( $i, true, $timeout ) && $ok;
487 // Restore the older position if it was higher
488 $this->setWaitForPositionIfHigher( $oldPos );
494 * @param DBMasterPos|bool $pos
496 private function setWaitForPositionIfHigher( $pos ) {
501 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
502 $this->mWaitForPos
= $pos;
508 * @return IDatabase|bool
510 public function getAnyOpenConnection( $i ) {
511 foreach ( $this->mConns
as $connsByServer ) {
512 if ( !empty( $connsByServer[$i] ) ) {
513 /** @var $serverConns IDatabase[] */
514 $serverConns = $connsByServer[$i];
516 return reset( $serverConns );
524 * Wait for a given replica DB to catch up to the master pos stored in $this
525 * @param int $index Server index
526 * @param bool $open Check the server even if a new connection has to be made
527 * @param int $timeout Max seconds to wait; default is mWaitTimeout
530 protected function doWait( $index, $open = false, $timeout = null ) {
531 $close = false; // close the connection afterwards
533 // Check if we already know that the DB has reached this point
534 $server = $this->getServerName( $index );
535 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
536 /** @var DBMasterPos $knownReachedPos */
537 $knownReachedPos = $this->srvCache
->get( $key );
539 $knownReachedPos instanceof DBMasterPos
&&
540 $knownReachedPos->hasReached( $this->mWaitForPos
)
542 $this->replLogger
->debug( __METHOD__
.
543 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
547 // Find a connection to wait on, creating one if needed and allowed
548 $conn = $this->getAnyOpenConnection( $index );
551 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
555 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
557 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
561 // Avoid connection spam in waitForAll() when connections
562 // are made just for the sake of doing this lag check.
567 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
568 $timeout = $timeout ?
: $this->mWaitTimeout
;
569 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
571 if ( $result == -1 ||
is_null( $result ) ) {
572 // Timed out waiting for replica DB, use master instead
573 $this->replLogger
->warning(
574 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
575 [ 'host' => $server ]
579 $this->replLogger
->info( __METHOD__
. ": Done" );
581 // Remember that the DB reached this point
582 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
586 $this->closeConnection( $conn );
593 * @see ILoadBalancer::getConnection()
596 * @param array $groups
597 * @param bool $domain
599 * @throws DBConnectionError
601 public function getConnection( $i, $groups = [], $domain = false ) {
602 if ( $i === null ||
$i === false ) {
603 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
604 ' with invalid server index' );
607 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
608 $domain = false; // local connection requested
611 $groups = ( $groups === false ||
$groups === [] )
612 ?
[ false ] // check one "group": the generic pool
615 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
616 $oldConnsOpened = $this->connsOpened
; // connections open now
618 if ( $i == self
::DB_MASTER
) {
619 $i = $this->getWriterIndex();
621 # Try to find an available server in any the query groups (in order)
622 foreach ( $groups as $group ) {
623 $groupIndex = $this->getReaderIndex( $group, $domain );
624 if ( $groupIndex !== false ) {
631 # Operation-based index
632 if ( $i == self
::DB_REPLICA
) {
633 $this->mLastError
= 'Unknown error'; // reset error string
634 # Try the general server pool if $groups are unavailable.
635 $i = ( $groups === [ false ] )
636 ?
false // don't bother with this if that is what was tried above
637 : $this->getReaderIndex( false, $domain );
638 # Couldn't find a working server in getReaderIndex()?
639 if ( $i === false ) {
640 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
641 // Throw an exception
642 $this->reportConnectionError();
643 return null; // not reached
647 # Now we have an explicit index into the servers array
648 $conn = $this->openConnection( $i, $domain );
650 // Throw an exception
651 $this->reportConnectionError();
652 return null; // not reached
655 # Profile any new connections that happen
656 if ( $this->connsOpened
> $oldConnsOpened ) {
657 $host = $conn->getServer();
658 $dbname = $conn->getDBname();
659 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
663 # Make master-requested DB handles inherit any read-only mode setting
664 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
670 public function reuseConnection( $conn ) {
671 $serverIndex = $conn->getLBInfo( 'serverIndex' );
672 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
673 if ( $serverIndex === null ||
$refCount === null ) {
675 * This can happen in code like:
676 * foreach ( $dbs as $db ) {
677 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
679 * $lb->reuseConnection( $conn );
681 * When a connection to the local DB is opened in this way, reuseConnection()
685 } elseif ( $conn instanceof DBConnRef
) {
686 // DBConnRef already handles calling reuseConnection() and only passes the live
687 // Database instance to this method. Any caller passing in a DBConnRef is broken.
688 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
689 ( new RuntimeException() )->getTraceAsString() );
694 if ( $this->disabled
) {
695 return; // DBConnRef handle probably survived longer than the LoadBalancer
698 $domain = $conn->getDomainID();
699 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
700 throw new InvalidArgumentException( __METHOD__
.
701 ": connection $serverIndex/$domain not found; it may have already been freed." );
702 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
703 throw new InvalidArgumentException( __METHOD__
.
704 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
706 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
707 if ( $refCount <= 0 ) {
708 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
709 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
710 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
711 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
713 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
715 $this->connLogger
->debug( __METHOD__
.
716 ": reference count for $serverIndex/$domain reduced to $refCount" );
720 public function getConnectionRef( $db, $groups = [], $domain = false ) {
721 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
723 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
726 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
727 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
729 return new DBConnRef( $this, [ $db, $groups, $domain ] );
732 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
733 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
735 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
739 * @see ILoadBalancer::openConnection()
742 * @param bool $domain
743 * @return bool|Database
744 * @throws DBAccessError
746 public function openConnection( $i, $domain = false ) {
747 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
748 $domain = false; // local connection requested
751 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
752 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
753 // Load CP positions before connecting so that doWait() triggers later if needed
754 $this->chronProtInitialized
= true;
755 $this->chronProt
->initLB( $this );
758 if ( $domain !== false ) {
759 $conn = $this->openForeignConnection( $i, $domain );
760 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
761 $conn = $this->mConns
['local'][$i][0];
763 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
764 throw new InvalidArgumentException( "No server with index '$i'." );
766 // Open a new connection
767 $server = $this->mServers
[$i];
768 $server['serverIndex'] = $i;
769 $conn = $this->reallyOpenConnection( $server, false );
770 $serverName = $this->getServerName( $i );
771 if ( $conn->isOpen() ) {
772 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
773 $this->mConns
['local'][$i][0] = $conn;
775 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
776 $this->errorConnection
= $conn;
781 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
782 // Connection was made but later unrecoverably lost for some reason.
783 // Do not return a handle that will just throw exceptions on use,
784 // but let the calling code (e.g. getReaderIndex) try another server.
785 // See DatabaseMyslBase::ping() for how this can happen.
786 $this->errorConnection
= $conn;
794 * Open a connection to a foreign DB, or return one if it is already open.
796 * Increments a reference count on the returned connection which locks the
797 * connection to the requested domain. This reference count can be
798 * decremented by calling reuseConnection().
800 * If a connection is open to the appropriate server already, but with the wrong
801 * database, it will be switched to the right database and returned, as long as
802 * it has been freed first with reuseConnection().
804 * On error, returns false, and the connection which caused the
805 * error will be available via $this->errorConnection.
807 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
809 * @param int $i Server index
810 * @param string $domain Domain ID to open
813 private function openForeignConnection( $i, $domain ) {
814 $domainInstance = DatabaseDomain
::newFromId( $domain );
815 $dbName = $domainInstance->getDatabase();
816 $prefix = $domainInstance->getTablePrefix();
818 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
819 // Reuse an already-used connection
820 $conn = $this->mConns
['foreignUsed'][$i][$domain];
821 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
822 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
823 // Reuse a free connection for the same domain
824 $conn = $this->mConns
['foreignFree'][$i][$domain];
825 unset( $this->mConns
['foreignFree'][$i][$domain] );
826 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
827 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
828 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
829 // Reuse a connection from another domain
830 $conn = reset( $this->mConns
['foreignFree'][$i] );
831 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
832 // The empty string as a DB name means "don't care".
833 // DatabaseMysqlBase::open() already handle this on connection.
834 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
835 $this->mLastError
= "Error selecting database '$dbName' on server " .
836 $conn->getServer() . " from client host {$this->host}";
837 $this->errorConnection
= $conn;
840 $conn->tablePrefix( $prefix );
841 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
842 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
843 $this->connLogger
->debug( __METHOD__
.
844 ": reusing free connection from $oldDomain for $domain" );
847 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
848 throw new InvalidArgumentException( "No server with index '$i'." );
850 // Open a new connection
851 $server = $this->mServers
[$i];
852 $server['serverIndex'] = $i;
853 $server['foreignPoolRefCount'] = 0;
854 $server['foreign'] = true;
855 $conn = $this->reallyOpenConnection( $server, $dbName );
856 if ( !$conn->isOpen() ) {
857 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
858 $this->errorConnection
= $conn;
861 $conn->tablePrefix( $prefix );
862 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
863 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
867 // Increment reference count
868 if ( $conn instanceof IDatabase
) {
869 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
870 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
877 * Test if the specified index represents an open connection
879 * @param int $index Server index
883 private function isOpen( $index ) {
884 if ( !is_integer( $index ) ) {
888 return (bool)$this->getAnyOpenConnection( $index );
892 * Really opens a connection. Uncached.
893 * Returns a Database object whether or not the connection was successful.
896 * @param array $server
897 * @param string|bool $dbNameOverride Use "" to not select any database
899 * @throws DBAccessError
900 * @throws InvalidArgumentException
902 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
903 if ( $this->disabled
) {
904 throw new DBAccessError();
907 if ( $dbNameOverride !== false ) {
908 $server['dbname'] = $dbNameOverride;
911 // Let the handle know what the cluster master is (e.g. "db1052")
912 $masterName = $this->getServerName( $this->getWriterIndex() );
913 $server['clusterMasterHost'] = $masterName;
915 // Log when many connection are made on requests
916 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
917 $this->perfLogger
->warning( __METHOD__
. ": " .
918 "{$this->connsOpened}+ connections made (master=$masterName)" );
921 $server['srvCache'] = $this->srvCache
;
922 // Set loggers and profilers
923 $server['connLogger'] = $this->connLogger
;
924 $server['queryLogger'] = $this->queryLogger
;
925 $server['errorLogger'] = $this->errorLogger
;
926 $server['profiler'] = $this->profiler
;
927 $server['trxProfiler'] = $this->trxProfiler
;
928 // Use the same agent and PHP mode for all DB handles
929 $server['cliMode'] = $this->cliMode
;
930 $server['agent'] = $this->agent
;
931 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
932 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
933 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
935 // Create a live connection object
937 $db = Database
::factory( $server['type'], $server );
938 } catch ( DBConnectionError
$e ) {
939 // FIXME: This is probably the ugliest thing I have ever done to
940 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
944 $db->setLBInfo( $server );
945 $db->setLazyMasterHandle(
946 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
948 $db->setTableAliases( $this->tableAliases
);
950 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
951 if ( $this->trxRoundId
!== false ) {
952 $this->applyTransactionRoundFlags( $db );
954 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
955 $db->setTransactionListener( $name, $callback );
963 * @throws DBConnectionError
965 private function reportConnectionError() {
966 $conn = $this->errorConnection
; // the connection which caused the error
968 'method' => __METHOD__
,
969 'last_error' => $this->mLastError
,
972 if ( $conn instanceof IDatabase
) {
973 $context['db_server'] = $conn->getServer();
974 $this->connLogger
->warning(
975 "Connection error: {last_error} ({db_server})",
979 // throws DBConnectionError
980 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
982 // No last connection, probably due to all servers being too busy
983 $this->connLogger
->error(
984 "LB failure with no last connection. Connection error: {last_error}",
988 // If all servers were busy, mLastError will contain something sensible
989 throw new DBConnectionError( null, $this->mLastError
);
993 public function getWriterIndex() {
997 public function haveIndex( $i ) {
998 return array_key_exists( $i, $this->mServers
);
1001 public function isNonZeroLoad( $i ) {
1002 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1005 public function getServerCount() {
1006 return count( $this->mServers
);
1009 public function getServerName( $i ) {
1010 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1011 $name = $this->mServers
[$i]['hostName'];
1012 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1013 $name = $this->mServers
[$i]['host'];
1018 return ( $name != '' ) ?
$name : 'localhost';
1021 public function getServerInfo( $i ) {
1022 if ( isset( $this->mServers
[$i] ) ) {
1023 return $this->mServers
[$i];
1029 public function setServerInfo( $i, array $serverInfo ) {
1030 $this->mServers
[$i] = $serverInfo;
1033 public function getMasterPos() {
1034 # If this entire request was served from a replica DB without opening a connection to the
1035 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1036 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1037 if ( !$masterConn ) {
1038 $serverCount = count( $this->mServers
);
1039 for ( $i = 1; $i < $serverCount; $i++
) {
1040 $conn = $this->getAnyOpenConnection( $i );
1042 return $conn->getReplicaPos();
1046 return $masterConn->getMasterPos();
1052 public function disable() {
1054 $this->disabled
= true;
1057 public function closeAll() {
1058 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1059 $host = $conn->getServer();
1060 $this->connLogger
->debug( "Closing connection to database '$host'." );
1066 'foreignFree' => [],
1067 'foreignUsed' => [],
1069 $this->connsOpened
= 0;
1072 public function closeConnection( IDatabase
$conn ) {
1073 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1074 foreach ( $this->mConns
as $type => $connsByServer ) {
1075 if ( !isset( $connsByServer[$serverIndex] ) ) {
1079 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1080 if ( $conn === $trackedConn ) {
1081 $host = $this->getServerName( $i );
1082 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1083 unset( $this->mConns
[$type][$serverIndex][$i] );
1084 --$this->connsOpened
;
1093 public function commitAll( $fname = __METHOD__
) {
1096 $restore = ( $this->trxRoundId
!== false );
1097 $this->trxRoundId
= false;
1098 $this->forEachOpenConnection(
1099 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1101 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1102 } catch ( DBError
$e ) {
1103 call_user_func( $this->errorLogger
, $e );
1104 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1106 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1107 $this->undoTransactionRoundFlags( $conn );
1113 throw new DBExpectedError(
1115 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1120 public function finalizeMasterChanges() {
1121 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1122 // Any error should cause all DB transactions to be rolled back together
1123 $conn->setTrxEndCallbackSuppression( false );
1124 $conn->runOnTransactionPreCommitCallbacks();
1125 // Defer post-commit callbacks until COMMIT finishes for all DBs
1126 $conn->setTrxEndCallbackSuppression( true );
1130 public function approveMasterChanges( array $options ) {
1131 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1132 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1133 // If atomic sections or explicit transactions are still open, some caller must have
1134 // caught an exception but failed to properly rollback any changes. Detect that and
1135 // throw and error (causing rollback).
1136 if ( $conn->explicitTrxActive() ) {
1137 throw new DBTransactionError(
1139 "Explicit transaction still active. A caller may have caught an error."
1142 // Assert that the time to replicate the transaction will be sane.
1143 // If this fails, then all DB transactions will be rollback back together.
1144 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1145 if ( $limit > 0 && $time > $limit ) {
1146 throw new DBTransactionSizeError(
1148 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1152 // If a connection sits idle while slow queries execute on another, that connection
1153 // may end up dropped before the commit round is reached. Ping servers to detect this.
1154 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1155 throw new DBTransactionError(
1157 "A connection to the {$conn->getDBname()} database was lost before commit."
1163 public function beginMasterChanges( $fname = __METHOD__
) {
1164 if ( $this->trxRoundId
!== false ) {
1165 throw new DBTransactionError(
1167 "$fname: Transaction round '{$this->trxRoundId}' already started."
1170 $this->trxRoundId
= $fname;
1173 $this->forEachOpenMasterConnection(
1174 function ( Database
$conn ) use ( $fname, &$failures ) {
1175 $conn->setTrxEndCallbackSuppression( true );
1177 $conn->flushSnapshot( $fname );
1178 } catch ( DBError
$e ) {
1179 call_user_func( $this->errorLogger
, $e );
1180 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1182 $conn->setTrxEndCallbackSuppression( false );
1183 $this->applyTransactionRoundFlags( $conn );
1188 throw new DBExpectedError(
1190 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1195 public function commitMasterChanges( $fname = __METHOD__
) {
1198 /** @noinspection PhpUnusedLocalVariableInspection */
1199 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1201 $restore = ( $this->trxRoundId
!== false );
1202 $this->trxRoundId
= false;
1203 $this->forEachOpenMasterConnection(
1204 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1206 if ( $conn->writesOrCallbacksPending() ) {
1207 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1208 } elseif ( $restore ) {
1209 $conn->flushSnapshot( $fname );
1211 } catch ( DBError
$e ) {
1212 call_user_func( $this->errorLogger
, $e );
1213 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1216 $this->undoTransactionRoundFlags( $conn );
1222 throw new DBExpectedError(
1224 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1229 public function runMasterPostTrxCallbacks( $type ) {
1230 $e = null; // first exception
1231 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1232 $conn->setTrxEndCallbackSuppression( false );
1233 if ( $conn->writesOrCallbacksPending() ) {
1234 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1235 // (which finished its callbacks already). Warn and recover in this case. Let the
1236 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1237 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1239 } elseif ( $conn->trxLevel() ) {
1240 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1241 // thus leaving an implicit read-only transaction open at this point. It
1242 // also happens if onTransactionIdle() callbacks leave implicit transactions
1243 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1244 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1248 $conn->runOnTransactionIdleCallbacks( $type );
1249 } catch ( Exception
$ex ) {
1253 $conn->runTransactionListenerCallbacks( $type );
1254 } catch ( Exception
$ex ) {
1262 public function rollbackMasterChanges( $fname = __METHOD__
) {
1263 $restore = ( $this->trxRoundId
!== false );
1264 $this->trxRoundId
= false;
1265 $this->forEachOpenMasterConnection(
1266 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1267 if ( $conn->writesOrCallbacksPending() ) {
1268 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1271 $this->undoTransactionRoundFlags( $conn );
1277 public function suppressTransactionEndCallbacks() {
1278 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1279 $conn->setTrxEndCallbackSuppression( true );
1284 * @param IDatabase $conn
1286 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1287 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1288 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1289 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1290 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1291 // If config has explicitly requested DBO_TRX be either on or off by not
1292 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1293 // for things like blob stores (ExternalStore) which want auto-commit mode.
1298 * @param IDatabase $conn
1300 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1301 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1302 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1306 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1307 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1308 $conn->flushSnapshot( __METHOD__
);
1312 public function hasMasterConnection() {
1313 return $this->isOpen( $this->getWriterIndex() );
1316 public function hasMasterChanges() {
1318 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1319 $pending |
= $conn->writesOrCallbacksPending();
1322 return (bool)$pending;
1325 public function lastMasterChangeTimestamp() {
1327 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1328 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1334 public function hasOrMadeRecentMasterChanges( $age = null ) {
1335 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1337 return ( $this->hasMasterChanges()
1338 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1341 public function pendingMasterChangeCallers() {
1343 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1344 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1350 public function getLaggedReplicaMode( $domain = false ) {
1351 // No-op if there is only one DB (also avoids recursion)
1352 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1354 // See if laggedReplicaMode gets set
1355 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1356 $this->reuseConnection( $conn );
1357 } catch ( DBConnectionError
$e ) {
1358 // Avoid expensive re-connect attempts and failures
1359 $this->allReplicasDownMode
= true;
1360 $this->laggedReplicaMode
= true;
1364 return $this->laggedReplicaMode
;
1368 * @param bool $domain
1370 * @deprecated 1.28; use getLaggedReplicaMode()
1372 public function getLaggedSlaveMode( $domain = false ) {
1373 return $this->getLaggedReplicaMode( $domain );
1376 public function laggedReplicaUsed() {
1377 return $this->laggedReplicaMode
;
1383 * @deprecated Since 1.28; use laggedReplicaUsed()
1385 public function laggedSlaveUsed() {
1386 return $this->laggedReplicaUsed();
1389 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1390 if ( $this->readOnlyReason
!== false ) {
1391 return $this->readOnlyReason
;
1392 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1393 if ( $this->allReplicasDownMode
) {
1394 return 'The database has been automatically locked ' .
1395 'until the replica database servers become available';
1397 return 'The database has been automatically locked ' .
1398 'while the replica database servers catch up to the master.';
1400 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1401 return 'The database master is running in read-only mode.';
1408 * @param string $domain Domain ID, or false for the current domain
1409 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1412 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1413 $cache = $this->wanCache
;
1414 $masterServer = $this->getServerName( $this->getWriterIndex() );
1416 return (bool)$cache->getWithSetCallback(
1417 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1418 self
::TTL_CACHE_READONLY
,
1419 function () use ( $domain, $conn ) {
1420 $old = $this->trxProfiler
->setSilenced( true );
1422 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1423 $readOnly = (int)$dbw->serverIsReadOnly();
1425 $this->reuseConnection( $dbw );
1427 } catch ( DBError
$e ) {
1430 $this->trxProfiler
->setSilenced( $old );
1433 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1437 public function allowLagged( $mode = null ) {
1438 if ( $mode === null ) {
1439 return $this->mAllowLagged
;
1441 $this->mAllowLagged
= $mode;
1443 return $this->mAllowLagged
;
1446 public function pingAll() {
1448 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1449 if ( !$conn->ping() ) {
1457 public function forEachOpenConnection( $callback, array $params = [] ) {
1458 foreach ( $this->mConns
as $connsByServer ) {
1459 foreach ( $connsByServer as $serverConns ) {
1460 foreach ( $serverConns as $conn ) {
1461 $mergedParams = array_merge( [ $conn ], $params );
1462 call_user_func_array( $callback, $mergedParams );
1468 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1469 $masterIndex = $this->getWriterIndex();
1470 foreach ( $this->mConns
as $connsByServer ) {
1471 if ( isset( $connsByServer[$masterIndex] ) ) {
1472 /** @var IDatabase $conn */
1473 foreach ( $connsByServer[$masterIndex] as $conn ) {
1474 $mergedParams = array_merge( [ $conn ], $params );
1475 call_user_func_array( $callback, $mergedParams );
1481 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1482 foreach ( $this->mConns
as $connsByServer ) {
1483 foreach ( $connsByServer as $i => $serverConns ) {
1484 if ( $i === $this->getWriterIndex() ) {
1485 continue; // skip master
1487 foreach ( $serverConns as $conn ) {
1488 $mergedParams = array_merge( [ $conn ], $params );
1489 call_user_func_array( $callback, $mergedParams );
1495 public function getMaxLag( $domain = false ) {
1500 if ( $this->getServerCount() <= 1 ) {
1501 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1504 $lagTimes = $this->getLagTimes( $domain );
1505 foreach ( $lagTimes as $i => $lag ) {
1506 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1508 $host = $this->mServers
[$i]['host'];
1513 return [ $host, $maxLag, $maxIndex ];
1516 public function getLagTimes( $domain = false ) {
1517 if ( $this->getServerCount() <= 1 ) {
1518 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1521 $knownLagTimes = []; // map of (server index => 0 seconds)
1522 $indexesWithLag = [];
1523 foreach ( $this->mServers
as $i => $server ) {
1524 if ( empty( $server['is static'] ) ) {
1525 $indexesWithLag[] = $i; // DB server might have replication lag
1527 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1531 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1534 public function safeGetLag( IDatabase
$conn ) {
1535 if ( $this->getServerCount() <= 1 ) {
1538 return $conn->getLag();
1543 * @param IDatabase $conn
1544 * @param DBMasterPos|bool $pos
1545 * @param int $timeout
1548 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1549 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1550 return true; // server is not a replica DB
1554 // Get the current master position, opening a connection if needed
1555 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1556 if ( $masterConn ) {
1557 $pos = $masterConn->getMasterPos();
1559 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1560 $pos = $masterConn->getMasterPos();
1561 $this->closeConnection( $masterConn );
1565 if ( $pos instanceof DBMasterPos
) {
1566 $result = $conn->masterPosWait( $pos, $timeout );
1567 if ( $result == -1 ||
is_null( $result ) ) {
1568 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1569 $this->replLogger
->warning( "$msg" );
1572 $this->replLogger
->info( __METHOD__
. ": Done" );
1576 $ok = false; // something is misconfigured
1577 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1583 public function setTransactionListener( $name, callable
$callback = null ) {
1585 $this->trxRecurringCallbacks
[$name] = $callback;
1587 unset( $this->trxRecurringCallbacks
[$name] );
1589 $this->forEachOpenMasterConnection(
1590 function ( IDatabase
$conn ) use ( $name, $callback ) {
1591 $conn->setTransactionListener( $name, $callback );
1596 public function setTableAliases( array $aliases ) {
1597 $this->tableAliases
= $aliases;
1600 public function setDomainPrefix( $prefix ) {
1601 if ( $this->mConns
['foreignUsed'] ) {
1602 // Do not switch connections to explicit foreign domains unless marked as free
1604 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1605 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1607 $domains = implode( ', ', $domains );
1608 throw new DBUnexpectedError( null,
1609 "Foreign domain connections are still in use ($domains)." );
1612 $this->localDomain
= new DatabaseDomain(
1613 $this->localDomain
->getDatabase(),
1618 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1619 $db->tablePrefix( $prefix );
1624 * Make PHP ignore user aborts/disconnects until the returned
1625 * value leaves scope. This returns null and does nothing in CLI mode.
1627 * @return ScopedCallback|null
1629 final protected function getScopedPHPBehaviorForCommit() {
1630 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1631 $old = ignore_user_abort( true ); // avoid half-finished operations
1632 return new ScopedCallback( function () use ( $old ) {
1633 ignore_user_abort( $old );
1640 function __destruct() {
1641 // Avoid connection leaks for sanity
1646 class_alias( LoadBalancer
::class, 'LoadBalancer' );