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 use Psr\Log\LoggerInterface
;
24 use Psr\Log\NullLogger
;
25 use Wikimedia\ScopedCallback
;
26 use Wikimedia\Rdbms\TransactionProfiler
;
27 use Wikimedia\Rdbms\ILoadMonitor
;
28 use Wikimedia\Rdbms\DatabaseDomain
;
31 * Database connection, tracking, load balancing, and transaction manager for a cluster
35 class LoadBalancer
implements ILoadBalancer
{
36 /** @var array[] Map of (server index => server config array) */
38 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
40 /** @var float[] Map of (server index => weight) */
42 /** @var array[] Map of (group => server index => weight) */
44 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
45 private $mAllowLagged;
46 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
47 private $mWaitTimeout;
48 /** @var array The LoadMonitor configuration */
49 private $loadMonitorConfig;
50 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
51 private $tableAliases = [];
53 /** @var ILoadMonitor */
59 /** @var WANObjectCache */
61 /** @var object|string Class name or object With profileIn/profileOut methods */
63 /** @var TransactionProfiler */
64 protected $trxProfiler;
65 /** @var LoggerInterface */
66 protected $replLogger;
67 /** @var LoggerInterface */
68 protected $connLogger;
69 /** @var LoggerInterface */
70 protected $queryLogger;
71 /** @var LoggerInterface */
72 protected $perfLogger;
74 /** @var bool|IDatabase Database connection that caused a problem */
75 private $mErrorConnection;
76 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
78 /** @var bool|DBMasterPos False if not set */
80 /** @var bool Whether the generic reader fell back to a lagged replica DB */
81 private $laggedReplicaMode = false;
82 /** @var bool Whether the generic reader fell back to a lagged replica DB */
83 private $allReplicasDownMode = false;
84 /** @var string The last DB selection or connection error */
85 private $mLastError = 'Unknown error';
86 /** @var string|bool Reason the LB is read-only or false if not */
87 private $readOnlyReason = false;
88 /** @var integer Total connections opened */
89 private $connsOpened = 0;
90 /** @var string|bool String if a requested DBO_TRX transaction round is active */
91 private $trxRoundId = false;
92 /** @var array[] Map of (name => callable) */
93 private $trxRecurringCallbacks = [];
94 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
96 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
97 private $localDomainIdAlias;
98 /** @var string Current server name */
100 /** @var bool Whether this PHP instance is for a CLI script */
102 /** @var string Agent name for query profiling */
105 /** @var callable Exception logger */
106 private $errorLogger;
109 private $disabled = false;
111 /** @var integer Warn when this many connection are held */
112 const CONN_HELD_WARN_THRESHOLD
= 10;
114 /** @var integer Default 'max lag' when unspecified */
115 const MAX_LAG_DEFAULT
= 10;
116 /** @var integer Seconds to cache master server read-only status */
117 const TTL_CACHE_READONLY
= 5;
119 public function __construct( array $params ) {
120 if ( !isset( $params['servers'] ) ) {
121 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
123 $this->mServers
= $params['servers'];
125 $this->localDomain
= isset( $params['localDomain'] )
126 ? DatabaseDomain
::newFromId( $params['localDomain'] )
127 : DatabaseDomain
::newUnspecified();
128 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
129 // always true, gracefully handle the case when they fail to account for escaping.
130 if ( $this->localDomain
->getTablePrefix() != '' ) {
131 $this->localDomainIdAlias
=
132 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
134 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
137 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
139 $this->mReadIndex
= -1;
146 $this->mWaitForPos
= false;
147 $this->mErrorConnection
= false;
148 $this->mAllowLagged
= false;
150 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
151 $this->readOnlyReason
= $params['readOnlyReason'];
154 if ( isset( $params['loadMonitor'] ) ) {
155 $this->loadMonitorConfig
= $params['loadMonitor'];
157 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
160 foreach ( $params['servers'] as $i => $server ) {
161 $this->mLoads
[$i] = $server['load'];
162 if ( isset( $server['groupLoads'] ) ) {
163 foreach ( $server['groupLoads'] as $group => $ratio ) {
164 if ( !isset( $this->mGroupLoads
[$group] ) ) {
165 $this->mGroupLoads
[$group] = [];
167 $this->mGroupLoads
[$group][$i] = $ratio;
172 if ( isset( $params['srvCache'] ) ) {
173 $this->srvCache
= $params['srvCache'];
175 $this->srvCache
= new EmptyBagOStuff();
177 if ( isset( $params['memCache'] ) ) {
178 $this->memCache
= $params['memCache'];
180 $this->memCache
= new EmptyBagOStuff();
182 if ( isset( $params['wanCache'] ) ) {
183 $this->wanCache
= $params['wanCache'];
185 $this->wanCache
= WANObjectCache
::newEmpty();
187 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
188 if ( isset( $params['trxProfiler'] ) ) {
189 $this->trxProfiler
= $params['trxProfiler'];
191 $this->trxProfiler
= new TransactionProfiler();
194 $this->errorLogger
= isset( $params['errorLogger'] )
195 ?
$params['errorLogger']
196 : function ( Exception
$e ) {
197 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
200 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
201 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
204 $this->host
= isset( $params['hostname'] )
205 ?
$params['hostname']
206 : ( gethostname() ?
: 'unknown' );
207 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
208 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
212 * Get a LoadMonitor instance
214 * @return ILoadMonitor
216 private function getLoadMonitor() {
217 if ( !isset( $this->loadMonitor
) ) {
219 'LoadMonitor' => Wikimedia\Rdbms\LoadMonitor
::class,
220 'LoadMonitorNull' => Wikimedia\Rdbms\LoadMonitorNull
::class,
221 'LoadMonitorMySQL' => Wikimedia\Rdbms\LoadMonitorMySQL
::class,
224 $class = $this->loadMonitorConfig
['class'];
225 if ( isset( $compat[$class] ) ) {
226 $class = $compat[$class];
229 $this->loadMonitor
= new $class(
230 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
231 $this->loadMonitor
->setLogger( $this->replLogger
);
234 return $this->loadMonitor
;
238 * @param array $loads
239 * @param bool|string $domain Domain to get non-lagged for
240 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
241 * @return bool|int|string
243 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
244 $lags = $this->getLagTimes( $domain );
246 # Unset excessively lagged servers
247 foreach ( $lags as $i => $lag ) {
249 # How much lag this server nominally is allowed to have
250 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
251 ?
$this->mServers
[$i]['max lag']
252 : self
::MAX_LAG_DEFAULT
; // default
253 # Constrain that futher by $maxLag argument
254 $maxServerLag = min( $maxServerLag, $maxLag );
256 $host = $this->getServerName( $i );
257 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
258 $this->replLogger
->error(
259 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
261 } elseif ( $lag > $maxServerLag ) {
262 $this->replLogger
->warning(
263 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
264 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
271 # Find out if all the replica DBs with non-zero load are lagged
273 foreach ( $loads as $load ) {
277 # No appropriate DB servers except maybe the master and some replica DBs with zero load
278 # Do NOT use the master
279 # Instead, this function will return false, triggering read-only mode,
280 # and a lagged replica DB will be used instead.
284 if ( count( $loads ) == 0 ) {
288 # Return a random representative of the remainder
289 return ArrayUtils
::pickRandom( $loads );
292 public function getReaderIndex( $group = false, $domain = false ) {
293 if ( count( $this->mServers
) == 1 ) {
294 # Skip the load balancing if there's only one server
295 return $this->getWriterIndex();
296 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
297 # Shortcut if generic reader exists already
298 return $this->mReadIndex
;
301 # Find the relevant load array
302 if ( $group !== false ) {
303 if ( isset( $this->mGroupLoads
[$group] ) ) {
304 $nonErrorLoads = $this->mGroupLoads
[$group];
306 # No loads for this group, return false and the caller can use some other group
307 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
312 $nonErrorLoads = $this->mLoads
;
315 if ( !count( $nonErrorLoads ) ) {
316 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
319 # Scale the configured load ratios according to the dynamic load if supported
320 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
322 $laggedReplicaMode = false;
324 # No server found yet
326 # First try quickly looking through the available servers for a server that
328 $currentLoads = $nonErrorLoads;
329 while ( count( $currentLoads ) ) {
330 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
331 $i = ArrayUtils
::pickRandom( $currentLoads );
334 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
335 # ChronologyProtecter causes mWaitForPos to be set via sessions.
336 # This triggers doWait() after connect, so it's especially good to
337 # avoid lagged servers so as to avoid just blocking in that method.
338 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
339 # Aim for <= 1 second of waiting (being too picky can backfire)
340 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
342 if ( $i === false ) {
343 # Any server with less lag than it's 'max lag' param is preferable
344 $i = $this->getRandomNonLagged( $currentLoads, $domain );
346 if ( $i === false && count( $currentLoads ) != 0 ) {
347 # All replica DBs lagged. Switch to read-only mode
348 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
349 $i = ArrayUtils
::pickRandom( $currentLoads );
350 $laggedReplicaMode = true;
354 if ( $i === false ) {
355 # pickRandom() returned false
356 # This is permanent and means the configuration or the load monitor
357 # wants us to return false.
358 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
363 $serverName = $this->getServerName( $i );
364 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
366 $conn = $this->openConnection( $i, $domain );
368 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
369 unset( $nonErrorLoads[$i] );
370 unset( $currentLoads[$i] );
375 // Decrement reference counter, we are finished with this connection.
376 // It will be incremented for the caller later.
377 if ( $domain !== false ) {
378 $this->reuseConnection( $conn );
385 # If all servers were down, quit now
386 if ( !count( $nonErrorLoads ) ) {
387 $this->connLogger
->error( "All servers down" );
390 if ( $i !== false ) {
391 # Replica DB connection successful.
392 # Wait for the session master pos for a short time.
393 if ( $this->mWaitForPos
&& $i > 0 ) {
396 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
397 $this->mReadIndex
= $i;
398 # Record if the generic reader index is in "lagged replica DB" mode
399 if ( $laggedReplicaMode ) {
400 $this->laggedReplicaMode
= true;
403 $serverName = $this->getServerName( $i );
404 $this->connLogger
->debug(
405 __METHOD__
. ": using server $serverName for group '$group'" );
412 * @param DBMasterPos|false $pos
414 public function waitFor( $pos ) {
415 $this->mWaitForPos
= $pos;
416 $i = $this->mReadIndex
;
419 if ( !$this->doWait( $i ) ) {
420 $this->laggedReplicaMode
= true;
425 public function waitForOne( $pos, $timeout = null ) {
426 $this->mWaitForPos
= $pos;
428 $i = $this->mReadIndex
;
430 // Pick a generic replica DB if there isn't one yet
431 $readLoads = $this->mLoads
;
432 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
433 $readLoads = array_filter( $readLoads ); // with non-zero load
434 $i = ArrayUtils
::pickRandom( $readLoads );
438 $ok = $this->doWait( $i, true, $timeout );
440 $ok = true; // no applicable loads
446 public function waitForAll( $pos, $timeout = null ) {
447 $this->mWaitForPos
= $pos;
448 $serverCount = count( $this->mServers
);
451 for ( $i = 1; $i < $serverCount; $i++
) {
452 if ( $this->mLoads
[$i] > 0 ) {
453 $ok = $this->doWait( $i, true, $timeout ) && $ok;
462 * @return IDatabase|bool
464 public function getAnyOpenConnection( $i ) {
465 foreach ( $this->mConns
as $connsByServer ) {
466 if ( !empty( $connsByServer[$i] ) ) {
467 /** @var $serverConns IDatabase[] */
468 $serverConns = $connsByServer[$i];
470 return reset( $serverConns );
478 * Wait for a given replica DB to catch up to the master pos stored in $this
479 * @param int $index Server index
480 * @param bool $open Check the server even if a new connection has to be made
481 * @param int $timeout Max seconds to wait; default is mWaitTimeout
484 protected function doWait( $index, $open = false, $timeout = null ) {
485 $close = false; // close the connection afterwards
487 // Check if we already know that the DB has reached this point
488 $server = $this->getServerName( $index );
489 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
490 /** @var DBMasterPos $knownReachedPos */
491 $knownReachedPos = $this->srvCache
->get( $key );
492 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
493 $this->replLogger
->debug( __METHOD__
.
494 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
498 // Find a connection to wait on, creating one if needed and allowed
499 $conn = $this->getAnyOpenConnection( $index );
502 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
506 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
508 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
512 // Avoid connection spam in waitForAll() when connections
513 // are made just for the sake of doing this lag check.
518 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
519 $timeout = $timeout ?
: $this->mWaitTimeout
;
520 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
522 if ( $result == -1 ||
is_null( $result ) ) {
523 // Timed out waiting for replica DB, use master instead
524 $this->replLogger
->warning(
525 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
526 [ 'host' => $server ]
530 $this->replLogger
->info( __METHOD__
. ": Done" );
532 // Remember that the DB reached this point
533 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
537 $this->closeConnection( $conn );
544 * @see ILoadBalancer::getConnection()
547 * @param array $groups
548 * @param bool $domain
550 * @throws DBConnectionError
552 public function getConnection( $i, $groups = [], $domain = false ) {
553 if ( $i === null ||
$i === false ) {
554 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
555 ' with invalid server index' );
558 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
559 $domain = false; // local connection requested
562 $groups = ( $groups === false ||
$groups === [] )
563 ?
[ false ] // check one "group": the generic pool
566 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
567 $oldConnsOpened = $this->connsOpened
; // connections open now
569 if ( $i == self
::DB_MASTER
) {
570 $i = $this->getWriterIndex();
572 # Try to find an available server in any the query groups (in order)
573 foreach ( $groups as $group ) {
574 $groupIndex = $this->getReaderIndex( $group, $domain );
575 if ( $groupIndex !== false ) {
582 # Operation-based index
583 if ( $i == self
::DB_REPLICA
) {
584 $this->mLastError
= 'Unknown error'; // reset error string
585 # Try the general server pool if $groups are unavailable.
586 $i = ( $groups === [ false ] )
587 ?
false // don't bother with this if that is what was tried above
588 : $this->getReaderIndex( false, $domain );
589 # Couldn't find a working server in getReaderIndex()?
590 if ( $i === false ) {
591 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
592 // Throw an exception
593 $this->reportConnectionError();
594 return null; // not reached
598 # Now we have an explicit index into the servers array
599 $conn = $this->openConnection( $i, $domain );
601 // Throw an exception
602 $this->reportConnectionError();
603 return null; // not reached
606 # Profile any new connections that happen
607 if ( $this->connsOpened
> $oldConnsOpened ) {
608 $host = $conn->getServer();
609 $dbname = $conn->getDBname();
610 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
614 # Make master-requested DB handles inherit any read-only mode setting
615 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
621 public function reuseConnection( $conn ) {
622 $serverIndex = $conn->getLBInfo( 'serverIndex' );
623 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
624 if ( $serverIndex === null ||
$refCount === null ) {
626 * This can happen in code like:
627 * foreach ( $dbs as $db ) {
628 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
630 * $lb->reuseConnection( $conn );
632 * When a connection to the local DB is opened in this way, reuseConnection()
636 } elseif ( $conn instanceof DBConnRef
) {
637 // DBConnRef already handles calling reuseConnection() and only passes the live
638 // Database instance to this method. Any caller passing in a DBConnRef is broken.
639 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
640 ( new RuntimeException() )->getTraceAsString() );
645 if ( $this->disabled
) {
646 return; // DBConnRef handle probably survived longer than the LoadBalancer
649 $domain = $conn->getDomainID();
650 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
651 throw new InvalidArgumentException( __METHOD__
.
652 ": connection $serverIndex/$domain not found; it may have already been freed." );
653 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
654 throw new InvalidArgumentException( __METHOD__
.
655 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
657 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
658 if ( $refCount <= 0 ) {
659 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
660 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
661 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
662 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
664 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
666 $this->connLogger
->debug( __METHOD__
.
667 ": reference count for $serverIndex/$domain reduced to $refCount" );
671 public function getConnectionRef( $db, $groups = [], $domain = false ) {
672 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
674 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
677 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
678 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
680 return new DBConnRef( $this, [ $db, $groups, $domain ] );
683 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
684 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
686 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
690 * @see ILoadBalancer::openConnection()
693 * @param bool $domain
694 * @return bool|Database
695 * @throws DBAccessError
697 public function openConnection( $i, $domain = false ) {
698 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
699 $domain = false; // local connection requested
702 if ( $domain !== false ) {
703 $conn = $this->openForeignConnection( $i, $domain );
704 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
705 $conn = $this->mConns
['local'][$i][0];
707 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
708 throw new InvalidArgumentException( "No server with index '$i'." );
710 // Open a new connection
711 $server = $this->mServers
[$i];
712 $server['serverIndex'] = $i;
713 $conn = $this->reallyOpenConnection( $server, false );
714 $serverName = $this->getServerName( $i );
715 if ( $conn->isOpen() ) {
716 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
717 $this->mConns
['local'][$i][0] = $conn;
719 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
720 $this->mErrorConnection
= $conn;
725 if ( $conn && !$conn->isOpen() ) {
726 // Connection was made but later unrecoverably lost for some reason.
727 // Do not return a handle that will just throw exceptions on use,
728 // but let the calling code (e.g. getReaderIndex) try another server.
729 // See DatabaseMyslBase::ping() for how this can happen.
730 $this->mErrorConnection
= $conn;
738 * Open a connection to a foreign DB, or return one if it is already open.
740 * Increments a reference count on the returned connection which locks the
741 * connection to the requested domain. This reference count can be
742 * decremented by calling reuseConnection().
744 * If a connection is open to the appropriate server already, but with the wrong
745 * database, it will be switched to the right database and returned, as long as
746 * it has been freed first with reuseConnection().
748 * On error, returns false, and the connection which caused the
749 * error will be available via $this->mErrorConnection.
751 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
753 * @param int $i Server index
754 * @param string $domain Domain ID to open
757 private function openForeignConnection( $i, $domain ) {
758 $domainInstance = DatabaseDomain
::newFromId( $domain );
759 $dbName = $domainInstance->getDatabase();
760 $prefix = $domainInstance->getTablePrefix();
762 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
763 // Reuse an already-used connection
764 $conn = $this->mConns
['foreignUsed'][$i][$domain];
765 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
766 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
767 // Reuse a free connection for the same domain
768 $conn = $this->mConns
['foreignFree'][$i][$domain];
769 unset( $this->mConns
['foreignFree'][$i][$domain] );
770 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
771 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
772 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
773 // Reuse a connection from another domain
774 $conn = reset( $this->mConns
['foreignFree'][$i] );
775 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
776 // The empty string as a DB name means "don't care".
777 // DatabaseMysqlBase::open() already handle this on connection.
778 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
779 $this->mLastError
= "Error selecting database '$dbName' on server " .
780 $conn->getServer() . " from client host {$this->host}";
781 $this->mErrorConnection
= $conn;
784 $conn->tablePrefix( $prefix );
785 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
786 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
787 $this->connLogger
->debug( __METHOD__
.
788 ": reusing free connection from $oldDomain for $domain" );
791 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
792 throw new InvalidArgumentException( "No server with index '$i'." );
794 // Open a new connection
795 $server = $this->mServers
[$i];
796 $server['serverIndex'] = $i;
797 $server['foreignPoolRefCount'] = 0;
798 $server['foreign'] = true;
799 $conn = $this->reallyOpenConnection( $server, $dbName );
800 if ( !$conn->isOpen() ) {
801 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
802 $this->mErrorConnection
= $conn;
805 $conn->tablePrefix( $prefix );
806 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
807 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
811 // Increment reference count
813 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
814 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
821 * Test if the specified index represents an open connection
823 * @param int $index Server index
827 private function isOpen( $index ) {
828 if ( !is_integer( $index ) ) {
832 return (bool)$this->getAnyOpenConnection( $index );
836 * Really opens a connection. Uncached.
837 * Returns a Database object whether or not the connection was successful.
840 * @param array $server
841 * @param string|bool $dbNameOverride Use "" to not select any database
843 * @throws DBAccessError
844 * @throws InvalidArgumentException
846 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
847 if ( $this->disabled
) {
848 throw new DBAccessError();
851 if ( $dbNameOverride !== false ) {
852 $server['dbname'] = $dbNameOverride;
855 // Let the handle know what the cluster master is (e.g. "db1052")
856 $masterName = $this->getServerName( $this->getWriterIndex() );
857 $server['clusterMasterHost'] = $masterName;
859 // Log when many connection are made on requests
860 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
861 $this->perfLogger
->warning( __METHOD__
. ": " .
862 "{$this->connsOpened}+ connections made (master=$masterName)" );
865 $server['srvCache'] = $this->srvCache
;
866 // Set loggers and profilers
867 $server['connLogger'] = $this->connLogger
;
868 $server['queryLogger'] = $this->queryLogger
;
869 $server['errorLogger'] = $this->errorLogger
;
870 $server['profiler'] = $this->profiler
;
871 $server['trxProfiler'] = $this->trxProfiler
;
872 // Use the same agent and PHP mode for all DB handles
873 $server['cliMode'] = $this->cliMode
;
874 $server['agent'] = $this->agent
;
875 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
876 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
877 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
879 // Create a live connection object
881 $db = Database
::factory( $server['type'], $server );
882 } catch ( DBConnectionError
$e ) {
883 // FIXME: This is probably the ugliest thing I have ever done to
884 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
888 $db->setLBInfo( $server );
889 $db->setLazyMasterHandle(
890 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
892 $db->setTableAliases( $this->tableAliases
);
894 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
895 if ( $this->trxRoundId
!== false ) {
896 $this->applyTransactionRoundFlags( $db );
898 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
899 $db->setTransactionListener( $name, $callback );
907 * @throws DBConnectionError
909 private function reportConnectionError() {
910 $conn = $this->mErrorConnection
; // the connection which caused the error
912 'method' => __METHOD__
,
913 'last_error' => $this->mLastError
,
916 if ( !is_object( $conn ) ) {
917 // No last connection, probably due to all servers being too busy
918 $this->connLogger
->error(
919 "LB failure with no last connection. Connection error: {last_error}",
923 // If all servers were busy, mLastError will contain something sensible
924 throw new DBConnectionError( null, $this->mLastError
);
926 $context['db_server'] = $conn->getServer();
927 $this->connLogger
->warning(
928 "Connection error: {last_error} ({db_server})",
932 // throws DBConnectionError
933 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
937 public function getWriterIndex() {
941 public function haveIndex( $i ) {
942 return array_key_exists( $i, $this->mServers
);
945 public function isNonZeroLoad( $i ) {
946 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
949 public function getServerCount() {
950 return count( $this->mServers
);
953 public function getServerName( $i ) {
954 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
955 $name = $this->mServers
[$i]['hostName'];
956 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
957 $name = $this->mServers
[$i]['host'];
962 return ( $name != '' ) ?
$name : 'localhost';
965 public function getServerInfo( $i ) {
966 if ( isset( $this->mServers
[$i] ) ) {
967 return $this->mServers
[$i];
973 public function setServerInfo( $i, array $serverInfo ) {
974 $this->mServers
[$i] = $serverInfo;
977 public function getMasterPos() {
978 # If this entire request was served from a replica DB without opening a connection to the
979 # master (however unlikely that may be), then we can fetch the position from the replica DB.
980 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
981 if ( !$masterConn ) {
982 $serverCount = count( $this->mServers
);
983 for ( $i = 1; $i < $serverCount; $i++
) {
984 $conn = $this->getAnyOpenConnection( $i );
986 return $conn->getReplicaPos();
990 return $masterConn->getMasterPos();
996 public function disable() {
998 $this->disabled
= true;
1001 public function closeAll() {
1002 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1003 $host = $conn->getServer();
1004 $this->connLogger
->debug( "Closing connection to database '$host'." );
1010 'foreignFree' => [],
1011 'foreignUsed' => [],
1013 $this->connsOpened
= 0;
1016 public function closeConnection( IDatabase
$conn ) {
1017 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1018 foreach ( $this->mConns
as $type => $connsByServer ) {
1019 if ( !isset( $connsByServer[$serverIndex] ) ) {
1023 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1024 if ( $conn === $trackedConn ) {
1025 $host = $this->getServerName( $i );
1026 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1027 unset( $this->mConns
[$type][$serverIndex][$i] );
1028 --$this->connsOpened
;
1037 public function commitAll( $fname = __METHOD__
) {
1040 $restore = ( $this->trxRoundId
!== false );
1041 $this->trxRoundId
= false;
1042 $this->forEachOpenConnection(
1043 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1045 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1046 } catch ( DBError
$e ) {
1047 call_user_func( $this->errorLogger
, $e );
1048 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1050 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1051 $this->undoTransactionRoundFlags( $conn );
1057 throw new DBExpectedError(
1059 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1064 public function finalizeMasterChanges() {
1065 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1066 // Any error should cause all DB transactions to be rolled back together
1067 $conn->setTrxEndCallbackSuppression( false );
1068 $conn->runOnTransactionPreCommitCallbacks();
1069 // Defer post-commit callbacks until COMMIT finishes for all DBs
1070 $conn->setTrxEndCallbackSuppression( true );
1074 public function approveMasterChanges( array $options ) {
1075 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1076 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1077 // If atomic sections or explicit transactions are still open, some caller must have
1078 // caught an exception but failed to properly rollback any changes. Detect that and
1079 // throw and error (causing rollback).
1080 if ( $conn->explicitTrxActive() ) {
1081 throw new DBTransactionError(
1083 "Explicit transaction still active. A caller may have caught an error."
1086 // Assert that the time to replicate the transaction will be sane.
1087 // If this fails, then all DB transactions will be rollback back together.
1088 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1089 if ( $limit > 0 && $time > $limit ) {
1090 throw new DBTransactionSizeError(
1092 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1096 // If a connection sits idle while slow queries execute on another, that connection
1097 // may end up dropped before the commit round is reached. Ping servers to detect this.
1098 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1099 throw new DBTransactionError(
1101 "A connection to the {$conn->getDBname()} database was lost before commit."
1107 public function beginMasterChanges( $fname = __METHOD__
) {
1108 if ( $this->trxRoundId
!== false ) {
1109 throw new DBTransactionError(
1111 "$fname: Transaction round '{$this->trxRoundId}' already started."
1114 $this->trxRoundId
= $fname;
1117 $this->forEachOpenMasterConnection(
1118 function ( Database
$conn ) use ( $fname, &$failures ) {
1119 $conn->setTrxEndCallbackSuppression( true );
1121 $conn->flushSnapshot( $fname );
1122 } catch ( DBError
$e ) {
1123 call_user_func( $this->errorLogger
, $e );
1124 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1126 $conn->setTrxEndCallbackSuppression( false );
1127 $this->applyTransactionRoundFlags( $conn );
1132 throw new DBExpectedError(
1134 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1139 public function commitMasterChanges( $fname = __METHOD__
) {
1142 /** @noinspection PhpUnusedLocalVariableInspection */
1143 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1145 $restore = ( $this->trxRoundId
!== false );
1146 $this->trxRoundId
= false;
1147 $this->forEachOpenMasterConnection(
1148 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1150 if ( $conn->writesOrCallbacksPending() ) {
1151 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1152 } elseif ( $restore ) {
1153 $conn->flushSnapshot( $fname );
1155 } catch ( DBError
$e ) {
1156 call_user_func( $this->errorLogger
, $e );
1157 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1160 $this->undoTransactionRoundFlags( $conn );
1166 throw new DBExpectedError(
1168 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1173 public function runMasterPostTrxCallbacks( $type ) {
1174 $e = null; // first exception
1175 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1176 $conn->setTrxEndCallbackSuppression( false );
1177 if ( $conn->writesOrCallbacksPending() ) {
1178 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1179 // (which finished its callbacks already). Warn and recover in this case. Let the
1180 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1181 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1183 } elseif ( $conn->trxLevel() ) {
1184 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1185 // thus leaving an implicit read-only transaction open at this point. It
1186 // also happens if onTransactionIdle() callbacks leave implicit transactions
1187 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1188 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1192 $conn->runOnTransactionIdleCallbacks( $type );
1193 } catch ( Exception
$ex ) {
1197 $conn->runTransactionListenerCallbacks( $type );
1198 } catch ( Exception
$ex ) {
1206 public function rollbackMasterChanges( $fname = __METHOD__
) {
1207 $restore = ( $this->trxRoundId
!== false );
1208 $this->trxRoundId
= false;
1209 $this->forEachOpenMasterConnection(
1210 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1211 if ( $conn->writesOrCallbacksPending() ) {
1212 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1215 $this->undoTransactionRoundFlags( $conn );
1221 public function suppressTransactionEndCallbacks() {
1222 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1223 $conn->setTrxEndCallbackSuppression( true );
1228 * @param IDatabase $conn
1230 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1231 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1232 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1233 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1234 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1235 // If config has explicitly requested DBO_TRX be either on or off by not
1236 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1237 // for things like blob stores (ExternalStore) which want auto-commit mode.
1242 * @param IDatabase $conn
1244 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1245 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1246 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1250 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1251 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1252 $conn->flushSnapshot( __METHOD__
);
1256 public function hasMasterConnection() {
1257 return $this->isOpen( $this->getWriterIndex() );
1260 public function hasMasterChanges() {
1262 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1263 $pending |
= $conn->writesOrCallbacksPending();
1266 return (bool)$pending;
1269 public function lastMasterChangeTimestamp() {
1271 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1272 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1278 public function hasOrMadeRecentMasterChanges( $age = null ) {
1279 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1281 return ( $this->hasMasterChanges()
1282 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1285 public function pendingMasterChangeCallers() {
1287 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1288 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1294 public function getLaggedReplicaMode( $domain = false ) {
1295 // No-op if there is only one DB (also avoids recursion)
1296 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1298 // See if laggedReplicaMode gets set
1299 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1300 $this->reuseConnection( $conn );
1301 } catch ( DBConnectionError
$e ) {
1302 // Avoid expensive re-connect attempts and failures
1303 $this->allReplicasDownMode
= true;
1304 $this->laggedReplicaMode
= true;
1308 return $this->laggedReplicaMode
;
1312 * @param bool $domain
1314 * @deprecated 1.28; use getLaggedReplicaMode()
1316 public function getLaggedSlaveMode( $domain = false ) {
1317 return $this->getLaggedReplicaMode( $domain );
1320 public function laggedReplicaUsed() {
1321 return $this->laggedReplicaMode
;
1327 * @deprecated Since 1.28; use laggedReplicaUsed()
1329 public function laggedSlaveUsed() {
1330 return $this->laggedReplicaUsed();
1333 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1334 if ( $this->readOnlyReason
!== false ) {
1335 return $this->readOnlyReason
;
1336 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1337 if ( $this->allReplicasDownMode
) {
1338 return 'The database has been automatically locked ' .
1339 'until the replica database servers become available';
1341 return 'The database has been automatically locked ' .
1342 'while the replica database servers catch up to the master.';
1344 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1345 return 'The database master is running in read-only mode.';
1352 * @param string $domain Domain ID, or false for the current domain
1353 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1356 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1357 $cache = $this->wanCache
;
1358 $masterServer = $this->getServerName( $this->getWriterIndex() );
1360 return (bool)$cache->getWithSetCallback(
1361 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1362 self
::TTL_CACHE_READONLY
,
1363 function () use ( $domain, $conn ) {
1364 $old = $this->trxProfiler
->setSilenced( true );
1366 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1367 $readOnly = (int)$dbw->serverIsReadOnly();
1369 $this->reuseConnection( $dbw );
1371 } catch ( DBError
$e ) {
1374 $this->trxProfiler
->setSilenced( $old );
1377 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1381 public function allowLagged( $mode = null ) {
1382 if ( $mode === null ) {
1383 return $this->mAllowLagged
;
1385 $this->mAllowLagged
= $mode;
1387 return $this->mAllowLagged
;
1390 public function pingAll() {
1392 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1393 if ( !$conn->ping() ) {
1401 public function forEachOpenConnection( $callback, array $params = [] ) {
1402 foreach ( $this->mConns
as $connsByServer ) {
1403 foreach ( $connsByServer as $serverConns ) {
1404 foreach ( $serverConns as $conn ) {
1405 $mergedParams = array_merge( [ $conn ], $params );
1406 call_user_func_array( $callback, $mergedParams );
1412 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1413 $masterIndex = $this->getWriterIndex();
1414 foreach ( $this->mConns
as $connsByServer ) {
1415 if ( isset( $connsByServer[$masterIndex] ) ) {
1416 /** @var IDatabase $conn */
1417 foreach ( $connsByServer[$masterIndex] as $conn ) {
1418 $mergedParams = array_merge( [ $conn ], $params );
1419 call_user_func_array( $callback, $mergedParams );
1425 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1426 foreach ( $this->mConns
as $connsByServer ) {
1427 foreach ( $connsByServer as $i => $serverConns ) {
1428 if ( $i === $this->getWriterIndex() ) {
1429 continue; // skip master
1431 foreach ( $serverConns as $conn ) {
1432 $mergedParams = array_merge( [ $conn ], $params );
1433 call_user_func_array( $callback, $mergedParams );
1439 public function getMaxLag( $domain = false ) {
1444 if ( $this->getServerCount() <= 1 ) {
1445 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1448 $lagTimes = $this->getLagTimes( $domain );
1449 foreach ( $lagTimes as $i => $lag ) {
1450 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1452 $host = $this->mServers
[$i]['host'];
1457 return [ $host, $maxLag, $maxIndex ];
1460 public function getLagTimes( $domain = false ) {
1461 if ( $this->getServerCount() <= 1 ) {
1462 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1465 $knownLagTimes = []; // map of (server index => 0 seconds)
1466 $indexesWithLag = [];
1467 foreach ( $this->mServers
as $i => $server ) {
1468 if ( empty( $server['is static'] ) ) {
1469 $indexesWithLag[] = $i; // DB server might have replication lag
1471 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1475 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1478 public function safeGetLag( IDatabase
$conn ) {
1479 if ( $this->getServerCount() <= 1 ) {
1482 return $conn->getLag();
1487 * @param IDatabase $conn
1488 * @param DBMasterPos|bool $pos
1489 * @param int $timeout
1492 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1493 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1494 return true; // server is not a replica DB
1498 // Get the current master position, opening a connection if needed
1499 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1500 if ( $masterConn ) {
1501 $pos = $masterConn->getMasterPos();
1503 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1504 $pos = $masterConn->getMasterPos();
1505 $this->closeConnection( $masterConn );
1509 if ( $pos instanceof DBMasterPos
) {
1510 $result = $conn->masterPosWait( $pos, $timeout );
1511 if ( $result == -1 ||
is_null( $result ) ) {
1512 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1513 $this->replLogger
->warning( "$msg" );
1516 $this->replLogger
->info( __METHOD__
. ": Done" );
1520 $ok = false; // something is misconfigured
1521 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1527 public function setTransactionListener( $name, callable
$callback = null ) {
1529 $this->trxRecurringCallbacks
[$name] = $callback;
1531 unset( $this->trxRecurringCallbacks
[$name] );
1533 $this->forEachOpenMasterConnection(
1534 function ( IDatabase
$conn ) use ( $name, $callback ) {
1535 $conn->setTransactionListener( $name, $callback );
1540 public function setTableAliases( array $aliases ) {
1541 $this->tableAliases
= $aliases;
1544 public function setDomainPrefix( $prefix ) {
1545 if ( $this->mConns
['foreignUsed'] ) {
1546 // Do not switch connections to explicit foreign domains unless marked as free
1548 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1549 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1551 $domains = implode( ', ', $domains );
1552 throw new DBUnexpectedError( null,
1553 "Foreign domain connections are still in use ($domains)." );
1556 $this->localDomain
= new DatabaseDomain(
1557 $this->localDomain
->getDatabase(),
1562 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1563 $db->tablePrefix( $prefix );
1568 * Make PHP ignore user aborts/disconnects until the returned
1569 * value leaves scope. This returns null and does nothing in CLI mode.
1571 * @return ScopedCallback|null
1573 final protected function getScopedPHPBehaviorForCommit() {
1574 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1575 $old = ignore_user_abort( true ); // avoid half-finished operations
1576 return new ScopedCallback( function () use ( $old ) {
1577 ignore_user_abort( $old );
1584 function __destruct() {
1585 // Avoid connection leaks for sanity