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
;
36 use DBUnexpectedError
;
37 use DBTransactionError
;
38 use DBTransactionSizeError
;
39 use DBConnectionError
;
40 use InvalidArgumentException
;
45 * Database connection, tracking, load balancing, and transaction manager for a cluster
49 class LoadBalancer
implements ILoadBalancer
{
50 /** @var array[] Map of (server index => server config array) */
52 /** @var \Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
54 /** @var float[] Map of (server index => weight) */
56 /** @var array[] Map of (group => server index => weight) */
58 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
59 private $mAllowLagged;
60 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
61 private $mWaitTimeout;
62 /** @var array The LoadMonitor configuration */
63 private $loadMonitorConfig;
64 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
65 private $tableAliases = [];
67 /** @var ILoadMonitor */
69 /** @var ChronologyProtector|null */
75 /** @var WANObjectCache */
77 /** @var object|string Class name or object With profileIn/profileOut methods */
79 /** @var TransactionProfiler */
80 protected $trxProfiler;
81 /** @var LoggerInterface */
82 protected $replLogger;
83 /** @var LoggerInterface */
84 protected $connLogger;
85 /** @var LoggerInterface */
86 protected $queryLogger;
87 /** @var LoggerInterface */
88 protected $perfLogger;
90 /** @var \Database Database connection that caused a problem */
91 private $errorConnection;
92 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
94 /** @var bool|DBMasterPos False if not set */
96 /** @var bool Whether the generic reader fell back to a lagged replica DB */
97 private $laggedReplicaMode = false;
98 /** @var bool Whether the generic reader fell back to a lagged replica DB */
99 private $allReplicasDownMode = false;
100 /** @var string The last DB selection or connection error */
101 private $mLastError = 'Unknown error';
102 /** @var string|bool Reason the LB is read-only or false if not */
103 private $readOnlyReason = false;
104 /** @var integer Total connections opened */
105 private $connsOpened = 0;
106 /** @var string|bool String if a requested DBO_TRX transaction round is active */
107 private $trxRoundId = false;
108 /** @var array[] Map of (name => callable) */
109 private $trxRecurringCallbacks = [];
110 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
111 private $localDomain;
112 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
113 private $localDomainIdAlias;
114 /** @var string Current server name */
116 /** @var bool Whether this PHP instance is for a CLI script */
118 /** @var string Agent name for query profiling */
121 /** @var callable Exception logger */
122 private $errorLogger;
125 private $disabled = false;
127 private $chronProtInitialized = false;
129 /** @var integer Warn when this many connection are held */
130 const CONN_HELD_WARN_THRESHOLD
= 10;
132 /** @var integer Default 'max lag' when unspecified */
133 const MAX_LAG_DEFAULT
= 10;
134 /** @var integer Seconds to cache master server read-only status */
135 const TTL_CACHE_READONLY
= 5;
137 public function __construct( array $params ) {
138 if ( !isset( $params['servers'] ) ) {
139 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
141 $this->mServers
= $params['servers'];
143 $this->localDomain
= isset( $params['localDomain'] )
144 ? DatabaseDomain
::newFromId( $params['localDomain'] )
145 : DatabaseDomain
::newUnspecified();
146 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
147 // always true, gracefully handle the case when they fail to account for escaping.
148 if ( $this->localDomain
->getTablePrefix() != '' ) {
149 $this->localDomainIdAlias
=
150 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
152 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
155 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
157 $this->mReadIndex
= -1;
164 $this->mWaitForPos
= false;
165 $this->mAllowLagged
= false;
167 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
168 $this->readOnlyReason
= $params['readOnlyReason'];
171 if ( isset( $params['loadMonitor'] ) ) {
172 $this->loadMonitorConfig
= $params['loadMonitor'];
174 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
177 foreach ( $params['servers'] as $i => $server ) {
178 $this->mLoads
[$i] = $server['load'];
179 if ( isset( $server['groupLoads'] ) ) {
180 foreach ( $server['groupLoads'] as $group => $ratio ) {
181 if ( !isset( $this->mGroupLoads
[$group] ) ) {
182 $this->mGroupLoads
[$group] = [];
184 $this->mGroupLoads
[$group][$i] = $ratio;
189 if ( isset( $params['srvCache'] ) ) {
190 $this->srvCache
= $params['srvCache'];
192 $this->srvCache
= new EmptyBagOStuff();
194 if ( isset( $params['memCache'] ) ) {
195 $this->memCache
= $params['memCache'];
197 $this->memCache
= new EmptyBagOStuff();
199 if ( isset( $params['wanCache'] ) ) {
200 $this->wanCache
= $params['wanCache'];
202 $this->wanCache
= WANObjectCache
::newEmpty();
204 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
205 if ( isset( $params['trxProfiler'] ) ) {
206 $this->trxProfiler
= $params['trxProfiler'];
208 $this->trxProfiler
= new TransactionProfiler();
211 $this->errorLogger
= isset( $params['errorLogger'] )
212 ?
$params['errorLogger']
213 : function ( Exception
$e ) {
214 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
217 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
218 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
221 $this->host
= isset( $params['hostname'] )
222 ?
$params['hostname']
223 : ( gethostname() ?
: 'unknown' );
224 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
225 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
227 if ( isset( $params['chronologyProtector'] ) ) {
228 $this->chronProt
= $params['chronologyProtector'];
233 * Get a LoadMonitor instance
235 * @return ILoadMonitor
237 private function getLoadMonitor() {
238 if ( !isset( $this->loadMonitor
) ) {
240 'LoadMonitor' => LoadMonitor
::class,
241 'LoadMonitorNull' => LoadMonitorNull
::class,
242 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
245 $class = $this->loadMonitorConfig
['class'];
246 if ( isset( $compat[$class] ) ) {
247 $class = $compat[$class];
250 $this->loadMonitor
= new $class(
251 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
252 $this->loadMonitor
->setLogger( $this->replLogger
);
255 return $this->loadMonitor
;
259 * @param array $loads
260 * @param bool|string $domain Domain to get non-lagged for
261 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
262 * @return bool|int|string
264 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
265 $lags = $this->getLagTimes( $domain );
267 # Unset excessively lagged servers
268 foreach ( $lags as $i => $lag ) {
270 # How much lag this server nominally is allowed to have
271 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
272 ?
$this->mServers
[$i]['max lag']
273 : self
::MAX_LAG_DEFAULT
; // default
274 # Constrain that futher by $maxLag argument
275 $maxServerLag = min( $maxServerLag, $maxLag );
277 $host = $this->getServerName( $i );
278 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
279 $this->replLogger
->error(
280 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
282 } elseif ( $lag > $maxServerLag ) {
283 $this->replLogger
->warning(
284 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
285 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
292 # Find out if all the replica DBs with non-zero load are lagged
294 foreach ( $loads as $load ) {
298 # No appropriate DB servers except maybe the master and some replica DBs with zero load
299 # Do NOT use the master
300 # Instead, this function will return false, triggering read-only mode,
301 # and a lagged replica DB will be used instead.
305 if ( count( $loads ) == 0 ) {
309 # Return a random representative of the remainder
310 return ArrayUtils
::pickRandom( $loads );
313 public function getReaderIndex( $group = false, $domain = false ) {
314 if ( count( $this->mServers
) == 1 ) {
315 # Skip the load balancing if there's only one server
316 return $this->getWriterIndex();
317 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
318 # Shortcut if generic reader exists already
319 return $this->mReadIndex
;
322 # Find the relevant load array
323 if ( $group !== false ) {
324 if ( isset( $this->mGroupLoads
[$group] ) ) {
325 $nonErrorLoads = $this->mGroupLoads
[$group];
327 # No loads for this group, return false and the caller can use some other group
328 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
333 $nonErrorLoads = $this->mLoads
;
336 if ( !count( $nonErrorLoads ) ) {
337 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
340 # Scale the configured load ratios according to the dynamic load if supported
341 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
343 $laggedReplicaMode = false;
345 # No server found yet
347 # First try quickly looking through the available servers for a server that
349 $currentLoads = $nonErrorLoads;
350 while ( count( $currentLoads ) ) {
351 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
352 $i = ArrayUtils
::pickRandom( $currentLoads );
355 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
356 # ChronologyProtecter causes mWaitForPos to be set via sessions.
357 # This triggers doWait() after connect, so it's especially good to
358 # avoid lagged servers so as to avoid just blocking in that method.
359 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
360 # Aim for <= 1 second of waiting (being too picky can backfire)
361 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
363 if ( $i === false ) {
364 # Any server with less lag than it's 'max lag' param is preferable
365 $i = $this->getRandomNonLagged( $currentLoads, $domain );
367 if ( $i === false && count( $currentLoads ) != 0 ) {
368 # All replica DBs lagged. Switch to read-only mode
369 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
370 $i = ArrayUtils
::pickRandom( $currentLoads );
371 $laggedReplicaMode = true;
375 if ( $i === false ) {
376 # pickRandom() returned false
377 # This is permanent and means the configuration or the load monitor
378 # wants us to return false.
379 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
384 $serverName = $this->getServerName( $i );
385 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
387 $conn = $this->openConnection( $i, $domain );
389 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
390 unset( $nonErrorLoads[$i] );
391 unset( $currentLoads[$i] );
396 // Decrement reference counter, we are finished with this connection.
397 // It will be incremented for the caller later.
398 if ( $domain !== false ) {
399 $this->reuseConnection( $conn );
406 # If all servers were down, quit now
407 if ( !count( $nonErrorLoads ) ) {
408 $this->connLogger
->error( "All servers down" );
411 if ( $i !== false ) {
412 # Replica DB connection successful.
413 # Wait for the session master pos for a short time.
414 if ( $this->mWaitForPos
&& $i > 0 ) {
417 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
418 $this->mReadIndex
= $i;
419 # Record if the generic reader index is in "lagged replica DB" mode
420 if ( $laggedReplicaMode ) {
421 $this->laggedReplicaMode
= true;
424 $serverName = $this->getServerName( $i );
425 $this->connLogger
->debug(
426 __METHOD__
. ": using server $serverName for group '$group'" );
432 public function waitFor( $pos ) {
433 $oldPos = $this->mWaitForPos
;
434 $this->mWaitForPos
= $pos;
436 // If a generic reader connection was already established, then wait now
437 $i = $this->mReadIndex
;
439 if ( !$this->doWait( $i ) ) {
440 $this->laggedReplicaMode
= true;
444 // Restore the older position if it was higher
445 $this->setWaitForPositionIfHigher( $oldPos );
448 public function waitForOne( $pos, $timeout = null ) {
449 $oldPos = $this->mWaitForPos
;
450 $this->mWaitForPos
= $pos;
452 $i = $this->mReadIndex
;
454 // Pick a generic replica DB if there isn't one yet
455 $readLoads = $this->mLoads
;
456 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
457 $readLoads = array_filter( $readLoads ); // with non-zero load
458 $i = ArrayUtils
::pickRandom( $readLoads );
462 $ok = $this->doWait( $i, true, $timeout );
464 $ok = true; // no applicable loads
467 // Restore the older position if it was higher
468 $this->setWaitForPositionIfHigher( $oldPos );
473 public function waitForAll( $pos, $timeout = null ) {
474 $oldPos = $this->mWaitForPos
;
475 $this->mWaitForPos
= $pos;
476 $serverCount = count( $this->mServers
);
479 for ( $i = 1; $i < $serverCount; $i++
) {
480 if ( $this->mLoads
[$i] > 0 ) {
481 $ok = $this->doWait( $i, true, $timeout ) && $ok;
485 // Restore the older position if it was higher
486 $this->setWaitForPositionIfHigher( $oldPos );
492 * @param DBMasterPos|bool $pos
494 private function setWaitForPositionIfHigher( $pos ) {
499 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
500 $this->mWaitForPos
= $pos;
506 * @return IDatabase|bool
508 public function getAnyOpenConnection( $i ) {
509 foreach ( $this->mConns
as $connsByServer ) {
510 if ( !empty( $connsByServer[$i] ) ) {
511 /** @var $serverConns IDatabase[] */
512 $serverConns = $connsByServer[$i];
514 return reset( $serverConns );
522 * Wait for a given replica DB to catch up to the master pos stored in $this
523 * @param int $index Server index
524 * @param bool $open Check the server even if a new connection has to be made
525 * @param int $timeout Max seconds to wait; default is mWaitTimeout
528 protected function doWait( $index, $open = false, $timeout = null ) {
529 $close = false; // close the connection afterwards
531 // Check if we already know that the DB has reached this point
532 $server = $this->getServerName( $index );
533 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
534 /** @var DBMasterPos $knownReachedPos */
535 $knownReachedPos = $this->srvCache
->get( $key );
537 $knownReachedPos instanceof DBMasterPos
&&
538 $knownReachedPos->hasReached( $this->mWaitForPos
)
540 $this->replLogger
->debug( __METHOD__
.
541 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
545 // Find a connection to wait on, creating one if needed and allowed
546 $conn = $this->getAnyOpenConnection( $index );
549 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
553 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
555 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
559 // Avoid connection spam in waitForAll() when connections
560 // are made just for the sake of doing this lag check.
565 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
566 $timeout = $timeout ?
: $this->mWaitTimeout
;
567 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
569 if ( $result == -1 ||
is_null( $result ) ) {
570 // Timed out waiting for replica DB, use master instead
571 $this->replLogger
->warning(
572 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
573 [ 'host' => $server ]
577 $this->replLogger
->info( __METHOD__
. ": Done" );
579 // Remember that the DB reached this point
580 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
584 $this->closeConnection( $conn );
591 * @see ILoadBalancer::getConnection()
594 * @param array $groups
595 * @param bool $domain
597 * @throws DBConnectionError
599 public function getConnection( $i, $groups = [], $domain = false ) {
600 if ( $i === null ||
$i === false ) {
601 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
602 ' with invalid server index' );
605 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
606 $domain = false; // local connection requested
609 $groups = ( $groups === false ||
$groups === [] )
610 ?
[ false ] // check one "group": the generic pool
613 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
614 $oldConnsOpened = $this->connsOpened
; // connections open now
616 if ( $i == self
::DB_MASTER
) {
617 $i = $this->getWriterIndex();
619 # Try to find an available server in any the query groups (in order)
620 foreach ( $groups as $group ) {
621 $groupIndex = $this->getReaderIndex( $group, $domain );
622 if ( $groupIndex !== false ) {
629 # Operation-based index
630 if ( $i == self
::DB_REPLICA
) {
631 $this->mLastError
= 'Unknown error'; // reset error string
632 # Try the general server pool if $groups are unavailable.
633 $i = ( $groups === [ false ] )
634 ?
false // don't bother with this if that is what was tried above
635 : $this->getReaderIndex( false, $domain );
636 # Couldn't find a working server in getReaderIndex()?
637 if ( $i === false ) {
638 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
639 // Throw an exception
640 $this->reportConnectionError();
641 return null; // not reached
645 # Now we have an explicit index into the servers array
646 $conn = $this->openConnection( $i, $domain );
648 // Throw an exception
649 $this->reportConnectionError();
650 return null; // not reached
653 # Profile any new connections that happen
654 if ( $this->connsOpened
> $oldConnsOpened ) {
655 $host = $conn->getServer();
656 $dbname = $conn->getDBname();
657 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
661 # Make master-requested DB handles inherit any read-only mode setting
662 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
668 public function reuseConnection( $conn ) {
669 $serverIndex = $conn->getLBInfo( 'serverIndex' );
670 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
671 if ( $serverIndex === null ||
$refCount === null ) {
673 * This can happen in code like:
674 * foreach ( $dbs as $db ) {
675 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
677 * $lb->reuseConnection( $conn );
679 * When a connection to the local DB is opened in this way, reuseConnection()
683 } elseif ( $conn instanceof DBConnRef
) {
684 // DBConnRef already handles calling reuseConnection() and only passes the live
685 // Database instance to this method. Any caller passing in a DBConnRef is broken.
686 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
687 ( new RuntimeException() )->getTraceAsString() );
692 if ( $this->disabled
) {
693 return; // DBConnRef handle probably survived longer than the LoadBalancer
696 $domain = $conn->getDomainID();
697 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
698 throw new InvalidArgumentException( __METHOD__
.
699 ": connection $serverIndex/$domain not found; it may have already been freed." );
700 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
701 throw new InvalidArgumentException( __METHOD__
.
702 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
704 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
705 if ( $refCount <= 0 ) {
706 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
707 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
708 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
709 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
711 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
713 $this->connLogger
->debug( __METHOD__
.
714 ": reference count for $serverIndex/$domain reduced to $refCount" );
718 public function getConnectionRef( $db, $groups = [], $domain = false ) {
719 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
721 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
724 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
725 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
727 return new DBConnRef( $this, [ $db, $groups, $domain ] );
730 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
731 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
733 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
737 * @see ILoadBalancer::openConnection()
740 * @param bool $domain
741 * @return bool|Database
742 * @throws DBAccessError
744 public function openConnection( $i, $domain = false ) {
745 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
746 $domain = false; // local connection requested
749 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
750 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
751 // Load CP positions before connecting so that doWait() triggers later if needed
752 $this->chronProtInitialized
= true;
753 $this->chronProt
->initLB( $this );
756 if ( $domain !== false ) {
757 $conn = $this->openForeignConnection( $i, $domain );
758 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
759 $conn = $this->mConns
['local'][$i][0];
761 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
762 throw new InvalidArgumentException( "No server with index '$i'." );
764 // Open a new connection
765 $server = $this->mServers
[$i];
766 $server['serverIndex'] = $i;
767 $conn = $this->reallyOpenConnection( $server, false );
768 $serverName = $this->getServerName( $i );
769 if ( $conn->isOpen() ) {
770 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
771 $this->mConns
['local'][$i][0] = $conn;
773 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
774 $this->errorConnection
= $conn;
779 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
780 // Connection was made but later unrecoverably lost for some reason.
781 // Do not return a handle that will just throw exceptions on use,
782 // but let the calling code (e.g. getReaderIndex) try another server.
783 // See DatabaseMyslBase::ping() for how this can happen.
784 $this->errorConnection
= $conn;
792 * Open a connection to a foreign DB, or return one if it is already open.
794 * Increments a reference count on the returned connection which locks the
795 * connection to the requested domain. This reference count can be
796 * decremented by calling reuseConnection().
798 * If a connection is open to the appropriate server already, but with the wrong
799 * database, it will be switched to the right database and returned, as long as
800 * it has been freed first with reuseConnection().
802 * On error, returns false, and the connection which caused the
803 * error will be available via $this->errorConnection.
805 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
807 * @param int $i Server index
808 * @param string $domain Domain ID to open
811 private function openForeignConnection( $i, $domain ) {
812 $domainInstance = DatabaseDomain
::newFromId( $domain );
813 $dbName = $domainInstance->getDatabase();
814 $prefix = $domainInstance->getTablePrefix();
816 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
817 // Reuse an already-used connection
818 $conn = $this->mConns
['foreignUsed'][$i][$domain];
819 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
820 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
821 // Reuse a free connection for the same domain
822 $conn = $this->mConns
['foreignFree'][$i][$domain];
823 unset( $this->mConns
['foreignFree'][$i][$domain] );
824 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
825 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
826 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
827 // Reuse a connection from another domain
828 $conn = reset( $this->mConns
['foreignFree'][$i] );
829 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
830 // The empty string as a DB name means "don't care".
831 // DatabaseMysqlBase::open() already handle this on connection.
832 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
833 $this->mLastError
= "Error selecting database '$dbName' on server " .
834 $conn->getServer() . " from client host {$this->host}";
835 $this->errorConnection
= $conn;
838 $conn->tablePrefix( $prefix );
839 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
840 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
841 $this->connLogger
->debug( __METHOD__
.
842 ": reusing free connection from $oldDomain for $domain" );
845 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
846 throw new InvalidArgumentException( "No server with index '$i'." );
848 // Open a new connection
849 $server = $this->mServers
[$i];
850 $server['serverIndex'] = $i;
851 $server['foreignPoolRefCount'] = 0;
852 $server['foreign'] = true;
853 $conn = $this->reallyOpenConnection( $server, $dbName );
854 if ( !$conn->isOpen() ) {
855 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
856 $this->errorConnection
= $conn;
859 $conn->tablePrefix( $prefix );
860 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
861 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
865 // Increment reference count
866 if ( $conn instanceof IDatabase
) {
867 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
868 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
875 * Test if the specified index represents an open connection
877 * @param int $index Server index
881 private function isOpen( $index ) {
882 if ( !is_integer( $index ) ) {
886 return (bool)$this->getAnyOpenConnection( $index );
890 * Really opens a connection. Uncached.
891 * Returns a Database object whether or not the connection was successful.
894 * @param array $server
895 * @param string|bool $dbNameOverride Use "" to not select any database
897 * @throws DBAccessError
898 * @throws InvalidArgumentException
900 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
901 if ( $this->disabled
) {
902 throw new DBAccessError();
905 if ( $dbNameOverride !== false ) {
906 $server['dbname'] = $dbNameOverride;
909 // Let the handle know what the cluster master is (e.g. "db1052")
910 $masterName = $this->getServerName( $this->getWriterIndex() );
911 $server['clusterMasterHost'] = $masterName;
913 // Log when many connection are made on requests
914 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
915 $this->perfLogger
->warning( __METHOD__
. ": " .
916 "{$this->connsOpened}+ connections made (master=$masterName)" );
919 $server['srvCache'] = $this->srvCache
;
920 // Set loggers and profilers
921 $server['connLogger'] = $this->connLogger
;
922 $server['queryLogger'] = $this->queryLogger
;
923 $server['errorLogger'] = $this->errorLogger
;
924 $server['profiler'] = $this->profiler
;
925 $server['trxProfiler'] = $this->trxProfiler
;
926 // Use the same agent and PHP mode for all DB handles
927 $server['cliMode'] = $this->cliMode
;
928 $server['agent'] = $this->agent
;
929 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
930 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
931 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
933 // Create a live connection object
935 $db = Database
::factory( $server['type'], $server );
936 } catch ( DBConnectionError
$e ) {
937 // FIXME: This is probably the ugliest thing I have ever done to
938 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
942 $db->setLBInfo( $server );
943 $db->setLazyMasterHandle(
944 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
946 $db->setTableAliases( $this->tableAliases
);
948 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
949 if ( $this->trxRoundId
!== false ) {
950 $this->applyTransactionRoundFlags( $db );
952 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
953 $db->setTransactionListener( $name, $callback );
961 * @throws DBConnectionError
963 private function reportConnectionError() {
964 $conn = $this->errorConnection
; // the connection which caused the error
966 'method' => __METHOD__
,
967 'last_error' => $this->mLastError
,
970 if ( $conn instanceof IDatabase
) {
971 $context['db_server'] = $conn->getServer();
972 $this->connLogger
->warning(
973 "Connection error: {last_error} ({db_server})",
977 // throws DBConnectionError
978 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
980 // No last connection, probably due to all servers being too busy
981 $this->connLogger
->error(
982 "LB failure with no last connection. Connection error: {last_error}",
986 // If all servers were busy, mLastError will contain something sensible
987 throw new DBConnectionError( null, $this->mLastError
);
991 public function getWriterIndex() {
995 public function haveIndex( $i ) {
996 return array_key_exists( $i, $this->mServers
);
999 public function isNonZeroLoad( $i ) {
1000 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1003 public function getServerCount() {
1004 return count( $this->mServers
);
1007 public function getServerName( $i ) {
1008 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1009 $name = $this->mServers
[$i]['hostName'];
1010 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1011 $name = $this->mServers
[$i]['host'];
1016 return ( $name != '' ) ?
$name : 'localhost';
1019 public function getServerInfo( $i ) {
1020 if ( isset( $this->mServers
[$i] ) ) {
1021 return $this->mServers
[$i];
1027 public function setServerInfo( $i, array $serverInfo ) {
1028 $this->mServers
[$i] = $serverInfo;
1031 public function getMasterPos() {
1032 # If this entire request was served from a replica DB without opening a connection to the
1033 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1034 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1035 if ( !$masterConn ) {
1036 $serverCount = count( $this->mServers
);
1037 for ( $i = 1; $i < $serverCount; $i++
) {
1038 $conn = $this->getAnyOpenConnection( $i );
1040 return $conn->getReplicaPos();
1044 return $masterConn->getMasterPos();
1050 public function disable() {
1052 $this->disabled
= true;
1055 public function closeAll() {
1056 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1057 $host = $conn->getServer();
1058 $this->connLogger
->debug( "Closing connection to database '$host'." );
1064 'foreignFree' => [],
1065 'foreignUsed' => [],
1067 $this->connsOpened
= 0;
1070 public function closeConnection( IDatabase
$conn ) {
1071 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1072 foreach ( $this->mConns
as $type => $connsByServer ) {
1073 if ( !isset( $connsByServer[$serverIndex] ) ) {
1077 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1078 if ( $conn === $trackedConn ) {
1079 $host = $this->getServerName( $i );
1080 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1081 unset( $this->mConns
[$type][$serverIndex][$i] );
1082 --$this->connsOpened
;
1091 public function commitAll( $fname = __METHOD__
) {
1094 $restore = ( $this->trxRoundId
!== false );
1095 $this->trxRoundId
= false;
1096 $this->forEachOpenConnection(
1097 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1099 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1100 } catch ( DBError
$e ) {
1101 call_user_func( $this->errorLogger
, $e );
1102 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1104 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1105 $this->undoTransactionRoundFlags( $conn );
1111 throw new DBExpectedError(
1113 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1118 public function finalizeMasterChanges() {
1119 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1120 // Any error should cause all DB transactions to be rolled back together
1121 $conn->setTrxEndCallbackSuppression( false );
1122 $conn->runOnTransactionPreCommitCallbacks();
1123 // Defer post-commit callbacks until COMMIT finishes for all DBs
1124 $conn->setTrxEndCallbackSuppression( true );
1128 public function approveMasterChanges( array $options ) {
1129 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1130 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1131 // If atomic sections or explicit transactions are still open, some caller must have
1132 // caught an exception but failed to properly rollback any changes. Detect that and
1133 // throw and error (causing rollback).
1134 if ( $conn->explicitTrxActive() ) {
1135 throw new DBTransactionError(
1137 "Explicit transaction still active. A caller may have caught an error."
1140 // Assert that the time to replicate the transaction will be sane.
1141 // If this fails, then all DB transactions will be rollback back together.
1142 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1143 if ( $limit > 0 && $time > $limit ) {
1144 throw new DBTransactionSizeError(
1146 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1150 // If a connection sits idle while slow queries execute on another, that connection
1151 // may end up dropped before the commit round is reached. Ping servers to detect this.
1152 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1153 throw new DBTransactionError(
1155 "A connection to the {$conn->getDBname()} database was lost before commit."
1161 public function beginMasterChanges( $fname = __METHOD__
) {
1162 if ( $this->trxRoundId
!== false ) {
1163 throw new DBTransactionError(
1165 "$fname: Transaction round '{$this->trxRoundId}' already started."
1168 $this->trxRoundId
= $fname;
1171 $this->forEachOpenMasterConnection(
1172 function ( Database
$conn ) use ( $fname, &$failures ) {
1173 $conn->setTrxEndCallbackSuppression( true );
1175 $conn->flushSnapshot( $fname );
1176 } catch ( DBError
$e ) {
1177 call_user_func( $this->errorLogger
, $e );
1178 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1180 $conn->setTrxEndCallbackSuppression( false );
1181 $this->applyTransactionRoundFlags( $conn );
1186 throw new DBExpectedError(
1188 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1193 public function commitMasterChanges( $fname = __METHOD__
) {
1196 /** @noinspection PhpUnusedLocalVariableInspection */
1197 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1199 $restore = ( $this->trxRoundId
!== false );
1200 $this->trxRoundId
= false;
1201 $this->forEachOpenMasterConnection(
1202 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1204 if ( $conn->writesOrCallbacksPending() ) {
1205 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1206 } elseif ( $restore ) {
1207 $conn->flushSnapshot( $fname );
1209 } catch ( DBError
$e ) {
1210 call_user_func( $this->errorLogger
, $e );
1211 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1214 $this->undoTransactionRoundFlags( $conn );
1220 throw new DBExpectedError(
1222 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1227 public function runMasterPostTrxCallbacks( $type ) {
1228 $e = null; // first exception
1229 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1230 $conn->setTrxEndCallbackSuppression( false );
1231 if ( $conn->writesOrCallbacksPending() ) {
1232 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1233 // (which finished its callbacks already). Warn and recover in this case. Let the
1234 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1235 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1237 } elseif ( $conn->trxLevel() ) {
1238 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1239 // thus leaving an implicit read-only transaction open at this point. It
1240 // also happens if onTransactionIdle() callbacks leave implicit transactions
1241 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1242 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1246 $conn->runOnTransactionIdleCallbacks( $type );
1247 } catch ( Exception
$ex ) {
1251 $conn->runTransactionListenerCallbacks( $type );
1252 } catch ( Exception
$ex ) {
1260 public function rollbackMasterChanges( $fname = __METHOD__
) {
1261 $restore = ( $this->trxRoundId
!== false );
1262 $this->trxRoundId
= false;
1263 $this->forEachOpenMasterConnection(
1264 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1265 if ( $conn->writesOrCallbacksPending() ) {
1266 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1269 $this->undoTransactionRoundFlags( $conn );
1275 public function suppressTransactionEndCallbacks() {
1276 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1277 $conn->setTrxEndCallbackSuppression( true );
1282 * @param IDatabase $conn
1284 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1285 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1286 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1287 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1288 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1289 // If config has explicitly requested DBO_TRX be either on or off by not
1290 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1291 // for things like blob stores (ExternalStore) which want auto-commit mode.
1296 * @param IDatabase $conn
1298 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1299 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1300 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1304 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1305 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1306 $conn->flushSnapshot( __METHOD__
);
1310 public function hasMasterConnection() {
1311 return $this->isOpen( $this->getWriterIndex() );
1314 public function hasMasterChanges() {
1316 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1317 $pending |
= $conn->writesOrCallbacksPending();
1320 return (bool)$pending;
1323 public function lastMasterChangeTimestamp() {
1325 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1326 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1332 public function hasOrMadeRecentMasterChanges( $age = null ) {
1333 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1335 return ( $this->hasMasterChanges()
1336 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1339 public function pendingMasterChangeCallers() {
1341 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1342 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1348 public function getLaggedReplicaMode( $domain = false ) {
1349 // No-op if there is only one DB (also avoids recursion)
1350 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1352 // See if laggedReplicaMode gets set
1353 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1354 $this->reuseConnection( $conn );
1355 } catch ( DBConnectionError
$e ) {
1356 // Avoid expensive re-connect attempts and failures
1357 $this->allReplicasDownMode
= true;
1358 $this->laggedReplicaMode
= true;
1362 return $this->laggedReplicaMode
;
1366 * @param bool $domain
1368 * @deprecated 1.28; use getLaggedReplicaMode()
1370 public function getLaggedSlaveMode( $domain = false ) {
1371 return $this->getLaggedReplicaMode( $domain );
1374 public function laggedReplicaUsed() {
1375 return $this->laggedReplicaMode
;
1381 * @deprecated Since 1.28; use laggedReplicaUsed()
1383 public function laggedSlaveUsed() {
1384 return $this->laggedReplicaUsed();
1387 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1388 if ( $this->readOnlyReason
!== false ) {
1389 return $this->readOnlyReason
;
1390 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1391 if ( $this->allReplicasDownMode
) {
1392 return 'The database has been automatically locked ' .
1393 'until the replica database servers become available';
1395 return 'The database has been automatically locked ' .
1396 'while the replica database servers catch up to the master.';
1398 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1399 return 'The database master is running in read-only mode.';
1406 * @param string $domain Domain ID, or false for the current domain
1407 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1410 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1411 $cache = $this->wanCache
;
1412 $masterServer = $this->getServerName( $this->getWriterIndex() );
1414 return (bool)$cache->getWithSetCallback(
1415 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1416 self
::TTL_CACHE_READONLY
,
1417 function () use ( $domain, $conn ) {
1418 $old = $this->trxProfiler
->setSilenced( true );
1420 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1421 $readOnly = (int)$dbw->serverIsReadOnly();
1423 $this->reuseConnection( $dbw );
1425 } catch ( DBError
$e ) {
1428 $this->trxProfiler
->setSilenced( $old );
1431 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1435 public function allowLagged( $mode = null ) {
1436 if ( $mode === null ) {
1437 return $this->mAllowLagged
;
1439 $this->mAllowLagged
= $mode;
1441 return $this->mAllowLagged
;
1444 public function pingAll() {
1446 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1447 if ( !$conn->ping() ) {
1455 public function forEachOpenConnection( $callback, array $params = [] ) {
1456 foreach ( $this->mConns
as $connsByServer ) {
1457 foreach ( $connsByServer as $serverConns ) {
1458 foreach ( $serverConns as $conn ) {
1459 $mergedParams = array_merge( [ $conn ], $params );
1460 call_user_func_array( $callback, $mergedParams );
1466 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1467 $masterIndex = $this->getWriterIndex();
1468 foreach ( $this->mConns
as $connsByServer ) {
1469 if ( isset( $connsByServer[$masterIndex] ) ) {
1470 /** @var IDatabase $conn */
1471 foreach ( $connsByServer[$masterIndex] as $conn ) {
1472 $mergedParams = array_merge( [ $conn ], $params );
1473 call_user_func_array( $callback, $mergedParams );
1479 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1480 foreach ( $this->mConns
as $connsByServer ) {
1481 foreach ( $connsByServer as $i => $serverConns ) {
1482 if ( $i === $this->getWriterIndex() ) {
1483 continue; // skip master
1485 foreach ( $serverConns as $conn ) {
1486 $mergedParams = array_merge( [ $conn ], $params );
1487 call_user_func_array( $callback, $mergedParams );
1493 public function getMaxLag( $domain = false ) {
1498 if ( $this->getServerCount() <= 1 ) {
1499 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1502 $lagTimes = $this->getLagTimes( $domain );
1503 foreach ( $lagTimes as $i => $lag ) {
1504 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1506 $host = $this->mServers
[$i]['host'];
1511 return [ $host, $maxLag, $maxIndex ];
1514 public function getLagTimes( $domain = false ) {
1515 if ( $this->getServerCount() <= 1 ) {
1516 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1519 $knownLagTimes = []; // map of (server index => 0 seconds)
1520 $indexesWithLag = [];
1521 foreach ( $this->mServers
as $i => $server ) {
1522 if ( empty( $server['is static'] ) ) {
1523 $indexesWithLag[] = $i; // DB server might have replication lag
1525 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1529 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1532 public function safeGetLag( IDatabase
$conn ) {
1533 if ( $this->getServerCount() <= 1 ) {
1536 return $conn->getLag();
1541 * @param IDatabase $conn
1542 * @param DBMasterPos|bool $pos
1543 * @param int $timeout
1546 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1547 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1548 return true; // server is not a replica DB
1552 // Get the current master position, opening a connection if needed
1553 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1554 if ( $masterConn ) {
1555 $pos = $masterConn->getMasterPos();
1557 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1558 $pos = $masterConn->getMasterPos();
1559 $this->closeConnection( $masterConn );
1563 if ( $pos instanceof DBMasterPos
) {
1564 $result = $conn->masterPosWait( $pos, $timeout );
1565 if ( $result == -1 ||
is_null( $result ) ) {
1566 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1567 $this->replLogger
->warning( "$msg" );
1570 $this->replLogger
->info( __METHOD__
. ": Done" );
1574 $ok = false; // something is misconfigured
1575 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1581 public function setTransactionListener( $name, callable
$callback = null ) {
1583 $this->trxRecurringCallbacks
[$name] = $callback;
1585 unset( $this->trxRecurringCallbacks
[$name] );
1587 $this->forEachOpenMasterConnection(
1588 function ( IDatabase
$conn ) use ( $name, $callback ) {
1589 $conn->setTransactionListener( $name, $callback );
1594 public function setTableAliases( array $aliases ) {
1595 $this->tableAliases
= $aliases;
1598 public function setDomainPrefix( $prefix ) {
1599 if ( $this->mConns
['foreignUsed'] ) {
1600 // Do not switch connections to explicit foreign domains unless marked as free
1602 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1603 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1605 $domains = implode( ', ', $domains );
1606 throw new DBUnexpectedError( null,
1607 "Foreign domain connections are still in use ($domains)." );
1610 $this->localDomain
= new DatabaseDomain(
1611 $this->localDomain
->getDatabase(),
1616 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1617 $db->tablePrefix( $prefix );
1622 * Make PHP ignore user aborts/disconnects until the returned
1623 * value leaves scope. This returns null and does nothing in CLI mode.
1625 * @return ScopedCallback|null
1627 final protected function getScopedPHPBehaviorForCommit() {
1628 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1629 $old = ignore_user_abort( true ); // avoid half-finished operations
1630 return new ScopedCallback( function () use ( $old ) {
1631 ignore_user_abort( $old );
1638 function __destruct() {
1639 // Avoid connection leaks for sanity
1644 class_alias( LoadBalancer
::class, 'LoadBalancer' );