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
;
31 use MaintainableDBConnRef
;
39 use DBUnexpectedError
;
40 use DBTransactionError
;
41 use DBTransactionSizeError
;
42 use DBConnectionError
;
43 use InvalidArgumentException
;
48 * Database connection, tracking, load balancing, and transaction manager for a cluster
52 class LoadBalancer
implements ILoadBalancer
{
53 /** @var array[] Map of (server index => server config array) */
55 /** @var \Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
57 /** @var float[] Map of (server index => weight) */
59 /** @var array[] Map of (group => server index => weight) */
61 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
62 private $mAllowLagged;
63 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
64 private $mWaitTimeout;
65 /** @var array The LoadMonitor configuration */
66 private $loadMonitorConfig;
67 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
68 private $tableAliases = [];
70 /** @var ILoadMonitor */
72 /** @var ChronologyProtector|null */
78 /** @var WANObjectCache */
80 /** @var object|string Class name or object With profileIn/profileOut methods */
82 /** @var TransactionProfiler */
83 protected $trxProfiler;
84 /** @var LoggerInterface */
85 protected $replLogger;
86 /** @var LoggerInterface */
87 protected $connLogger;
88 /** @var LoggerInterface */
89 protected $queryLogger;
90 /** @var LoggerInterface */
91 protected $perfLogger;
93 /** @var \Database Database connection that caused a problem */
94 private $errorConnection;
95 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
97 /** @var bool|DBMasterPos False if not set */
99 /** @var bool Whether the generic reader fell back to a lagged replica DB */
100 private $laggedReplicaMode = false;
101 /** @var bool Whether the generic reader fell back to a lagged replica DB */
102 private $allReplicasDownMode = false;
103 /** @var string The last DB selection or connection error */
104 private $mLastError = 'Unknown error';
105 /** @var string|bool Reason the LB is read-only or false if not */
106 private $readOnlyReason = false;
107 /** @var integer Total connections opened */
108 private $connsOpened = 0;
109 /** @var string|bool String if a requested DBO_TRX transaction round is active */
110 private $trxRoundId = false;
111 /** @var array[] Map of (name => callable) */
112 private $trxRecurringCallbacks = [];
113 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
114 private $localDomain;
115 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
116 private $localDomainIdAlias;
117 /** @var string Current server name */
119 /** @var bool Whether this PHP instance is for a CLI script */
121 /** @var string Agent name for query profiling */
124 /** @var callable Exception logger */
125 private $errorLogger;
128 private $disabled = false;
130 private $chronProtInitialized = false;
132 /** @var integer Warn when this many connection are held */
133 const CONN_HELD_WARN_THRESHOLD
= 10;
135 /** @var integer Default 'max lag' when unspecified */
136 const MAX_LAG_DEFAULT
= 10;
137 /** @var integer Seconds to cache master server read-only status */
138 const TTL_CACHE_READONLY
= 5;
140 public function __construct( array $params ) {
141 if ( !isset( $params['servers'] ) ) {
142 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
144 $this->mServers
= $params['servers'];
146 $this->localDomain
= isset( $params['localDomain'] )
147 ? DatabaseDomain
::newFromId( $params['localDomain'] )
148 : DatabaseDomain
::newUnspecified();
149 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
150 // always true, gracefully handle the case when they fail to account for escaping.
151 if ( $this->localDomain
->getTablePrefix() != '' ) {
152 $this->localDomainIdAlias
=
153 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
155 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
158 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
160 $this->mReadIndex
= -1;
167 $this->mWaitForPos
= false;
168 $this->mAllowLagged
= false;
170 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
171 $this->readOnlyReason
= $params['readOnlyReason'];
174 if ( isset( $params['loadMonitor'] ) ) {
175 $this->loadMonitorConfig
= $params['loadMonitor'];
177 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
180 foreach ( $params['servers'] as $i => $server ) {
181 $this->mLoads
[$i] = $server['load'];
182 if ( isset( $server['groupLoads'] ) ) {
183 foreach ( $server['groupLoads'] as $group => $ratio ) {
184 if ( !isset( $this->mGroupLoads
[$group] ) ) {
185 $this->mGroupLoads
[$group] = [];
187 $this->mGroupLoads
[$group][$i] = $ratio;
192 if ( isset( $params['srvCache'] ) ) {
193 $this->srvCache
= $params['srvCache'];
195 $this->srvCache
= new EmptyBagOStuff();
197 if ( isset( $params['memCache'] ) ) {
198 $this->memCache
= $params['memCache'];
200 $this->memCache
= new EmptyBagOStuff();
202 if ( isset( $params['wanCache'] ) ) {
203 $this->wanCache
= $params['wanCache'];
205 $this->wanCache
= WANObjectCache
::newEmpty();
207 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
208 if ( isset( $params['trxProfiler'] ) ) {
209 $this->trxProfiler
= $params['trxProfiler'];
211 $this->trxProfiler
= new TransactionProfiler();
214 $this->errorLogger
= isset( $params['errorLogger'] )
215 ?
$params['errorLogger']
216 : function ( Exception
$e ) {
217 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
220 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
221 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
224 $this->host
= isset( $params['hostname'] )
225 ?
$params['hostname']
226 : ( gethostname() ?
: 'unknown' );
227 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
228 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
230 if ( isset( $params['chronologyProtector'] ) ) {
231 $this->chronProt
= $params['chronologyProtector'];
236 * Get a LoadMonitor instance
238 * @return ILoadMonitor
240 private function getLoadMonitor() {
241 if ( !isset( $this->loadMonitor
) ) {
243 'LoadMonitor' => LoadMonitor
::class,
244 'LoadMonitorNull' => LoadMonitorNull
::class,
245 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
248 $class = $this->loadMonitorConfig
['class'];
249 if ( isset( $compat[$class] ) ) {
250 $class = $compat[$class];
253 $this->loadMonitor
= new $class(
254 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
255 $this->loadMonitor
->setLogger( $this->replLogger
);
258 return $this->loadMonitor
;
262 * @param array $loads
263 * @param bool|string $domain Domain to get non-lagged for
264 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
265 * @return bool|int|string
267 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
268 $lags = $this->getLagTimes( $domain );
270 # Unset excessively lagged servers
271 foreach ( $lags as $i => $lag ) {
273 # How much lag this server nominally is allowed to have
274 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
275 ?
$this->mServers
[$i]['max lag']
276 : self
::MAX_LAG_DEFAULT
; // default
277 # Constrain that futher by $maxLag argument
278 $maxServerLag = min( $maxServerLag, $maxLag );
280 $host = $this->getServerName( $i );
281 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
282 $this->replLogger
->error(
283 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
285 } elseif ( $lag > $maxServerLag ) {
286 $this->replLogger
->warning(
287 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
288 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
295 # Find out if all the replica DBs with non-zero load are lagged
297 foreach ( $loads as $load ) {
301 # No appropriate DB servers except maybe the master and some replica DBs with zero load
302 # Do NOT use the master
303 # Instead, this function will return false, triggering read-only mode,
304 # and a lagged replica DB will be used instead.
308 if ( count( $loads ) == 0 ) {
312 # Return a random representative of the remainder
313 return ArrayUtils
::pickRandom( $loads );
316 public function getReaderIndex( $group = false, $domain = false ) {
317 if ( count( $this->mServers
) == 1 ) {
318 # Skip the load balancing if there's only one server
319 return $this->getWriterIndex();
320 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
321 # Shortcut if generic reader exists already
322 return $this->mReadIndex
;
325 # Find the relevant load array
326 if ( $group !== false ) {
327 if ( isset( $this->mGroupLoads
[$group] ) ) {
328 $nonErrorLoads = $this->mGroupLoads
[$group];
330 # No loads for this group, return false and the caller can use some other group
331 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
336 $nonErrorLoads = $this->mLoads
;
339 if ( !count( $nonErrorLoads ) ) {
340 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
343 # Scale the configured load ratios according to the dynamic load if supported
344 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
346 $laggedReplicaMode = false;
348 # No server found yet
350 # First try quickly looking through the available servers for a server that
352 $currentLoads = $nonErrorLoads;
353 while ( count( $currentLoads ) ) {
354 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
355 $i = ArrayUtils
::pickRandom( $currentLoads );
358 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
359 # ChronologyProtecter causes mWaitForPos to be set via sessions.
360 # This triggers doWait() after connect, so it's especially good to
361 # avoid lagged servers so as to avoid just blocking in that method.
362 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
363 # Aim for <= 1 second of waiting (being too picky can backfire)
364 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
366 if ( $i === false ) {
367 # Any server with less lag than it's 'max lag' param is preferable
368 $i = $this->getRandomNonLagged( $currentLoads, $domain );
370 if ( $i === false && count( $currentLoads ) != 0 ) {
371 # All replica DBs lagged. Switch to read-only mode
372 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
373 $i = ArrayUtils
::pickRandom( $currentLoads );
374 $laggedReplicaMode = true;
378 if ( $i === false ) {
379 # pickRandom() returned false
380 # This is permanent and means the configuration or the load monitor
381 # wants us to return false.
382 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
387 $serverName = $this->getServerName( $i );
388 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
390 $conn = $this->openConnection( $i, $domain );
392 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
393 unset( $nonErrorLoads[$i] );
394 unset( $currentLoads[$i] );
399 // Decrement reference counter, we are finished with this connection.
400 // It will be incremented for the caller later.
401 if ( $domain !== false ) {
402 $this->reuseConnection( $conn );
409 # If all servers were down, quit now
410 if ( !count( $nonErrorLoads ) ) {
411 $this->connLogger
->error( "All servers down" );
414 if ( $i !== false ) {
415 # Replica DB connection successful.
416 # Wait for the session master pos for a short time.
417 if ( $this->mWaitForPos
&& $i > 0 ) {
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
;
437 $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
448 $this->setWaitForPositionIfHigher( $oldPos );
451 public function waitForOne( $pos, $timeout = null ) {
452 $oldPos = $this->mWaitForPos
;
453 $this->mWaitForPos
= $pos;
455 $i = $this->mReadIndex
;
457 // Pick a generic replica DB if there isn't one yet
458 $readLoads = $this->mLoads
;
459 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
460 $readLoads = array_filter( $readLoads ); // with non-zero load
461 $i = ArrayUtils
::pickRandom( $readLoads );
465 $ok = $this->doWait( $i, true, $timeout );
467 $ok = true; // no applicable loads
470 // Restore the older position if it was higher
471 $this->setWaitForPositionIfHigher( $oldPos );
476 public function waitForAll( $pos, $timeout = null ) {
477 $oldPos = $this->mWaitForPos
;
478 $this->mWaitForPos
= $pos;
479 $serverCount = count( $this->mServers
);
482 for ( $i = 1; $i < $serverCount; $i++
) {
483 if ( $this->mLoads
[$i] > 0 ) {
484 $ok = $this->doWait( $i, true, $timeout ) && $ok;
488 // Restore the older position if it was higher
489 $this->setWaitForPositionIfHigher( $oldPos );
495 * @param DBMasterPos|bool $pos
497 private function setWaitForPositionIfHigher( $pos ) {
502 if ( !$this->mWaitForPos ||
$pos->hasReached( $this->mWaitForPos
) ) {
503 $this->mWaitForPos
= $pos;
509 * @return IDatabase|bool
511 public function getAnyOpenConnection( $i ) {
512 foreach ( $this->mConns
as $connsByServer ) {
513 if ( !empty( $connsByServer[$i] ) ) {
514 /** @var $serverConns IDatabase[] */
515 $serverConns = $connsByServer[$i];
517 return reset( $serverConns );
525 * Wait for a given replica DB to catch up to the master pos stored in $this
526 * @param int $index Server index
527 * @param bool $open Check the server even if a new connection has to be made
528 * @param int $timeout Max seconds to wait; default is mWaitTimeout
531 protected function doWait( $index, $open = false, $timeout = null ) {
532 $close = false; // close the connection afterwards
534 // Check if we already know that the DB has reached this point
535 $server = $this->getServerName( $index );
536 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
537 /** @var DBMasterPos $knownReachedPos */
538 $knownReachedPos = $this->srvCache
->get( $key );
540 $knownReachedPos instanceof DBMasterPos
&&
541 $knownReachedPos->hasReached( $this->mWaitForPos
)
543 $this->replLogger
->debug( __METHOD__
.
544 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
548 // Find a connection to wait on, creating one if needed and allowed
549 $conn = $this->getAnyOpenConnection( $index );
552 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
556 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
558 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
562 // Avoid connection spam in waitForAll() when connections
563 // are made just for the sake of doing this lag check.
568 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
569 $timeout = $timeout ?
: $this->mWaitTimeout
;
570 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
572 if ( $result == -1 ||
is_null( $result ) ) {
573 // Timed out waiting for replica DB, use master instead
574 $this->replLogger
->warning(
575 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
576 [ 'host' => $server ]
580 $this->replLogger
->info( __METHOD__
. ": Done" );
582 // Remember that the DB reached this point
583 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
587 $this->closeConnection( $conn );
594 * @see ILoadBalancer::getConnection()
597 * @param array $groups
598 * @param bool $domain
600 * @throws DBConnectionError
602 public function getConnection( $i, $groups = [], $domain = false ) {
603 if ( $i === null ||
$i === false ) {
604 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
605 ' with invalid server index' );
608 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
609 $domain = false; // local connection requested
612 $groups = ( $groups === false ||
$groups === [] )
613 ?
[ false ] // check one "group": the generic pool
616 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
617 $oldConnsOpened = $this->connsOpened
; // connections open now
619 if ( $i == self
::DB_MASTER
) {
620 $i = $this->getWriterIndex();
622 # Try to find an available server in any the query groups (in order)
623 foreach ( $groups as $group ) {
624 $groupIndex = $this->getReaderIndex( $group, $domain );
625 if ( $groupIndex !== false ) {
632 # Operation-based index
633 if ( $i == self
::DB_REPLICA
) {
634 $this->mLastError
= 'Unknown error'; // reset error string
635 # Try the general server pool if $groups are unavailable.
636 $i = ( $groups === [ false ] )
637 ?
false // don't bother with this if that is what was tried above
638 : $this->getReaderIndex( false, $domain );
639 # Couldn't find a working server in getReaderIndex()?
640 if ( $i === false ) {
641 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
642 // Throw an exception
643 $this->reportConnectionError();
644 return null; // not reached
648 # Now we have an explicit index into the servers array
649 $conn = $this->openConnection( $i, $domain );
651 // Throw an exception
652 $this->reportConnectionError();
653 return null; // not reached
656 # Profile any new connections that happen
657 if ( $this->connsOpened
> $oldConnsOpened ) {
658 $host = $conn->getServer();
659 $dbname = $conn->getDBname();
660 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
664 # Make master-requested DB handles inherit any read-only mode setting
665 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
671 public function reuseConnection( $conn ) {
672 $serverIndex = $conn->getLBInfo( 'serverIndex' );
673 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
674 if ( $serverIndex === null ||
$refCount === null ) {
676 * This can happen in code like:
677 * foreach ( $dbs as $db ) {
678 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
680 * $lb->reuseConnection( $conn );
682 * When a connection to the local DB is opened in this way, reuseConnection()
686 } elseif ( $conn instanceof DBConnRef
) {
687 // DBConnRef already handles calling reuseConnection() and only passes the live
688 // Database instance to this method. Any caller passing in a DBConnRef is broken.
689 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
690 ( new RuntimeException() )->getTraceAsString() );
695 if ( $this->disabled
) {
696 return; // DBConnRef handle probably survived longer than the LoadBalancer
699 $domain = $conn->getDomainID();
700 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
701 throw new InvalidArgumentException( __METHOD__
.
702 ": connection $serverIndex/$domain not found; it may have already been freed." );
703 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
704 throw new InvalidArgumentException( __METHOD__
.
705 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
707 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
708 if ( $refCount <= 0 ) {
709 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
710 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
711 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
712 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
714 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
716 $this->connLogger
->debug( __METHOD__
.
717 ": reference count for $serverIndex/$domain reduced to $refCount" );
721 public function getConnectionRef( $db, $groups = [], $domain = false ) {
722 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
724 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
727 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
728 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
730 return new DBConnRef( $this, [ $db, $groups, $domain ] );
733 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
734 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
736 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
740 * @see ILoadBalancer::openConnection()
743 * @param bool $domain
744 * @return bool|Database
745 * @throws DBAccessError
747 public function openConnection( $i, $domain = false ) {
748 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
749 $domain = false; // local connection requested
752 if ( !$this->chronProtInitialized
&& $this->chronProt
) {
753 $this->connLogger
->debug( __METHOD__
. ': calling initLB() before first connection.' );
754 // Load CP positions before connecting so that doWait() triggers later if needed
755 $this->chronProtInitialized
= true;
756 $this->chronProt
->initLB( $this );
759 if ( $domain !== false ) {
760 $conn = $this->openForeignConnection( $i, $domain );
761 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
762 $conn = $this->mConns
['local'][$i][0];
764 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
765 throw new InvalidArgumentException( "No server with index '$i'." );
767 // Open a new connection
768 $server = $this->mServers
[$i];
769 $server['serverIndex'] = $i;
770 $conn = $this->reallyOpenConnection( $server, false );
771 $serverName = $this->getServerName( $i );
772 if ( $conn->isOpen() ) {
773 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
774 $this->mConns
['local'][$i][0] = $conn;
776 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
777 $this->errorConnection
= $conn;
782 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
783 // Connection was made but later unrecoverably lost for some reason.
784 // Do not return a handle that will just throw exceptions on use,
785 // but let the calling code (e.g. getReaderIndex) try another server.
786 // See DatabaseMyslBase::ping() for how this can happen.
787 $this->errorConnection
= $conn;
795 * Open a connection to a foreign DB, or return one if it is already open.
797 * Increments a reference count on the returned connection which locks the
798 * connection to the requested domain. This reference count can be
799 * decremented by calling reuseConnection().
801 * If a connection is open to the appropriate server already, but with the wrong
802 * database, it will be switched to the right database and returned, as long as
803 * it has been freed first with reuseConnection().
805 * On error, returns false, and the connection which caused the
806 * error will be available via $this->errorConnection.
808 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
810 * @param int $i Server index
811 * @param string $domain Domain ID to open
814 private function openForeignConnection( $i, $domain ) {
815 $domainInstance = DatabaseDomain
::newFromId( $domain );
816 $dbName = $domainInstance->getDatabase();
817 $prefix = $domainInstance->getTablePrefix();
819 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
820 // Reuse an already-used connection
821 $conn = $this->mConns
['foreignUsed'][$i][$domain];
822 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
823 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
824 // Reuse a free connection for the same domain
825 $conn = $this->mConns
['foreignFree'][$i][$domain];
826 unset( $this->mConns
['foreignFree'][$i][$domain] );
827 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
828 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
829 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
830 // Reuse a connection from another domain
831 $conn = reset( $this->mConns
['foreignFree'][$i] );
832 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
833 // The empty string as a DB name means "don't care".
834 // DatabaseMysqlBase::open() already handle this on connection.
835 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
836 $this->mLastError
= "Error selecting database '$dbName' on server " .
837 $conn->getServer() . " from client host {$this->host}";
838 $this->errorConnection
= $conn;
841 $conn->tablePrefix( $prefix );
842 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
843 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
844 $this->connLogger
->debug( __METHOD__
.
845 ": reusing free connection from $oldDomain for $domain" );
848 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
849 throw new InvalidArgumentException( "No server with index '$i'." );
851 // Open a new connection
852 $server = $this->mServers
[$i];
853 $server['serverIndex'] = $i;
854 $server['foreignPoolRefCount'] = 0;
855 $server['foreign'] = true;
856 $conn = $this->reallyOpenConnection( $server, $dbName );
857 if ( !$conn->isOpen() ) {
858 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
859 $this->errorConnection
= $conn;
862 $conn->tablePrefix( $prefix );
863 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
864 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
868 // Increment reference count
869 if ( $conn instanceof IDatabase
) {
870 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
871 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
878 * Test if the specified index represents an open connection
880 * @param int $index Server index
884 private function isOpen( $index ) {
885 if ( !is_integer( $index ) ) {
889 return (bool)$this->getAnyOpenConnection( $index );
893 * Really opens a connection. Uncached.
894 * Returns a Database object whether or not the connection was successful.
897 * @param array $server
898 * @param string|bool $dbNameOverride Use "" to not select any database
900 * @throws DBAccessError
901 * @throws InvalidArgumentException
903 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
904 if ( $this->disabled
) {
905 throw new DBAccessError();
908 if ( $dbNameOverride !== false ) {
909 $server['dbname'] = $dbNameOverride;
912 // Let the handle know what the cluster master is (e.g. "db1052")
913 $masterName = $this->getServerName( $this->getWriterIndex() );
914 $server['clusterMasterHost'] = $masterName;
916 // Log when many connection are made on requests
917 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
918 $this->perfLogger
->warning( __METHOD__
. ": " .
919 "{$this->connsOpened}+ connections made (master=$masterName)" );
922 $server['srvCache'] = $this->srvCache
;
923 // Set loggers and profilers
924 $server['connLogger'] = $this->connLogger
;
925 $server['queryLogger'] = $this->queryLogger
;
926 $server['errorLogger'] = $this->errorLogger
;
927 $server['profiler'] = $this->profiler
;
928 $server['trxProfiler'] = $this->trxProfiler
;
929 // Use the same agent and PHP mode for all DB handles
930 $server['cliMode'] = $this->cliMode
;
931 $server['agent'] = $this->agent
;
932 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
933 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
934 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
936 // Create a live connection object
938 $db = Database
::factory( $server['type'], $server );
939 } catch ( DBConnectionError
$e ) {
940 // FIXME: This is probably the ugliest thing I have ever done to
941 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
945 $db->setLBInfo( $server );
946 $db->setLazyMasterHandle(
947 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
949 $db->setTableAliases( $this->tableAliases
);
951 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
952 if ( $this->trxRoundId
!== false ) {
953 $this->applyTransactionRoundFlags( $db );
955 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
956 $db->setTransactionListener( $name, $callback );
964 * @throws DBConnectionError
966 private function reportConnectionError() {
967 $conn = $this->errorConnection
; // the connection which caused the error
969 'method' => __METHOD__
,
970 'last_error' => $this->mLastError
,
973 if ( $conn instanceof IDatabase
) {
974 $context['db_server'] = $conn->getServer();
975 $this->connLogger
->warning(
976 "Connection error: {last_error} ({db_server})",
980 // throws DBConnectionError
981 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
983 // No last connection, probably due to all servers being too busy
984 $this->connLogger
->error(
985 "LB failure with no last connection. Connection error: {last_error}",
989 // If all servers were busy, mLastError will contain something sensible
990 throw new DBConnectionError( null, $this->mLastError
);
994 public function getWriterIndex() {
998 public function haveIndex( $i ) {
999 return array_key_exists( $i, $this->mServers
);
1002 public function isNonZeroLoad( $i ) {
1003 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
1006 public function getServerCount() {
1007 return count( $this->mServers
);
1010 public function getServerName( $i ) {
1011 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
1012 $name = $this->mServers
[$i]['hostName'];
1013 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
1014 $name = $this->mServers
[$i]['host'];
1019 return ( $name != '' ) ?
$name : 'localhost';
1022 public function getServerInfo( $i ) {
1023 if ( isset( $this->mServers
[$i] ) ) {
1024 return $this->mServers
[$i];
1030 public function setServerInfo( $i, array $serverInfo ) {
1031 $this->mServers
[$i] = $serverInfo;
1034 public function getMasterPos() {
1035 # If this entire request was served from a replica DB without opening a connection to the
1036 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1037 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1038 if ( !$masterConn ) {
1039 $serverCount = count( $this->mServers
);
1040 for ( $i = 1; $i < $serverCount; $i++
) {
1041 $conn = $this->getAnyOpenConnection( $i );
1043 return $conn->getReplicaPos();
1047 return $masterConn->getMasterPos();
1053 public function disable() {
1055 $this->disabled
= true;
1058 public function closeAll() {
1059 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1060 $host = $conn->getServer();
1061 $this->connLogger
->debug( "Closing connection to database '$host'." );
1067 'foreignFree' => [],
1068 'foreignUsed' => [],
1070 $this->connsOpened
= 0;
1073 public function closeConnection( IDatabase
$conn ) {
1074 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1075 foreach ( $this->mConns
as $type => $connsByServer ) {
1076 if ( !isset( $connsByServer[$serverIndex] ) ) {
1080 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1081 if ( $conn === $trackedConn ) {
1082 $host = $this->getServerName( $i );
1083 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1084 unset( $this->mConns
[$type][$serverIndex][$i] );
1085 --$this->connsOpened
;
1094 public function commitAll( $fname = __METHOD__
) {
1097 $restore = ( $this->trxRoundId
!== false );
1098 $this->trxRoundId
= false;
1099 $this->forEachOpenConnection(
1100 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1102 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1103 } catch ( DBError
$e ) {
1104 call_user_func( $this->errorLogger
, $e );
1105 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1107 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1108 $this->undoTransactionRoundFlags( $conn );
1114 throw new DBExpectedError(
1116 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1121 public function finalizeMasterChanges() {
1122 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1123 // Any error should cause all DB transactions to be rolled back together
1124 $conn->setTrxEndCallbackSuppression( false );
1125 $conn->runOnTransactionPreCommitCallbacks();
1126 // Defer post-commit callbacks until COMMIT finishes for all DBs
1127 $conn->setTrxEndCallbackSuppression( true );
1131 public function approveMasterChanges( array $options ) {
1132 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1133 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1134 // If atomic sections or explicit transactions are still open, some caller must have
1135 // caught an exception but failed to properly rollback any changes. Detect that and
1136 // throw and error (causing rollback).
1137 if ( $conn->explicitTrxActive() ) {
1138 throw new DBTransactionError(
1140 "Explicit transaction still active. A caller may have caught an error."
1143 // Assert that the time to replicate the transaction will be sane.
1144 // If this fails, then all DB transactions will be rollback back together.
1145 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1146 if ( $limit > 0 && $time > $limit ) {
1147 throw new DBTransactionSizeError(
1149 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1153 // If a connection sits idle while slow queries execute on another, that connection
1154 // may end up dropped before the commit round is reached. Ping servers to detect this.
1155 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1156 throw new DBTransactionError(
1158 "A connection to the {$conn->getDBname()} database was lost before commit."
1164 public function beginMasterChanges( $fname = __METHOD__
) {
1165 if ( $this->trxRoundId
!== false ) {
1166 throw new DBTransactionError(
1168 "$fname: Transaction round '{$this->trxRoundId}' already started."
1171 $this->trxRoundId
= $fname;
1174 $this->forEachOpenMasterConnection(
1175 function ( Database
$conn ) use ( $fname, &$failures ) {
1176 $conn->setTrxEndCallbackSuppression( true );
1178 $conn->flushSnapshot( $fname );
1179 } catch ( DBError
$e ) {
1180 call_user_func( $this->errorLogger
, $e );
1181 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1183 $conn->setTrxEndCallbackSuppression( false );
1184 $this->applyTransactionRoundFlags( $conn );
1189 throw new DBExpectedError(
1191 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1196 public function commitMasterChanges( $fname = __METHOD__
) {
1199 /** @noinspection PhpUnusedLocalVariableInspection */
1200 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1202 $restore = ( $this->trxRoundId
!== false );
1203 $this->trxRoundId
= false;
1204 $this->forEachOpenMasterConnection(
1205 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1207 if ( $conn->writesOrCallbacksPending() ) {
1208 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1209 } elseif ( $restore ) {
1210 $conn->flushSnapshot( $fname );
1212 } catch ( DBError
$e ) {
1213 call_user_func( $this->errorLogger
, $e );
1214 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1217 $this->undoTransactionRoundFlags( $conn );
1223 throw new DBExpectedError(
1225 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1230 public function runMasterPostTrxCallbacks( $type ) {
1231 $e = null; // first exception
1232 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1233 $conn->setTrxEndCallbackSuppression( false );
1234 if ( $conn->writesOrCallbacksPending() ) {
1235 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1236 // (which finished its callbacks already). Warn and recover in this case. Let the
1237 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1238 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1240 } elseif ( $conn->trxLevel() ) {
1241 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1242 // thus leaving an implicit read-only transaction open at this point. It
1243 // also happens if onTransactionIdle() callbacks leave implicit transactions
1244 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1245 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1249 $conn->runOnTransactionIdleCallbacks( $type );
1250 } catch ( Exception
$ex ) {
1254 $conn->runTransactionListenerCallbacks( $type );
1255 } catch ( Exception
$ex ) {
1263 public function rollbackMasterChanges( $fname = __METHOD__
) {
1264 $restore = ( $this->trxRoundId
!== false );
1265 $this->trxRoundId
= false;
1266 $this->forEachOpenMasterConnection(
1267 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1268 if ( $conn->writesOrCallbacksPending() ) {
1269 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1272 $this->undoTransactionRoundFlags( $conn );
1278 public function suppressTransactionEndCallbacks() {
1279 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1280 $conn->setTrxEndCallbackSuppression( true );
1285 * @param IDatabase $conn
1287 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1288 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1289 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1290 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1291 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1292 // If config has explicitly requested DBO_TRX be either on or off by not
1293 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1294 // for things like blob stores (ExternalStore) which want auto-commit mode.
1299 * @param IDatabase $conn
1301 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1302 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1303 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1307 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1308 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1309 $conn->flushSnapshot( __METHOD__
);
1313 public function hasMasterConnection() {
1314 return $this->isOpen( $this->getWriterIndex() );
1317 public function hasMasterChanges() {
1319 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1320 $pending |
= $conn->writesOrCallbacksPending();
1323 return (bool)$pending;
1326 public function lastMasterChangeTimestamp() {
1328 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1329 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1335 public function hasOrMadeRecentMasterChanges( $age = null ) {
1336 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1338 return ( $this->hasMasterChanges()
1339 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1342 public function pendingMasterChangeCallers() {
1344 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1345 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1351 public function getLaggedReplicaMode( $domain = false ) {
1352 // No-op if there is only one DB (also avoids recursion)
1353 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1355 // See if laggedReplicaMode gets set
1356 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1357 $this->reuseConnection( $conn );
1358 } catch ( DBConnectionError
$e ) {
1359 // Avoid expensive re-connect attempts and failures
1360 $this->allReplicasDownMode
= true;
1361 $this->laggedReplicaMode
= true;
1365 return $this->laggedReplicaMode
;
1369 * @param bool $domain
1371 * @deprecated 1.28; use getLaggedReplicaMode()
1373 public function getLaggedSlaveMode( $domain = false ) {
1374 return $this->getLaggedReplicaMode( $domain );
1377 public function laggedReplicaUsed() {
1378 return $this->laggedReplicaMode
;
1384 * @deprecated Since 1.28; use laggedReplicaUsed()
1386 public function laggedSlaveUsed() {
1387 return $this->laggedReplicaUsed();
1390 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1391 if ( $this->readOnlyReason
!== false ) {
1392 return $this->readOnlyReason
;
1393 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1394 if ( $this->allReplicasDownMode
) {
1395 return 'The database has been automatically locked ' .
1396 'until the replica database servers become available';
1398 return 'The database has been automatically locked ' .
1399 'while the replica database servers catch up to the master.';
1401 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1402 return 'The database master is running in read-only mode.';
1409 * @param string $domain Domain ID, or false for the current domain
1410 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1413 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1414 $cache = $this->wanCache
;
1415 $masterServer = $this->getServerName( $this->getWriterIndex() );
1417 return (bool)$cache->getWithSetCallback(
1418 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1419 self
::TTL_CACHE_READONLY
,
1420 function () use ( $domain, $conn ) {
1421 $old = $this->trxProfiler
->setSilenced( true );
1423 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1424 $readOnly = (int)$dbw->serverIsReadOnly();
1426 $this->reuseConnection( $dbw );
1428 } catch ( DBError
$e ) {
1431 $this->trxProfiler
->setSilenced( $old );
1434 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1438 public function allowLagged( $mode = null ) {
1439 if ( $mode === null ) {
1440 return $this->mAllowLagged
;
1442 $this->mAllowLagged
= $mode;
1444 return $this->mAllowLagged
;
1447 public function pingAll() {
1449 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1450 if ( !$conn->ping() ) {
1458 public function forEachOpenConnection( $callback, array $params = [] ) {
1459 foreach ( $this->mConns
as $connsByServer ) {
1460 foreach ( $connsByServer as $serverConns ) {
1461 foreach ( $serverConns as $conn ) {
1462 $mergedParams = array_merge( [ $conn ], $params );
1463 call_user_func_array( $callback, $mergedParams );
1469 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1470 $masterIndex = $this->getWriterIndex();
1471 foreach ( $this->mConns
as $connsByServer ) {
1472 if ( isset( $connsByServer[$masterIndex] ) ) {
1473 /** @var IDatabase $conn */
1474 foreach ( $connsByServer[$masterIndex] as $conn ) {
1475 $mergedParams = array_merge( [ $conn ], $params );
1476 call_user_func_array( $callback, $mergedParams );
1482 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1483 foreach ( $this->mConns
as $connsByServer ) {
1484 foreach ( $connsByServer as $i => $serverConns ) {
1485 if ( $i === $this->getWriterIndex() ) {
1486 continue; // skip master
1488 foreach ( $serverConns as $conn ) {
1489 $mergedParams = array_merge( [ $conn ], $params );
1490 call_user_func_array( $callback, $mergedParams );
1496 public function getMaxLag( $domain = false ) {
1501 if ( $this->getServerCount() <= 1 ) {
1502 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1505 $lagTimes = $this->getLagTimes( $domain );
1506 foreach ( $lagTimes as $i => $lag ) {
1507 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1509 $host = $this->mServers
[$i]['host'];
1514 return [ $host, $maxLag, $maxIndex ];
1517 public function getLagTimes( $domain = false ) {
1518 if ( $this->getServerCount() <= 1 ) {
1519 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1522 $knownLagTimes = []; // map of (server index => 0 seconds)
1523 $indexesWithLag = [];
1524 foreach ( $this->mServers
as $i => $server ) {
1525 if ( empty( $server['is static'] ) ) {
1526 $indexesWithLag[] = $i; // DB server might have replication lag
1528 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1532 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1535 public function safeGetLag( IDatabase
$conn ) {
1536 if ( $this->getServerCount() <= 1 ) {
1539 return $conn->getLag();
1544 * @param IDatabase $conn
1545 * @param DBMasterPos|bool $pos
1546 * @param int $timeout
1549 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1550 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1551 return true; // server is not a replica DB
1555 // Get the current master position, opening a connection if needed
1556 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1557 if ( $masterConn ) {
1558 $pos = $masterConn->getMasterPos();
1560 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1561 $pos = $masterConn->getMasterPos();
1562 $this->closeConnection( $masterConn );
1566 if ( $pos instanceof DBMasterPos
) {
1567 $result = $conn->masterPosWait( $pos, $timeout );
1568 if ( $result == -1 ||
is_null( $result ) ) {
1569 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1570 $this->replLogger
->warning( "$msg" );
1573 $this->replLogger
->info( __METHOD__
. ": Done" );
1577 $ok = false; // something is misconfigured
1578 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1584 public function setTransactionListener( $name, callable
$callback = null ) {
1586 $this->trxRecurringCallbacks
[$name] = $callback;
1588 unset( $this->trxRecurringCallbacks
[$name] );
1590 $this->forEachOpenMasterConnection(
1591 function ( IDatabase
$conn ) use ( $name, $callback ) {
1592 $conn->setTransactionListener( $name, $callback );
1597 public function setTableAliases( array $aliases ) {
1598 $this->tableAliases
= $aliases;
1601 public function setDomainPrefix( $prefix ) {
1602 if ( $this->mConns
['foreignUsed'] ) {
1603 // Do not switch connections to explicit foreign domains unless marked as free
1605 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1606 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1608 $domains = implode( ', ', $domains );
1609 throw new DBUnexpectedError( null,
1610 "Foreign domain connections are still in use ($domains)." );
1613 $this->localDomain
= new DatabaseDomain(
1614 $this->localDomain
->getDatabase(),
1619 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1620 $db->tablePrefix( $prefix );
1625 * Make PHP ignore user aborts/disconnects until the returned
1626 * value leaves scope. This returns null and does nothing in CLI mode.
1628 * @return ScopedCallback|null
1630 final protected function getScopedPHPBehaviorForCommit() {
1631 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1632 $old = ignore_user_abort( true ); // avoid half-finished operations
1633 return new ScopedCallback( function () use ( $old ) {
1634 ignore_user_abort( $old );
1641 function __destruct() {
1642 // Avoid connection leaks for sanity
1647 class_alias( LoadBalancer
::class, 'LoadBalancer' );