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
;
35 use DBUnexpectedError
;
36 use DBTransactionError
;
37 use DBTransactionSizeError
;
38 use DBConnectionError
;
39 use InvalidArgumentException
;
44 * Database connection, tracking, load balancing, and transaction manager for a cluster
48 class LoadBalancer
implements ILoadBalancer
{
49 /** @var array[] Map of (server index => server config array) */
51 /** @var Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
53 /** @var float[] Map of (server index => weight) */
55 /** @var array[] Map of (group => server index => weight) */
57 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
58 private $mAllowLagged;
59 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
60 private $mWaitTimeout;
61 /** @var array The LoadMonitor configuration */
62 private $loadMonitorConfig;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 private $tableAliases = [];
66 /** @var ILoadMonitor */
68 /** @var ChronologyProtector|null */
74 /** @var WANObjectCache */
76 /** @var object|string Class name or object With profileIn/profileOut methods */
78 /** @var TransactionProfiler */
79 protected $trxProfiler;
80 /** @var LoggerInterface */
81 protected $replLogger;
82 /** @var LoggerInterface */
83 protected $connLogger;
84 /** @var LoggerInterface */
85 protected $queryLogger;
86 /** @var LoggerInterface */
87 protected $perfLogger;
89 /** @var Database DB connection object that caused a problem */
90 private $errorConnection;
91 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
93 /** @var bool|DBMasterPos False if not set */
95 /** @var bool Whether the generic reader fell back to a lagged replica DB */
96 private $laggedReplicaMode = false;
97 /** @var bool Whether the generic reader fell back to a lagged replica DB */
98 private $allReplicasDownMode = false;
99 /** @var string The last DB selection or connection error */
100 private $mLastError = 'Unknown error';
101 /** @var string|bool Reason the LB is read-only or false if not */
102 private $readOnlyReason = false;
103 /** @var integer Total connections opened */
104 private $connsOpened = 0;
105 /** @var string|bool String if a requested DBO_TRX transaction round is active */
106 private $trxRoundId = false;
107 /** @var array[] Map of (name => callable) */
108 private $trxRecurringCallbacks = [];
109 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
110 private $localDomain;
111 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
112 private $localDomainIdAlias;
113 /** @var string Current server name */
115 /** @var bool Whether this PHP instance is for a CLI script */
117 /** @var string Agent name for query profiling */
120 /** @var callable Exception logger */
121 private $errorLogger;
124 private $disabled = false;
126 private $chronProtInitialized = false;
128 /** @var integer Warn when this many connection are held */
129 const CONN_HELD_WARN_THRESHOLD
= 10;
131 /** @var integer Default 'max lag' when unspecified */
132 const MAX_LAG_DEFAULT
= 10;
133 /** @var integer Seconds to cache master server read-only status */
134 const TTL_CACHE_READONLY
= 5;
136 public function __construct( array $params ) {
137 if ( !isset( $params['servers'] ) ) {
138 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
140 $this->mServers
= $params['servers'];
142 $this->localDomain
= isset( $params['localDomain'] )
143 ? DatabaseDomain
::newFromId( $params['localDomain'] )
144 : DatabaseDomain
::newUnspecified();
145 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
146 // always true, gracefully handle the case when they fail to account for escaping.
147 if ( $this->localDomain
->getTablePrefix() != '' ) {
148 $this->localDomainIdAlias
=
149 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
151 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
154 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
156 $this->mReadIndex
= -1;
163 $this->mWaitForPos
= false;
164 $this->mAllowLagged
= false;
166 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
167 $this->readOnlyReason
= $params['readOnlyReason'];
170 if ( isset( $params['loadMonitor'] ) ) {
171 $this->loadMonitorConfig
= $params['loadMonitor'];
173 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
176 foreach ( $params['servers'] as $i => $server ) {
177 $this->mLoads
[$i] = $server['load'];
178 if ( isset( $server['groupLoads'] ) ) {
179 foreach ( $server['groupLoads'] as $group => $ratio ) {
180 if ( !isset( $this->mGroupLoads
[$group] ) ) {
181 $this->mGroupLoads
[$group] = [];
183 $this->mGroupLoads
[$group][$i] = $ratio;
188 if ( isset( $params['srvCache'] ) ) {
189 $this->srvCache
= $params['srvCache'];
191 $this->srvCache
= new EmptyBagOStuff();
193 if ( isset( $params['memCache'] ) ) {
194 $this->memCache
= $params['memCache'];
196 $this->memCache
= new EmptyBagOStuff();
198 if ( isset( $params['wanCache'] ) ) {
199 $this->wanCache
= $params['wanCache'];
201 $this->wanCache
= WANObjectCache
::newEmpty();
203 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
204 if ( isset( $params['trxProfiler'] ) ) {
205 $this->trxProfiler
= $params['trxProfiler'];
207 $this->trxProfiler
= new TransactionProfiler();
210 $this->errorLogger
= isset( $params['errorLogger'] )
211 ?
$params['errorLogger']
212 : function ( Exception
$e ) {
213 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
216 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
217 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
220 $this->host
= isset( $params['hostname'] )
221 ?
$params['hostname']
222 : ( gethostname() ?
: 'unknown' );
223 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
224 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
226 if ( isset( $params['chronologyProtector'] ) ) {
227 $this->chronProt
= $params['chronologyProtector'];
232 * Get a LoadMonitor instance
234 * @return ILoadMonitor
236 private function getLoadMonitor() {
237 if ( !isset( $this->loadMonitor
) ) {
239 'LoadMonitor' => LoadMonitor
::class,
240 'LoadMonitorNull' => LoadMonitorNull
::class,
241 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
244 $class = $this->loadMonitorConfig
['class'];
245 if ( isset( $compat[$class] ) ) {
246 $class = $compat[$class];
249 $this->loadMonitor
= new $class(
250 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
251 $this->loadMonitor
->setLogger( $this->replLogger
);
254 return $this->loadMonitor
;
258 * @param array $loads
259 * @param bool|string $domain Domain to get non-lagged for
260 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
261 * @return bool|int|string
263 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
264 $lags = $this->getLagTimes( $domain );
266 # Unset excessively lagged servers
267 foreach ( $lags as $i => $lag ) {
269 # How much lag this server nominally is allowed to have
270 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
271 ?
$this->mServers
[$i]['max lag']
272 : self
::MAX_LAG_DEFAULT
; // default
273 # Constrain that futher by $maxLag argument
274 $maxServerLag = min( $maxServerLag, $maxLag );
276 $host = $this->getServerName( $i );
277 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
278 $this->replLogger
->error(
279 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
281 } elseif ( $lag > $maxServerLag ) {
282 $this->replLogger
->warning(
283 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
284 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
291 # Find out if all the replica DBs with non-zero load are lagged
293 foreach ( $loads as $load ) {
297 # No appropriate DB servers except maybe the master and some replica DBs with zero load
298 # Do NOT use the master
299 # Instead, this function will return false, triggering read-only mode,
300 # and a lagged replica DB will be used instead.
304 if ( count( $loads ) == 0 ) {
308 # Return a random representative of the remainder
309 return ArrayUtils
::pickRandom( $loads );
312 public function getReaderIndex( $group = false, $domain = false ) {
313 if ( count( $this->mServers
) == 1 ) {
314 # Skip the load balancing if there's only one server
315 return $this->getWriterIndex();
316 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
317 # Shortcut if generic reader exists already
318 return $this->mReadIndex
;
321 # Find the relevant load array
322 if ( $group !== false ) {
323 if ( isset( $this->mGroupLoads
[$group] ) ) {
324 $nonErrorLoads = $this->mGroupLoads
[$group];
326 # No loads for this group, return false and the caller can use some other group
327 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
332 $nonErrorLoads = $this->mLoads
;
335 if ( !count( $nonErrorLoads ) ) {
336 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
339 # Scale the configured load ratios according to the dynamic load if supported
340 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
342 $laggedReplicaMode = false;
344 # No server found yet
346 # First try quickly looking through the available servers for a server that
348 $currentLoads = $nonErrorLoads;
349 while ( count( $currentLoads ) ) {
350 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
351 $i = ArrayUtils
::pickRandom( $currentLoads );
354 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
355 # ChronologyProtecter causes mWaitForPos to be set via sessions.
356 # This triggers doWait() after connect, so it's especially good to
357 # avoid lagged servers so as to avoid just blocking in that method.
358 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
359 # Aim for <= 1 second of waiting (being too picky can backfire)
360 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
362 if ( $i === false ) {
363 # Any server with less lag than it's 'max lag' param is preferable
364 $i = $this->getRandomNonLagged( $currentLoads, $domain );
366 if ( $i === false && count( $currentLoads ) != 0 ) {
367 # All replica DBs lagged. Switch to read-only mode
368 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
369 $i = ArrayUtils
::pickRandom( $currentLoads );
370 $laggedReplicaMode = true;
374 if ( $i === false ) {
375 # pickRandom() returned false
376 # This is permanent and means the configuration or the load monitor
377 # wants us to return false.
378 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
383 $serverName = $this->getServerName( $i );
384 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
386 $conn = $this->openConnection( $i, $domain );
388 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
389 unset( $nonErrorLoads[$i] );
390 unset( $currentLoads[$i] );
395 // Decrement reference counter, we are finished with this connection.
396 // It will be incremented for the caller later.
397 if ( $domain !== false ) {
398 $this->reuseConnection( $conn );
405 # If all servers were down, quit now
406 if ( !count( $nonErrorLoads ) ) {
407 $this->connLogger
->error( "All servers down" );
410 if ( $i !== false ) {
411 # Replica DB connection successful.
412 # Wait for the session master pos for a short time.
413 if ( $this->mWaitForPos
&& $i > 0 ) {
414 # When LoadBalancer::waitFor() set mWaitForPos, the wait will happen here.
415 # Be sure to update laggedReplicaMode accordingly for consistency.
416 if ( !$this->doWait( $i ) ) {
417 $laggedReplicaMode = true;
420 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
421 $this->mReadIndex
= $i;
422 # Record if the generic reader index is in "lagged replica DB" mode
423 if ( $laggedReplicaMode ) {
424 $this->laggedReplicaMode
= true;
427 $serverName = $this->getServerName( $i );
428 $this->connLogger
->debug(
429 __METHOD__
. ": using server $serverName for group '$group'" );
435 public function waitFor( $pos ) {
436 $oldPos = $this->mWaitForPos
;
438 $this->mWaitForPos
= $pos;
439 // If a generic reader connection was already established, then wait now
440 $i = $this->mReadIndex
;
442 if ( !$this->doWait( $i ) ) {
443 $this->laggedReplicaMode
= true;
447 // Restore the older position if it was higher since this is used for lag-protection
448 $this->setWaitForPositionIfHigher( $oldPos );
452 public function waitForOne( $pos, $timeout = null ) {
453 $oldPos = $this->mWaitForPos
;
455 $this->mWaitForPos
= $pos;
457 $i = $this->mReadIndex
;
459 // Pick a generic replica DB if there isn't one yet
460 $readLoads = $this->mLoads
;
461 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
462 $readLoads = array_filter( $readLoads ); // with non-zero load
463 $i = ArrayUtils
::pickRandom( $readLoads );
467 $ok = $this->doWait( $i, true, $timeout );
469 $ok = true; // no applicable loads
472 # Restore the old position, as this is not used for lag-protection but for throttling
473 $this->mWaitForPos
= $oldPos;
479 public function waitForAll( $pos, $timeout = null ) {
480 $oldPos = $this->mWaitForPos
;
482 $this->mWaitForPos
= $pos;
483 $serverCount = count( $this->mServers
);
486 for ( $i = 1; $i < $serverCount; $i++
) {
487 if ( $this->mLoads
[$i] > 0 ) {
488 $ok = $this->doWait( $i, true, $timeout ) && $ok;
492 # Restore the old position, as this is not used for lag-protection but for throttling
493 $this->mWaitForPos
= $oldPos;
500 * @param DBMasterPos|bool $pos
502 private function setWaitForPositionIfHigher( $pos ) {
507 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
508 $this->mWaitForPos
= $pos;
514 * @return IDatabase|bool
516 public function getAnyOpenConnection( $i ) {
517 foreach ( $this->mConns
as $connsByServer ) {
518 if ( !empty( $connsByServer[$i] ) ) {
519 /** @var $serverConns IDatabase[] */
520 $serverConns = $connsByServer[$i];
522 return reset( $serverConns );
530 * Wait for a given replica DB to catch up to the master pos stored in $this
531 * @param int $index Server index
532 * @param bool $open Check the server even if a new connection has to be made
533 * @param int $timeout Max seconds to wait; default is mWaitTimeout
536 protected function doWait( $index, $open = false, $timeout = null ) {
537 $close = false; // close the connection afterwards
539 // Check if we already know that the DB has reached this point
540 $server = $this->getServerName( $index );
541 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
542 /** @var DBMasterPos $knownReachedPos */
543 $knownReachedPos = $this->srvCache
->get( $key );
545 $knownReachedPos instanceof DBMasterPos
&&
546 $knownReachedPos->hasReached( $this->mWaitForPos
)
548 $this->replLogger
->debug( __METHOD__
.
549 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
553 // Find a connection to wait on, creating one if needed and allowed
554 $conn = $this->getAnyOpenConnection( $index );
557 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
561 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
563 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
567 // Avoid connection spam in waitForAll() when connections
568 // are made just for the sake of doing this lag check.
573 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
574 $timeout = $timeout ?
: $this->mWaitTimeout
;
575 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
577 if ( $result == -1 ||
is_null( $result ) ) {
578 // Timed out waiting for replica DB, use master instead
579 $this->replLogger
->warning(
580 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
581 [ 'host' => $server ]
585 $this->replLogger
->info( __METHOD__
. ": Done" );
587 // Remember that the DB reached this point
588 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
592 $this->closeConnection( $conn );
599 * @see ILoadBalancer::getConnection()
602 * @param array $groups
603 * @param bool $domain
605 * @throws DBConnectionError
607 public function getConnection( $i, $groups = [], $domain = false ) {
608 if ( $i === null ||
$i === false ) {
609 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
610 ' with invalid server index' );
613 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
614 $domain = false; // local connection requested
617 $groups = ( $groups === false ||
$groups === [] )
618 ?
[ false ] // check one "group": the generic pool
621 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
622 $oldConnsOpened = $this->connsOpened
; // connections open now
624 if ( $i == self
::DB_MASTER
) {
625 $i = $this->getWriterIndex();
627 # Try to find an available server in any the query groups (in order)
628 foreach ( $groups as $group ) {
629 $groupIndex = $this->getReaderIndex( $group, $domain );
630 if ( $groupIndex !== false ) {
637 # Operation-based index
638 if ( $i == self
::DB_REPLICA
) {
639 $this->mLastError
= 'Unknown error'; // reset error string
640 # Try the general server pool if $groups are unavailable.
641 $i = ( $groups === [ false ] )
642 ?
false // don't bother with this if that is what was tried above
643 : $this->getReaderIndex( false, $domain );
644 # Couldn't find a working server in getReaderIndex()?
645 if ( $i === false ) {
646 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
647 // Throw an exception
648 $this->reportConnectionError();
649 return null; // not reached
653 # Now we have an explicit index into the servers array
654 $conn = $this->openConnection( $i, $domain );
656 // Throw an exception
657 $this->reportConnectionError();
658 return null; // not reached
661 # Profile any new connections that happen
662 if ( $this->connsOpened
> $oldConnsOpened ) {
663 $host = $conn->getServer();
664 $dbname = $conn->getDBname();
665 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
669 # Make master-requested DB handles inherit any read-only mode setting
670 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
676 public function reuseConnection( $conn ) {
677 $serverIndex = $conn->getLBInfo( 'serverIndex' );
678 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
679 if ( $serverIndex === null ||
$refCount === null ) {
681 * This can happen in code like:
682 * foreach ( $dbs as $db ) {
683 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
685 * $lb->reuseConnection( $conn );
687 * When a connection to the local DB is opened in this way, reuseConnection()
691 } elseif ( $conn instanceof DBConnRef
) {
692 // DBConnRef already handles calling reuseConnection() and only passes the live
693 // Database instance to this method. Any caller passing in a DBConnRef is broken.
694 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
695 ( new RuntimeException() )->getTraceAsString() );
700 if ( $this->disabled
) {
701 return; // DBConnRef handle probably survived longer than the LoadBalancer
704 $domain = $conn->getDomainID();
705 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
706 throw new InvalidArgumentException( __METHOD__
.
707 ": connection $serverIndex/$domain not found; it may have already been freed." );
708 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
709 throw new InvalidArgumentException( __METHOD__
.
710 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
712 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
713 if ( $refCount <= 0 ) {
714 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
715 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
716 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
717 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
719 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
721 $this->connLogger
->debug( __METHOD__
.
722 ": reference count for $serverIndex/$domain reduced to $refCount" );
726 public function getConnectionRef( $db, $groups = [], $domain = false ) {
727 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
729 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
732 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
733 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
735 return new DBConnRef( $this, [ $db, $groups, $domain ] );
738 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
739 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
741 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
745 * @see ILoadBalancer::openConnection()
748 * @param bool $domain
749 * @return bool|Database
750 * @throws DBAccessError
752 public function openConnection( $i, $domain = false ) {
753 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
754 $domain = false; // local connection requested
757 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
758 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
759 // Load CP positions before connecting so that doWait() triggers later if needed
760 $this->chronProtInitialized
= true;
761 $this->chronProt
->initLB( $this );
764 if ( $domain !== false ) {
765 $conn = $this->openForeignConnection( $i, $domain );
766 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
767 $conn = $this->mConns
['local'][$i][0];
769 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
770 throw new InvalidArgumentException( "No server with index '$i'." );
772 // Open a new connection
773 $server = $this->mServers
[$i];
774 $server['serverIndex'] = $i;
775 $conn = $this->reallyOpenConnection( $server, false );
776 $serverName = $this->getServerName( $i );
777 if ( $conn->isOpen() ) {
778 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
779 $this->mConns
['local'][$i][0] = $conn;
781 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
782 $this->errorConnection
= $conn;
787 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
788 // Connection was made but later unrecoverably lost for some reason.
789 // Do not return a handle that will just throw exceptions on use,
790 // but let the calling code (e.g. getReaderIndex) try another server.
791 // See DatabaseMyslBase::ping() for how this can happen.
792 $this->errorConnection
= $conn;
800 * Open a connection to a foreign DB, or return one if it is already open.
802 * Increments a reference count on the returned connection which locks the
803 * connection to the requested domain. This reference count can be
804 * decremented by calling reuseConnection().
806 * If a connection is open to the appropriate server already, but with the wrong
807 * database, it will be switched to the right database and returned, as long as
808 * it has been freed first with reuseConnection().
810 * On error, returns false, and the connection which caused the
811 * error will be available via $this->errorConnection.
813 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
815 * @param int $i Server index
816 * @param string $domain Domain ID to open
819 private function openForeignConnection( $i, $domain ) {
820 $domainInstance = DatabaseDomain
::newFromId( $domain );
821 $dbName = $domainInstance->getDatabase();
822 $prefix = $domainInstance->getTablePrefix();
824 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
825 // Reuse an already-used connection
826 $conn = $this->mConns
['foreignUsed'][$i][$domain];
827 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
828 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
829 // Reuse a free connection for the same domain
830 $conn = $this->mConns
['foreignFree'][$i][$domain];
831 unset( $this->mConns
['foreignFree'][$i][$domain] );
832 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
833 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
834 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
835 // Reuse a connection from another domain
836 $conn = reset( $this->mConns
['foreignFree'][$i] );
837 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
838 // The empty string as a DB name means "don't care".
839 // DatabaseMysqlBase::open() already handle this on connection.
840 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
841 $this->mLastError
= "Error selecting database '$dbName' on server " .
842 $conn->getServer() . " from client host {$this->host}";
843 $this->errorConnection
= $conn;
846 $conn->tablePrefix( $prefix );
847 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
848 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
849 $this->connLogger
->debug( __METHOD__
.
850 ": reusing free connection from $oldDomain for $domain" );
853 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
854 throw new InvalidArgumentException( "No server with index '$i'." );
856 // Open a new connection
857 $server = $this->mServers
[$i];
858 $server['serverIndex'] = $i;
859 $server['foreignPoolRefCount'] = 0;
860 $server['foreign'] = true;
861 $conn = $this->reallyOpenConnection( $server, $dbName );
862 if ( !$conn->isOpen() ) {
863 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
864 $this->errorConnection
= $conn;
867 $conn->tablePrefix( $prefix );
868 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
869 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
873 // Increment reference count
874 if ( $conn instanceof IDatabase
) {
875 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
876 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
883 * Test if the specified index represents an open connection
885 * @param int $index Server index
889 private function isOpen( $index ) {
890 if ( !is_integer( $index ) ) {
894 return (bool)$this->getAnyOpenConnection( $index );
898 * Really opens a connection. Uncached.
899 * Returns a Database object whether or not the connection was successful.
902 * @param array $server
903 * @param string|bool $dbNameOverride Use "" to not select any database
905 * @throws DBAccessError
906 * @throws InvalidArgumentException
908 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
909 if ( $this->disabled
) {
910 throw new DBAccessError();
913 if ( $dbNameOverride !== false ) {
914 $server['dbname'] = $dbNameOverride;
917 // Let the handle know what the cluster master is (e.g. "db1052")
918 $masterName = $this->getServerName( $this->getWriterIndex() );
919 $server['clusterMasterHost'] = $masterName;
921 // Log when many connection are made on requests
922 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
923 $this->perfLogger
->warning( __METHOD__
. ": " .
924 "{$this->connsOpened}+ connections made (master=$masterName)" );
927 $server['srvCache'] = $this->srvCache
;
928 // Set loggers and profilers
929 $server['connLogger'] = $this->connLogger
;
930 $server['queryLogger'] = $this->queryLogger
;
931 $server['errorLogger'] = $this->errorLogger
;
932 $server['profiler'] = $this->profiler
;
933 $server['trxProfiler'] = $this->trxProfiler
;
934 // Use the same agent and PHP mode for all DB handles
935 $server['cliMode'] = $this->cliMode
;
936 $server['agent'] = $this->agent
;
937 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
938 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
939 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
941 // Create a live connection object
943 $db = Database
::factory( $server['type'], $server );
944 } catch ( DBConnectionError
$e ) {
945 // FIXME: This is probably the ugliest thing I have ever done to
946 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
950 $db->setLBInfo( $server );
951 $db->setLazyMasterHandle(
952 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
954 $db->setTableAliases( $this->tableAliases
);
956 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
957 if ( $this->trxRoundId
!== false ) {
958 $this->applyTransactionRoundFlags( $db );
960 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
961 $db->setTransactionListener( $name, $callback );
969 * @throws DBConnectionError
971 private function reportConnectionError() {
972 $conn = $this->errorConnection
; // the connection which caused the error
974 'method' => __METHOD__
,
975 'last_error' => $this->mLastError
,
978 if ( $conn instanceof IDatabase
) {
979 $context['db_server'] = $conn->getServer();
980 $this->connLogger
->warning(
981 "Connection error: {last_error} ({db_server})",
985 // throws DBConnectionError
986 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
988 // No last connection, probably due to all servers being too busy
989 $this->connLogger
->error(
990 "LB failure with no last connection. Connection error: {last_error}",
994 // If all servers were busy, mLastError will contain something sensible
995 throw new DBConnectionError( null, $this->mLastError
);
999 public function getWriterIndex() {
1003 public function haveIndex( $i ) {
1004 return array_key_exists( $i, $this->mServers
);
1007 public function isNonZeroLoad( $i ) {
1008 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1011 public function getServerCount() {
1012 return count( $this->mServers
);
1015 public function getServerName( $i ) {
1016 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1017 $name = $this->mServers
[$i]['hostName'];
1018 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1019 $name = $this->mServers
[$i]['host'];
1024 return ( $name != '' ) ?
$name : 'localhost';
1027 public function getServerInfo( $i ) {
1028 if ( isset( $this->mServers
[$i] ) ) {
1029 return $this->mServers
[$i];
1035 public function setServerInfo( $i, array $serverInfo ) {
1036 $this->mServers
[$i] = $serverInfo;
1039 public function getMasterPos() {
1040 # If this entire request was served from a replica DB without opening a connection to the
1041 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1042 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1043 if ( !$masterConn ) {
1044 $serverCount = count( $this->mServers
);
1045 for ( $i = 1; $i < $serverCount; $i++
) {
1046 $conn = $this->getAnyOpenConnection( $i );
1048 return $conn->getReplicaPos();
1052 return $masterConn->getMasterPos();
1058 public function disable() {
1060 $this->disabled
= true;
1063 public function closeAll() {
1064 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1065 $host = $conn->getServer();
1066 $this->connLogger
->debug( "Closing connection to database '$host'." );
1072 'foreignFree' => [],
1073 'foreignUsed' => [],
1075 $this->connsOpened
= 0;
1078 public function closeConnection( IDatabase
$conn ) {
1079 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1080 foreach ( $this->mConns
as $type => $connsByServer ) {
1081 if ( !isset( $connsByServer[$serverIndex] ) ) {
1085 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1086 if ( $conn === $trackedConn ) {
1087 $host = $this->getServerName( $i );
1088 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1089 unset( $this->mConns
[$type][$serverIndex][$i] );
1090 --$this->connsOpened
;
1099 public function commitAll( $fname = __METHOD__
) {
1102 $restore = ( $this->trxRoundId
!== false );
1103 $this->trxRoundId
= false;
1104 $this->forEachOpenConnection(
1105 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1107 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1108 } catch ( DBError
$e ) {
1109 call_user_func( $this->errorLogger
, $e );
1110 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1112 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1113 $this->undoTransactionRoundFlags( $conn );
1119 throw new DBExpectedError(
1121 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1126 public function finalizeMasterChanges() {
1127 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1128 // Any error should cause all DB transactions to be rolled back together
1129 $conn->setTrxEndCallbackSuppression( false );
1130 $conn->runOnTransactionPreCommitCallbacks();
1131 // Defer post-commit callbacks until COMMIT finishes for all DBs
1132 $conn->setTrxEndCallbackSuppression( true );
1136 public function approveMasterChanges( array $options ) {
1137 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1138 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1139 // If atomic sections or explicit transactions are still open, some caller must have
1140 // caught an exception but failed to properly rollback any changes. Detect that and
1141 // throw and error (causing rollback).
1142 if ( $conn->explicitTrxActive() ) {
1143 throw new DBTransactionError(
1145 "Explicit transaction still active. A caller may have caught an error."
1148 // Assert that the time to replicate the transaction will be sane.
1149 // If this fails, then all DB transactions will be rollback back together.
1150 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1151 if ( $limit > 0 && $time > $limit ) {
1152 throw new DBTransactionSizeError(
1154 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1158 // If a connection sits idle while slow queries execute on another, that connection
1159 // may end up dropped before the commit round is reached. Ping servers to detect this.
1160 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1161 throw new DBTransactionError(
1163 "A connection to the {$conn->getDBname()} database was lost before commit."
1169 public function beginMasterChanges( $fname = __METHOD__
) {
1170 if ( $this->trxRoundId
!== false ) {
1171 throw new DBTransactionError(
1173 "$fname: Transaction round '{$this->trxRoundId}' already started."
1176 $this->trxRoundId
= $fname;
1179 $this->forEachOpenMasterConnection(
1180 function ( Database
$conn ) use ( $fname, &$failures ) {
1181 $conn->setTrxEndCallbackSuppression( true );
1183 $conn->flushSnapshot( $fname );
1184 } catch ( DBError
$e ) {
1185 call_user_func( $this->errorLogger
, $e );
1186 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1188 $conn->setTrxEndCallbackSuppression( false );
1189 $this->applyTransactionRoundFlags( $conn );
1194 throw new DBExpectedError(
1196 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1201 public function commitMasterChanges( $fname = __METHOD__
) {
1204 /** @noinspection PhpUnusedLocalVariableInspection */
1205 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1207 $restore = ( $this->trxRoundId
!== false );
1208 $this->trxRoundId
= false;
1209 $this->forEachOpenMasterConnection(
1210 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1212 if ( $conn->writesOrCallbacksPending() ) {
1213 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1214 } elseif ( $restore ) {
1215 $conn->flushSnapshot( $fname );
1217 } catch ( DBError
$e ) {
1218 call_user_func( $this->errorLogger
, $e );
1219 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1222 $this->undoTransactionRoundFlags( $conn );
1228 throw new DBExpectedError(
1230 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1235 public function runMasterPostTrxCallbacks( $type ) {
1236 $e = null; // first exception
1237 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1238 $conn->setTrxEndCallbackSuppression( false );
1239 if ( $conn->writesOrCallbacksPending() ) {
1240 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1241 // (which finished its callbacks already). Warn and recover in this case. Let the
1242 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1243 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1245 } elseif ( $conn->trxLevel() ) {
1246 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1247 // thus leaving an implicit read-only transaction open at this point. It
1248 // also happens if onTransactionIdle() callbacks leave implicit transactions
1249 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1250 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1254 $conn->runOnTransactionIdleCallbacks( $type );
1255 } catch ( Exception
$ex ) {
1259 $conn->runTransactionListenerCallbacks( $type );
1260 } catch ( Exception
$ex ) {
1268 public function rollbackMasterChanges( $fname = __METHOD__
) {
1269 $restore = ( $this->trxRoundId
!== false );
1270 $this->trxRoundId
= false;
1271 $this->forEachOpenMasterConnection(
1272 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1273 if ( $conn->writesOrCallbacksPending() ) {
1274 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1277 $this->undoTransactionRoundFlags( $conn );
1283 public function suppressTransactionEndCallbacks() {
1284 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1285 $conn->setTrxEndCallbackSuppression( true );
1290 * @param IDatabase $conn
1292 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1293 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1294 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1295 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1296 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1297 // If config has explicitly requested DBO_TRX be either on or off by not
1298 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1299 // for things like blob stores (ExternalStore) which want auto-commit mode.
1304 * @param IDatabase $conn
1306 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1307 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1308 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1312 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1313 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1314 $conn->flushSnapshot( __METHOD__
);
1318 public function hasMasterConnection() {
1319 return $this->isOpen( $this->getWriterIndex() );
1322 public function hasMasterChanges() {
1324 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1325 $pending |
= $conn->writesOrCallbacksPending();
1328 return (bool)$pending;
1331 public function lastMasterChangeTimestamp() {
1333 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1334 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1340 public function hasOrMadeRecentMasterChanges( $age = null ) {
1341 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1343 return ( $this->hasMasterChanges()
1344 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1347 public function pendingMasterChangeCallers() {
1349 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1350 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1356 public function getLaggedReplicaMode( $domain = false ) {
1357 // No-op if there is only one DB (also avoids recursion)
1358 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1360 // See if laggedReplicaMode gets set
1361 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1362 $this->reuseConnection( $conn );
1363 } catch ( DBConnectionError
$e ) {
1364 // Avoid expensive re-connect attempts and failures
1365 $this->allReplicasDownMode
= true;
1366 $this->laggedReplicaMode
= true;
1370 return $this->laggedReplicaMode
;
1374 * @param bool $domain
1376 * @deprecated 1.28; use getLaggedReplicaMode()
1378 public function getLaggedSlaveMode( $domain = false ) {
1379 return $this->getLaggedReplicaMode( $domain );
1382 public function laggedReplicaUsed() {
1383 return $this->laggedReplicaMode
;
1389 * @deprecated Since 1.28; use laggedReplicaUsed()
1391 public function laggedSlaveUsed() {
1392 return $this->laggedReplicaUsed();
1395 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1396 if ( $this->readOnlyReason
!== false ) {
1397 return $this->readOnlyReason
;
1398 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1399 if ( $this->allReplicasDownMode
) {
1400 return 'The database has been automatically locked ' .
1401 'until the replica database servers become available';
1403 return 'The database has been automatically locked ' .
1404 'while the replica database servers catch up to the master.';
1406 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1407 return 'The database master is running in read-only mode.';
1414 * @param string $domain Domain ID, or false for the current domain
1415 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1418 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1419 $cache = $this->wanCache
;
1420 $masterServer = $this->getServerName( $this->getWriterIndex() );
1422 return (bool)$cache->getWithSetCallback(
1423 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1424 self
::TTL_CACHE_READONLY
,
1425 function () use ( $domain, $conn ) {
1426 $old = $this->trxProfiler
->setSilenced( true );
1428 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1429 $readOnly = (int)$dbw->serverIsReadOnly();
1431 $this->reuseConnection( $dbw );
1433 } catch ( DBError
$e ) {
1436 $this->trxProfiler
->setSilenced( $old );
1439 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1443 public function allowLagged( $mode = null ) {
1444 if ( $mode === null ) {
1445 return $this->mAllowLagged
;
1447 $this->mAllowLagged
= $mode;
1449 return $this->mAllowLagged
;
1452 public function pingAll() {
1454 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1455 if ( !$conn->ping() ) {
1463 public function forEachOpenConnection( $callback, array $params = [] ) {
1464 foreach ( $this->mConns
as $connsByServer ) {
1465 foreach ( $connsByServer as $serverConns ) {
1466 foreach ( $serverConns as $conn ) {
1467 $mergedParams = array_merge( [ $conn ], $params );
1468 call_user_func_array( $callback, $mergedParams );
1474 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1475 $masterIndex = $this->getWriterIndex();
1476 foreach ( $this->mConns
as $connsByServer ) {
1477 if ( isset( $connsByServer[$masterIndex] ) ) {
1478 /** @var IDatabase $conn */
1479 foreach ( $connsByServer[$masterIndex] as $conn ) {
1480 $mergedParams = array_merge( [ $conn ], $params );
1481 call_user_func_array( $callback, $mergedParams );
1487 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1488 foreach ( $this->mConns
as $connsByServer ) {
1489 foreach ( $connsByServer as $i => $serverConns ) {
1490 if ( $i === $this->getWriterIndex() ) {
1491 continue; // skip master
1493 foreach ( $serverConns as $conn ) {
1494 $mergedParams = array_merge( [ $conn ], $params );
1495 call_user_func_array( $callback, $mergedParams );
1501 public function getMaxLag( $domain = false ) {
1506 if ( $this->getServerCount() <= 1 ) {
1507 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1510 $lagTimes = $this->getLagTimes( $domain );
1511 foreach ( $lagTimes as $i => $lag ) {
1512 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1514 $host = $this->mServers
[$i]['host'];
1519 return [ $host, $maxLag, $maxIndex ];
1522 public function getLagTimes( $domain = false ) {
1523 if ( $this->getServerCount() <= 1 ) {
1524 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1527 $knownLagTimes = []; // map of (server index => 0 seconds)
1528 $indexesWithLag = [];
1529 foreach ( $this->mServers
as $i => $server ) {
1530 if ( empty( $server['is static'] ) ) {
1531 $indexesWithLag[] = $i; // DB server might have replication lag
1533 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1537 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1540 public function safeGetLag( IDatabase
$conn ) {
1541 if ( $this->getServerCount() <= 1 ) {
1544 return $conn->getLag();
1549 * @param IDatabase $conn
1550 * @param DBMasterPos|bool $pos
1551 * @param int $timeout
1554 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1555 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1556 return true; // server is not a replica DB
1560 // Get the current master position, opening a connection if needed
1561 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1562 if ( $masterConn ) {
1563 $pos = $masterConn->getMasterPos();
1565 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1566 $pos = $masterConn->getMasterPos();
1567 $this->closeConnection( $masterConn );
1571 if ( $pos instanceof DBMasterPos
) {
1572 $result = $conn->masterPosWait( $pos, $timeout );
1573 if ( $result == -1 ||
is_null( $result ) ) {
1574 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1575 $this->replLogger
->warning( "$msg" );
1578 $this->replLogger
->info( __METHOD__
. ": Done" );
1582 $ok = false; // something is misconfigured
1583 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1589 public function setTransactionListener( $name, callable
$callback = null ) {
1591 $this->trxRecurringCallbacks
[$name] = $callback;
1593 unset( $this->trxRecurringCallbacks
[$name] );
1595 $this->forEachOpenMasterConnection(
1596 function ( IDatabase
$conn ) use ( $name, $callback ) {
1597 $conn->setTransactionListener( $name, $callback );
1602 public function setTableAliases( array $aliases ) {
1603 $this->tableAliases
= $aliases;
1606 public function setDomainPrefix( $prefix ) {
1607 if ( $this->mConns
['foreignUsed'] ) {
1608 // Do not switch connections to explicit foreign domains unless marked as free
1610 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1611 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1613 $domains = implode( ', ', $domains );
1614 throw new DBUnexpectedError( null,
1615 "Foreign domain connections are still in use ($domains)." );
1618 $this->localDomain
= new DatabaseDomain(
1619 $this->localDomain
->getDatabase(),
1624 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1625 $db->tablePrefix( $prefix );
1630 * Make PHP ignore user aborts/disconnects until the returned
1631 * value leaves scope. This returns null and does nothing in CLI mode.
1633 * @return ScopedCallback|null
1635 final protected function getScopedPHPBehaviorForCommit() {
1636 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1637 $old = ignore_user_abort( true ); // avoid half-finished operations
1638 return new ScopedCallback( function () use ( $old ) {
1639 ignore_user_abort( $old );
1646 function __destruct() {
1647 // Avoid connection leaks for sanity
1652 class_alias( LoadBalancer
::class, 'LoadBalancer' );