3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 namespace Wikimedia\Rdbms
;
25 use Psr\Log\LoggerInterface
;
26 use Psr\Log\NullLogger
;
27 use Wikimedia\ScopedCallback
;
30 use MaintainableDBConnRef
;
38 use DBUnexpectedError
;
39 use DBTransactionError
;
40 use DBTransactionSizeError
;
41 use DBConnectionError
;
42 use InvalidArgumentException
;
47 * Database connection, tracking, load balancing, and transaction manager for a cluster
51 class LoadBalancer
implements ILoadBalancer
{
52 /** @var array[] Map of (server index => server config array) */
54 /** @var \Database[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
56 /** @var float[] Map of (server index => weight) */
58 /** @var array[] Map of (group => server index => weight) */
60 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
61 private $mAllowLagged;
62 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
63 private $mWaitTimeout;
64 /** @var array The LoadMonitor configuration */
65 private $loadMonitorConfig;
66 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
67 private $tableAliases = [];
69 /** @var ILoadMonitor */
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 /** @var integer Warn when this many connection are held */
128 const CONN_HELD_WARN_THRESHOLD
= 10;
130 /** @var integer Default 'max lag' when unspecified */
131 const MAX_LAG_DEFAULT
= 10;
132 /** @var integer Seconds to cache master server read-only status */
133 const TTL_CACHE_READONLY
= 5;
135 public function __construct( array $params ) {
136 if ( !isset( $params['servers'] ) ) {
137 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
139 $this->mServers
= $params['servers'];
141 $this->localDomain
= isset( $params['localDomain'] )
142 ? DatabaseDomain
::newFromId( $params['localDomain'] )
143 : DatabaseDomain
::newUnspecified();
144 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
145 // always true, gracefully handle the case when they fail to account for escaping.
146 if ( $this->localDomain
->getTablePrefix() != '' ) {
147 $this->localDomainIdAlias
=
148 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
150 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
153 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
155 $this->mReadIndex
= -1;
162 $this->mWaitForPos
= false;
163 $this->mAllowLagged
= false;
165 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
166 $this->readOnlyReason
= $params['readOnlyReason'];
169 if ( isset( $params['loadMonitor'] ) ) {
170 $this->loadMonitorConfig
= $params['loadMonitor'];
172 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
175 foreach ( $params['servers'] as $i => $server ) {
176 $this->mLoads
[$i] = $server['load'];
177 if ( isset( $server['groupLoads'] ) ) {
178 foreach ( $server['groupLoads'] as $group => $ratio ) {
179 if ( !isset( $this->mGroupLoads
[$group] ) ) {
180 $this->mGroupLoads
[$group] = [];
182 $this->mGroupLoads
[$group][$i] = $ratio;
187 if ( isset( $params['srvCache'] ) ) {
188 $this->srvCache
= $params['srvCache'];
190 $this->srvCache
= new EmptyBagOStuff();
192 if ( isset( $params['memCache'] ) ) {
193 $this->memCache
= $params['memCache'];
195 $this->memCache
= new EmptyBagOStuff();
197 if ( isset( $params['wanCache'] ) ) {
198 $this->wanCache
= $params['wanCache'];
200 $this->wanCache
= WANObjectCache
::newEmpty();
202 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
203 if ( isset( $params['trxProfiler'] ) ) {
204 $this->trxProfiler
= $params['trxProfiler'];
206 $this->trxProfiler
= new TransactionProfiler();
209 $this->errorLogger
= isset( $params['errorLogger'] )
210 ?
$params['errorLogger']
211 : function ( Exception
$e ) {
212 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
215 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
216 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
219 $this->host
= isset( $params['hostname'] )
220 ?
$params['hostname']
221 : ( gethostname() ?
: 'unknown' );
222 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
223 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
227 * Get a LoadMonitor instance
229 * @return ILoadMonitor
231 private function getLoadMonitor() {
232 if ( !isset( $this->loadMonitor
) ) {
234 'LoadMonitor' => LoadMonitor
::class,
235 'LoadMonitorNull' => LoadMonitorNull
::class,
236 'LoadMonitorMySQL' => LoadMonitorMySQL
::class,
239 $class = $this->loadMonitorConfig
['class'];
240 if ( isset( $compat[$class] ) ) {
241 $class = $compat[$class];
244 $this->loadMonitor
= new $class(
245 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
246 $this->loadMonitor
->setLogger( $this->replLogger
);
249 return $this->loadMonitor
;
253 * @param array $loads
254 * @param bool|string $domain Domain to get non-lagged for
255 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
256 * @return bool|int|string
258 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
259 $lags = $this->getLagTimes( $domain );
261 # Unset excessively lagged servers
262 foreach ( $lags as $i => $lag ) {
264 # How much lag this server nominally is allowed to have
265 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
266 ?
$this->mServers
[$i]['max lag']
267 : self
::MAX_LAG_DEFAULT
; // default
268 # Constrain that futher by $maxLag argument
269 $maxServerLag = min( $maxServerLag, $maxLag );
271 $host = $this->getServerName( $i );
272 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
273 $this->replLogger
->error(
274 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
276 } elseif ( $lag > $maxServerLag ) {
277 $this->replLogger
->warning(
278 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
279 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
286 # Find out if all the replica DBs with non-zero load are lagged
288 foreach ( $loads as $load ) {
292 # No appropriate DB servers except maybe the master and some replica DBs with zero load
293 # Do NOT use the master
294 # Instead, this function will return false, triggering read-only mode,
295 # and a lagged replica DB will be used instead.
299 if ( count( $loads ) == 0 ) {
303 # Return a random representative of the remainder
304 return ArrayUtils
::pickRandom( $loads );
307 public function getReaderIndex( $group = false, $domain = false ) {
308 if ( count( $this->mServers
) == 1 ) {
309 # Skip the load balancing if there's only one server
310 return $this->getWriterIndex();
311 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
312 # Shortcut if generic reader exists already
313 return $this->mReadIndex
;
316 # Find the relevant load array
317 if ( $group !== false ) {
318 if ( isset( $this->mGroupLoads
[$group] ) ) {
319 $nonErrorLoads = $this->mGroupLoads
[$group];
321 # No loads for this group, return false and the caller can use some other group
322 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
327 $nonErrorLoads = $this->mLoads
;
330 if ( !count( $nonErrorLoads ) ) {
331 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
334 # Scale the configured load ratios according to the dynamic load if supported
335 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
337 $laggedReplicaMode = false;
339 # No server found yet
341 # First try quickly looking through the available servers for a server that
343 $currentLoads = $nonErrorLoads;
344 while ( count( $currentLoads ) ) {
345 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
346 $i = ArrayUtils
::pickRandom( $currentLoads );
349 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
350 # ChronologyProtecter causes mWaitForPos to be set via sessions.
351 # This triggers doWait() after connect, so it's especially good to
352 # avoid lagged servers so as to avoid just blocking in that method.
353 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
354 # Aim for <= 1 second of waiting (being too picky can backfire)
355 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
357 if ( $i === false ) {
358 # Any server with less lag than it's 'max lag' param is preferable
359 $i = $this->getRandomNonLagged( $currentLoads, $domain );
361 if ( $i === false && count( $currentLoads ) != 0 ) {
362 # All replica DBs lagged. Switch to read-only mode
363 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
364 $i = ArrayUtils
::pickRandom( $currentLoads );
365 $laggedReplicaMode = true;
369 if ( $i === false ) {
370 # pickRandom() returned false
371 # This is permanent and means the configuration or the load monitor
372 # wants us to return false.
373 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
378 $serverName = $this->getServerName( $i );
379 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
381 $conn = $this->openConnection( $i, $domain );
383 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
384 unset( $nonErrorLoads[$i] );
385 unset( $currentLoads[$i] );
390 // Decrement reference counter, we are finished with this connection.
391 // It will be incremented for the caller later.
392 if ( $domain !== false ) {
393 $this->reuseConnection( $conn );
400 # If all servers were down, quit now
401 if ( !count( $nonErrorLoads ) ) {
402 $this->connLogger
->error( "All servers down" );
405 if ( $i !== false ) {
406 # Replica DB connection successful.
407 # Wait for the session master pos for a short time.
408 if ( $this->mWaitForPos
&& $i > 0 ) {
411 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
412 $this->mReadIndex
= $i;
413 # Record if the generic reader index is in "lagged replica DB" mode
414 if ( $laggedReplicaMode ) {
415 $this->laggedReplicaMode
= true;
418 $serverName = $this->getServerName( $i );
419 $this->connLogger
->debug(
420 __METHOD__
. ": using server $serverName for group '$group'" );
427 * @param DBMasterPos|false $pos
429 public function waitFor( $pos ) {
430 $this->mWaitForPos
= $pos;
431 $i = $this->mReadIndex
;
434 if ( !$this->doWait( $i ) ) {
435 $this->laggedReplicaMode
= true;
440 public function waitForOne( $pos, $timeout = null ) {
441 $this->mWaitForPos
= $pos;
443 $i = $this->mReadIndex
;
445 // Pick a generic replica DB if there isn't one yet
446 $readLoads = $this->mLoads
;
447 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
448 $readLoads = array_filter( $readLoads ); // with non-zero load
449 $i = ArrayUtils
::pickRandom( $readLoads );
453 $ok = $this->doWait( $i, true, $timeout );
455 $ok = true; // no applicable loads
461 public function waitForAll( $pos, $timeout = null ) {
462 $this->mWaitForPos
= $pos;
463 $serverCount = count( $this->mServers
);
466 for ( $i = 1; $i < $serverCount; $i++
) {
467 if ( $this->mLoads
[$i] > 0 ) {
468 $ok = $this->doWait( $i, true, $timeout ) && $ok;
477 * @return IDatabase|bool
479 public function getAnyOpenConnection( $i ) {
480 foreach ( $this->mConns
as $connsByServer ) {
481 if ( !empty( $connsByServer[$i] ) ) {
482 /** @var $serverConns IDatabase[] */
483 $serverConns = $connsByServer[$i];
485 return reset( $serverConns );
493 * Wait for a given replica DB to catch up to the master pos stored in $this
494 * @param int $index Server index
495 * @param bool $open Check the server even if a new connection has to be made
496 * @param int $timeout Max seconds to wait; default is mWaitTimeout
499 protected function doWait( $index, $open = false, $timeout = null ) {
500 $close = false; // close the connection afterwards
502 // Check if we already know that the DB has reached this point
503 $server = $this->getServerName( $index );
504 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server, 'v1' );
505 /** @var DBMasterPos $knownReachedPos */
506 $knownReachedPos = $this->srvCache
->get( $key );
508 $knownReachedPos instanceof DBMasterPos
&&
509 $knownReachedPos->hasReached( $this->mWaitForPos
)
511 $this->replLogger
->debug( __METHOD__
.
512 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
516 // Find a connection to wait on, creating one if needed and allowed
517 $conn = $this->getAnyOpenConnection( $index );
520 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
524 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
526 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
530 // Avoid connection spam in waitForAll() when connections
531 // are made just for the sake of doing this lag check.
536 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
537 $timeout = $timeout ?
: $this->mWaitTimeout
;
538 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
540 if ( $result == -1 ||
is_null( $result ) ) {
541 // Timed out waiting for replica DB, use master instead
542 $this->replLogger
->warning(
543 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
544 [ 'host' => $server ]
548 $this->replLogger
->info( __METHOD__
. ": Done" );
550 // Remember that the DB reached this point
551 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
555 $this->closeConnection( $conn );
562 * @see ILoadBalancer::getConnection()
565 * @param array $groups
566 * @param bool $domain
568 * @throws DBConnectionError
570 public function getConnection( $i, $groups = [], $domain = false ) {
571 if ( $i === null ||
$i === false ) {
572 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
573 ' with invalid server index' );
576 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
577 $domain = false; // local connection requested
580 $groups = ( $groups === false ||
$groups === [] )
581 ?
[ false ] // check one "group": the generic pool
584 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
585 $oldConnsOpened = $this->connsOpened
; // connections open now
587 if ( $i == self
::DB_MASTER
) {
588 $i = $this->getWriterIndex();
590 # Try to find an available server in any the query groups (in order)
591 foreach ( $groups as $group ) {
592 $groupIndex = $this->getReaderIndex( $group, $domain );
593 if ( $groupIndex !== false ) {
600 # Operation-based index
601 if ( $i == self
::DB_REPLICA
) {
602 $this->mLastError
= 'Unknown error'; // reset error string
603 # Try the general server pool if $groups are unavailable.
604 $i = ( $groups === [ false ] )
605 ?
false // don't bother with this if that is what was tried above
606 : $this->getReaderIndex( false, $domain );
607 # Couldn't find a working server in getReaderIndex()?
608 if ( $i === false ) {
609 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
610 // Throw an exception
611 $this->reportConnectionError();
612 return null; // not reached
616 # Now we have an explicit index into the servers array
617 $conn = $this->openConnection( $i, $domain );
619 // Throw an exception
620 $this->reportConnectionError();
621 return null; // not reached
624 # Profile any new connections that happen
625 if ( $this->connsOpened
> $oldConnsOpened ) {
626 $host = $conn->getServer();
627 $dbname = $conn->getDBname();
628 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
632 # Make master-requested DB handles inherit any read-only mode setting
633 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
639 public function reuseConnection( $conn ) {
640 $serverIndex = $conn->getLBInfo( 'serverIndex' );
641 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
642 if ( $serverIndex === null ||
$refCount === null ) {
644 * This can happen in code like:
645 * foreach ( $dbs as $db ) {
646 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
648 * $lb->reuseConnection( $conn );
650 * When a connection to the local DB is opened in this way, reuseConnection()
654 } elseif ( $conn instanceof DBConnRef
) {
655 // DBConnRef already handles calling reuseConnection() and only passes the live
656 // Database instance to this method. Any caller passing in a DBConnRef is broken.
657 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
658 ( new RuntimeException() )->getTraceAsString() );
663 if ( $this->disabled
) {
664 return; // DBConnRef handle probably survived longer than the LoadBalancer
667 $domain = $conn->getDomainID();
668 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
669 throw new InvalidArgumentException( __METHOD__
.
670 ": connection $serverIndex/$domain not found; it may have already been freed." );
671 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
672 throw new InvalidArgumentException( __METHOD__
.
673 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
675 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
676 if ( $refCount <= 0 ) {
677 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
678 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
679 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
680 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
682 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
684 $this->connLogger
->debug( __METHOD__
.
685 ": reference count for $serverIndex/$domain reduced to $refCount" );
689 public function getConnectionRef( $db, $groups = [], $domain = false ) {
690 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
692 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
695 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
696 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
698 return new DBConnRef( $this, [ $db, $groups, $domain ] );
701 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
702 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
704 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
708 * @see ILoadBalancer::openConnection()
711 * @param bool $domain
712 * @return bool|Database
713 * @throws DBAccessError
715 public function openConnection( $i, $domain = false ) {
716 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
717 $domain = false; // local connection requested
720 if ( $domain !== false ) {
721 $conn = $this->openForeignConnection( $i, $domain );
722 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
723 $conn = $this->mConns
['local'][$i][0];
725 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
726 throw new InvalidArgumentException( "No server with index '$i'." );
728 // Open a new connection
729 $server = $this->mServers
[$i];
730 $server['serverIndex'] = $i;
731 $conn = $this->reallyOpenConnection( $server, false );
732 $serverName = $this->getServerName( $i );
733 if ( $conn->isOpen() ) {
734 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
735 $this->mConns
['local'][$i][0] = $conn;
737 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
738 $this->errorConnection
= $conn;
743 if ( $conn instanceof IDatabase
&& !$conn->isOpen() ) {
744 // Connection was made but later unrecoverably lost for some reason.
745 // Do not return a handle that will just throw exceptions on use,
746 // but let the calling code (e.g. getReaderIndex) try another server.
747 // See DatabaseMyslBase::ping() for how this can happen.
748 $this->errorConnection
= $conn;
756 * Open a connection to a foreign DB, or return one if it is already open.
758 * Increments a reference count on the returned connection which locks the
759 * connection to the requested domain. This reference count can be
760 * decremented by calling reuseConnection().
762 * If a connection is open to the appropriate server already, but with the wrong
763 * database, it will be switched to the right database and returned, as long as
764 * it has been freed first with reuseConnection().
766 * On error, returns false, and the connection which caused the
767 * error will be available via $this->errorConnection.
769 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
771 * @param int $i Server index
772 * @param string $domain Domain ID to open
775 private function openForeignConnection( $i, $domain ) {
776 $domainInstance = DatabaseDomain
::newFromId( $domain );
777 $dbName = $domainInstance->getDatabase();
778 $prefix = $domainInstance->getTablePrefix();
780 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
781 // Reuse an already-used connection
782 $conn = $this->mConns
['foreignUsed'][$i][$domain];
783 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
784 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
785 // Reuse a free connection for the same domain
786 $conn = $this->mConns
['foreignFree'][$i][$domain];
787 unset( $this->mConns
['foreignFree'][$i][$domain] );
788 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
789 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
790 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
791 // Reuse a connection from another domain
792 $conn = reset( $this->mConns
['foreignFree'][$i] );
793 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
794 // The empty string as a DB name means "don't care".
795 // DatabaseMysqlBase::open() already handle this on connection.
796 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
797 $this->mLastError
= "Error selecting database '$dbName' on server " .
798 $conn->getServer() . " from client host {$this->host}";
799 $this->errorConnection
= $conn;
802 $conn->tablePrefix( $prefix );
803 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
804 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
805 $this->connLogger
->debug( __METHOD__
.
806 ": reusing free connection from $oldDomain for $domain" );
809 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
810 throw new InvalidArgumentException( "No server with index '$i'." );
812 // Open a new connection
813 $server = $this->mServers
[$i];
814 $server['serverIndex'] = $i;
815 $server['foreignPoolRefCount'] = 0;
816 $server['foreign'] = true;
817 $conn = $this->reallyOpenConnection( $server, $dbName );
818 if ( !$conn->isOpen() ) {
819 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
820 $this->errorConnection
= $conn;
823 $conn->tablePrefix( $prefix );
824 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
825 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
829 // Increment reference count
830 if ( $conn instanceof IDatabase
) {
831 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
832 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
839 * Test if the specified index represents an open connection
841 * @param int $index Server index
845 private function isOpen( $index ) {
846 if ( !is_integer( $index ) ) {
850 return (bool)$this->getAnyOpenConnection( $index );
854 * Really opens a connection. Uncached.
855 * Returns a Database object whether or not the connection was successful.
858 * @param array $server
859 * @param string|bool $dbNameOverride Use "" to not select any database
861 * @throws DBAccessError
862 * @throws InvalidArgumentException
864 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
865 if ( $this->disabled
) {
866 throw new DBAccessError();
869 if ( $dbNameOverride !== false ) {
870 $server['dbname'] = $dbNameOverride;
873 // Let the handle know what the cluster master is (e.g. "db1052")
874 $masterName = $this->getServerName( $this->getWriterIndex() );
875 $server['clusterMasterHost'] = $masterName;
877 // Log when many connection are made on requests
878 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
879 $this->perfLogger
->warning( __METHOD__
. ": " .
880 "{$this->connsOpened}+ connections made (master=$masterName)" );
883 $server['srvCache'] = $this->srvCache
;
884 // Set loggers and profilers
885 $server['connLogger'] = $this->connLogger
;
886 $server['queryLogger'] = $this->queryLogger
;
887 $server['errorLogger'] = $this->errorLogger
;
888 $server['profiler'] = $this->profiler
;
889 $server['trxProfiler'] = $this->trxProfiler
;
890 // Use the same agent and PHP mode for all DB handles
891 $server['cliMode'] = $this->cliMode
;
892 $server['agent'] = $this->agent
;
893 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
894 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
895 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
897 // Create a live connection object
899 $db = Database
::factory( $server['type'], $server );
900 } catch ( DBConnectionError
$e ) {
901 // FIXME: This is probably the ugliest thing I have ever done to
902 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
906 $db->setLBInfo( $server );
907 $db->setLazyMasterHandle(
908 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
910 $db->setTableAliases( $this->tableAliases
);
912 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
913 if ( $this->trxRoundId
!== false ) {
914 $this->applyTransactionRoundFlags( $db );
916 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
917 $db->setTransactionListener( $name, $callback );
925 * @throws DBConnectionError
927 private function reportConnectionError() {
928 $conn = $this->errorConnection
; // the connection which caused the error
930 'method' => __METHOD__
,
931 'last_error' => $this->mLastError
,
934 if ( $conn instanceof IDatabase
) {
935 $context['db_server'] = $conn->getServer();
936 $this->connLogger
->warning(
937 "Connection error: {last_error} ({db_server})",
941 // throws DBConnectionError
942 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
944 // No last connection, probably due to all servers being too busy
945 $this->connLogger
->error(
946 "LB failure with no last connection. Connection error: {last_error}",
950 // If all servers were busy, mLastError will contain something sensible
951 throw new DBConnectionError( null, $this->mLastError
);
955 public function getWriterIndex() {
959 public function haveIndex( $i ) {
960 return array_key_exists( $i, $this->mServers
);
963 public function isNonZeroLoad( $i ) {
964 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
967 public function getServerCount() {
968 return count( $this->mServers
);
971 public function getServerName( $i ) {
972 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
973 $name = $this->mServers
[$i]['hostName'];
974 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
975 $name = $this->mServers
[$i]['host'];
980 return ( $name != '' ) ?
$name : 'localhost';
983 public function getServerInfo( $i ) {
984 if ( isset( $this->mServers
[$i] ) ) {
985 return $this->mServers
[$i];
991 public function setServerInfo( $i, array $serverInfo ) {
992 $this->mServers
[$i] = $serverInfo;
995 public function getMasterPos() {
996 # If this entire request was served from a replica DB without opening a connection to the
997 # master (however unlikely that may be), then we can fetch the position from the replica DB.
998 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
999 if ( !$masterConn ) {
1000 $serverCount = count( $this->mServers
);
1001 for ( $i = 1; $i < $serverCount; $i++
) {
1002 $conn = $this->getAnyOpenConnection( $i );
1004 return $conn->getReplicaPos();
1008 return $masterConn->getMasterPos();
1014 public function disable() {
1016 $this->disabled
= true;
1019 public function closeAll() {
1020 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1021 $host = $conn->getServer();
1022 $this->connLogger
->debug( "Closing connection to database '$host'." );
1028 'foreignFree' => [],
1029 'foreignUsed' => [],
1031 $this->connsOpened
= 0;
1034 public function closeConnection( IDatabase
$conn ) {
1035 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1036 foreach ( $this->mConns
as $type => $connsByServer ) {
1037 if ( !isset( $connsByServer[$serverIndex] ) ) {
1041 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1042 if ( $conn === $trackedConn ) {
1043 $host = $this->getServerName( $i );
1044 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1045 unset( $this->mConns
[$type][$serverIndex][$i] );
1046 --$this->connsOpened
;
1055 public function commitAll( $fname = __METHOD__
) {
1058 $restore = ( $this->trxRoundId
!== false );
1059 $this->trxRoundId
= false;
1060 $this->forEachOpenConnection(
1061 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1063 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1064 } catch ( DBError
$e ) {
1065 call_user_func( $this->errorLogger
, $e );
1066 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1068 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1069 $this->undoTransactionRoundFlags( $conn );
1075 throw new DBExpectedError(
1077 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1082 public function finalizeMasterChanges() {
1083 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1084 // Any error should cause all DB transactions to be rolled back together
1085 $conn->setTrxEndCallbackSuppression( false );
1086 $conn->runOnTransactionPreCommitCallbacks();
1087 // Defer post-commit callbacks until COMMIT finishes for all DBs
1088 $conn->setTrxEndCallbackSuppression( true );
1092 public function approveMasterChanges( array $options ) {
1093 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1094 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1095 // If atomic sections or explicit transactions are still open, some caller must have
1096 // caught an exception but failed to properly rollback any changes. Detect that and
1097 // throw and error (causing rollback).
1098 if ( $conn->explicitTrxActive() ) {
1099 throw new DBTransactionError(
1101 "Explicit transaction still active. A caller may have caught an error."
1104 // Assert that the time to replicate the transaction will be sane.
1105 // If this fails, then all DB transactions will be rollback back together.
1106 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1107 if ( $limit > 0 && $time > $limit ) {
1108 throw new DBTransactionSizeError(
1110 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1114 // If a connection sits idle while slow queries execute on another, that connection
1115 // may end up dropped before the commit round is reached. Ping servers to detect this.
1116 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1117 throw new DBTransactionError(
1119 "A connection to the {$conn->getDBname()} database was lost before commit."
1125 public function beginMasterChanges( $fname = __METHOD__
) {
1126 if ( $this->trxRoundId
!== false ) {
1127 throw new DBTransactionError(
1129 "$fname: Transaction round '{$this->trxRoundId}' already started."
1132 $this->trxRoundId
= $fname;
1135 $this->forEachOpenMasterConnection(
1136 function ( Database
$conn ) use ( $fname, &$failures ) {
1137 $conn->setTrxEndCallbackSuppression( true );
1139 $conn->flushSnapshot( $fname );
1140 } catch ( DBError
$e ) {
1141 call_user_func( $this->errorLogger
, $e );
1142 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1144 $conn->setTrxEndCallbackSuppression( false );
1145 $this->applyTransactionRoundFlags( $conn );
1150 throw new DBExpectedError(
1152 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1157 public function commitMasterChanges( $fname = __METHOD__
) {
1160 /** @noinspection PhpUnusedLocalVariableInspection */
1161 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1163 $restore = ( $this->trxRoundId
!== false );
1164 $this->trxRoundId
= false;
1165 $this->forEachOpenMasterConnection(
1166 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1168 if ( $conn->writesOrCallbacksPending() ) {
1169 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1170 } elseif ( $restore ) {
1171 $conn->flushSnapshot( $fname );
1173 } catch ( DBError
$e ) {
1174 call_user_func( $this->errorLogger
, $e );
1175 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1178 $this->undoTransactionRoundFlags( $conn );
1184 throw new DBExpectedError(
1186 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1191 public function runMasterPostTrxCallbacks( $type ) {
1192 $e = null; // first exception
1193 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1194 $conn->setTrxEndCallbackSuppression( false );
1195 if ( $conn->writesOrCallbacksPending() ) {
1196 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1197 // (which finished its callbacks already). Warn and recover in this case. Let the
1198 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1199 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1201 } elseif ( $conn->trxLevel() ) {
1202 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1203 // thus leaving an implicit read-only transaction open at this point. It
1204 // also happens if onTransactionIdle() callbacks leave implicit transactions
1205 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1206 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1210 $conn->runOnTransactionIdleCallbacks( $type );
1211 } catch ( Exception
$ex ) {
1215 $conn->runTransactionListenerCallbacks( $type );
1216 } catch ( Exception
$ex ) {
1224 public function rollbackMasterChanges( $fname = __METHOD__
) {
1225 $restore = ( $this->trxRoundId
!== false );
1226 $this->trxRoundId
= false;
1227 $this->forEachOpenMasterConnection(
1228 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1229 if ( $conn->writesOrCallbacksPending() ) {
1230 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1233 $this->undoTransactionRoundFlags( $conn );
1239 public function suppressTransactionEndCallbacks() {
1240 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1241 $conn->setTrxEndCallbackSuppression( true );
1246 * @param IDatabase $conn
1248 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1249 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1250 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1251 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1252 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1253 // If config has explicitly requested DBO_TRX be either on or off by not
1254 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1255 // for things like blob stores (ExternalStore) which want auto-commit mode.
1260 * @param IDatabase $conn
1262 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1263 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1264 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1268 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1269 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1270 $conn->flushSnapshot( __METHOD__
);
1274 public function hasMasterConnection() {
1275 return $this->isOpen( $this->getWriterIndex() );
1278 public function hasMasterChanges() {
1280 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1281 $pending |
= $conn->writesOrCallbacksPending();
1284 return (bool)$pending;
1287 public function lastMasterChangeTimestamp() {
1289 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1290 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1296 public function hasOrMadeRecentMasterChanges( $age = null ) {
1297 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1299 return ( $this->hasMasterChanges()
1300 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1303 public function pendingMasterChangeCallers() {
1305 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1306 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1312 public function getLaggedReplicaMode( $domain = false ) {
1313 // No-op if there is only one DB (also avoids recursion)
1314 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1316 // See if laggedReplicaMode gets set
1317 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1318 $this->reuseConnection( $conn );
1319 } catch ( DBConnectionError
$e ) {
1320 // Avoid expensive re-connect attempts and failures
1321 $this->allReplicasDownMode
= true;
1322 $this->laggedReplicaMode
= true;
1326 return $this->laggedReplicaMode
;
1330 * @param bool $domain
1332 * @deprecated 1.28; use getLaggedReplicaMode()
1334 public function getLaggedSlaveMode( $domain = false ) {
1335 return $this->getLaggedReplicaMode( $domain );
1338 public function laggedReplicaUsed() {
1339 return $this->laggedReplicaMode
;
1345 * @deprecated Since 1.28; use laggedReplicaUsed()
1347 public function laggedSlaveUsed() {
1348 return $this->laggedReplicaUsed();
1351 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1352 if ( $this->readOnlyReason
!== false ) {
1353 return $this->readOnlyReason
;
1354 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1355 if ( $this->allReplicasDownMode
) {
1356 return 'The database has been automatically locked ' .
1357 'until the replica database servers become available';
1359 return 'The database has been automatically locked ' .
1360 'while the replica database servers catch up to the master.';
1362 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1363 return 'The database master is running in read-only mode.';
1370 * @param string $domain Domain ID, or false for the current domain
1371 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1374 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1375 $cache = $this->wanCache
;
1376 $masterServer = $this->getServerName( $this->getWriterIndex() );
1378 return (bool)$cache->getWithSetCallback(
1379 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1380 self
::TTL_CACHE_READONLY
,
1381 function () use ( $domain, $conn ) {
1382 $old = $this->trxProfiler
->setSilenced( true );
1384 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1385 $readOnly = (int)$dbw->serverIsReadOnly();
1387 $this->reuseConnection( $dbw );
1389 } catch ( DBError
$e ) {
1392 $this->trxProfiler
->setSilenced( $old );
1395 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1399 public function allowLagged( $mode = null ) {
1400 if ( $mode === null ) {
1401 return $this->mAllowLagged
;
1403 $this->mAllowLagged
= $mode;
1405 return $this->mAllowLagged
;
1408 public function pingAll() {
1410 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1411 if ( !$conn->ping() ) {
1419 public function forEachOpenConnection( $callback, array $params = [] ) {
1420 foreach ( $this->mConns
as $connsByServer ) {
1421 foreach ( $connsByServer as $serverConns ) {
1422 foreach ( $serverConns as $conn ) {
1423 $mergedParams = array_merge( [ $conn ], $params );
1424 call_user_func_array( $callback, $mergedParams );
1430 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1431 $masterIndex = $this->getWriterIndex();
1432 foreach ( $this->mConns
as $connsByServer ) {
1433 if ( isset( $connsByServer[$masterIndex] ) ) {
1434 /** @var IDatabase $conn */
1435 foreach ( $connsByServer[$masterIndex] as $conn ) {
1436 $mergedParams = array_merge( [ $conn ], $params );
1437 call_user_func_array( $callback, $mergedParams );
1443 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1444 foreach ( $this->mConns
as $connsByServer ) {
1445 foreach ( $connsByServer as $i => $serverConns ) {
1446 if ( $i === $this->getWriterIndex() ) {
1447 continue; // skip master
1449 foreach ( $serverConns as $conn ) {
1450 $mergedParams = array_merge( [ $conn ], $params );
1451 call_user_func_array( $callback, $mergedParams );
1457 public function getMaxLag( $domain = false ) {
1462 if ( $this->getServerCount() <= 1 ) {
1463 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1466 $lagTimes = $this->getLagTimes( $domain );
1467 foreach ( $lagTimes as $i => $lag ) {
1468 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1470 $host = $this->mServers
[$i]['host'];
1475 return [ $host, $maxLag, $maxIndex ];
1478 public function getLagTimes( $domain = false ) {
1479 if ( $this->getServerCount() <= 1 ) {
1480 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1483 $knownLagTimes = []; // map of (server index => 0 seconds)
1484 $indexesWithLag = [];
1485 foreach ( $this->mServers
as $i => $server ) {
1486 if ( empty( $server['is static'] ) ) {
1487 $indexesWithLag[] = $i; // DB server might have replication lag
1489 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1493 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1496 public function safeGetLag( IDatabase
$conn ) {
1497 if ( $this->getServerCount() <= 1 ) {
1500 return $conn->getLag();
1505 * @param IDatabase $conn
1506 * @param DBMasterPos|bool $pos
1507 * @param int $timeout
1510 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1511 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1512 return true; // server is not a replica DB
1516 // Get the current master position, opening a connection if needed
1517 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1518 if ( $masterConn ) {
1519 $pos = $masterConn->getMasterPos();
1521 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1522 $pos = $masterConn->getMasterPos();
1523 $this->closeConnection( $masterConn );
1527 if ( $pos instanceof DBMasterPos
) {
1528 $result = $conn->masterPosWait( $pos, $timeout );
1529 if ( $result == -1 ||
is_null( $result ) ) {
1530 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1531 $this->replLogger
->warning( "$msg" );
1534 $this->replLogger
->info( __METHOD__
. ": Done" );
1538 $ok = false; // something is misconfigured
1539 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1545 public function setTransactionListener( $name, callable
$callback = null ) {
1547 $this->trxRecurringCallbacks
[$name] = $callback;
1549 unset( $this->trxRecurringCallbacks
[$name] );
1551 $this->forEachOpenMasterConnection(
1552 function ( IDatabase
$conn ) use ( $name, $callback ) {
1553 $conn->setTransactionListener( $name, $callback );
1558 public function setTableAliases( array $aliases ) {
1559 $this->tableAliases
= $aliases;
1562 public function setDomainPrefix( $prefix ) {
1563 if ( $this->mConns
['foreignUsed'] ) {
1564 // Do not switch connections to explicit foreign domains unless marked as free
1566 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1567 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1569 $domains = implode( ', ', $domains );
1570 throw new DBUnexpectedError( null,
1571 "Foreign domain connections are still in use ($domains)." );
1574 $this->localDomain
= new DatabaseDomain(
1575 $this->localDomain
->getDatabase(),
1580 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1581 $db->tablePrefix( $prefix );
1586 * Make PHP ignore user aborts/disconnects until the returned
1587 * value leaves scope. This returns null and does nothing in CLI mode.
1589 * @return ScopedCallback|null
1591 final protected function getScopedPHPBehaviorForCommit() {
1592 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1593 $old = ignore_user_abort( true ); // avoid half-finished operations
1594 return new ScopedCallback( function () use ( $old ) {
1595 ignore_user_abort( $old );
1602 function __destruct() {
1603 // Avoid connection leaks for sanity
1608 class_alias( LoadBalancer
::class, 'LoadBalancer' );