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
;
26 * Database connection, tracking, load balancing, and transaction manager for a cluster
30 class LoadBalancer
implements ILoadBalancer
{
31 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => IDatabase array) */
35 /** @var float[] Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
39 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
42 private $mWaitTimeout;
43 /** @var array The LoadMonitor configuration */
44 private $loadMonitorConfig;
45 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
46 private $tableAliases = [];
48 /** @var ILoadMonitor */
54 /** @var WANObjectCache */
56 /** @var object|string Class name or object With profileIn/profileOut methods */
58 /** @var TransactionProfiler */
59 protected $trxProfiler;
60 /** @var LoggerInterface */
61 protected $replLogger;
62 /** @var LoggerInterface */
63 protected $connLogger;
64 /** @var LoggerInterface */
65 protected $queryLogger;
66 /** @var LoggerInterface */
67 protected $perfLogger;
69 /** @var bool|IDatabase Database connection that caused a problem */
70 private $mErrorConnection;
71 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
73 /** @var bool|DBMasterPos False if not set */
75 /** @var bool Whether the generic reader fell back to a lagged replica DB */
76 private $laggedReplicaMode = false;
77 /** @var bool Whether the generic reader fell back to a lagged replica DB */
78 private $allReplicasDownMode = false;
79 /** @var string The last DB selection or connection error */
80 private $mLastError = 'Unknown error';
81 /** @var string|bool Reason the LB is read-only or false if not */
82 private $readOnlyReason = false;
83 /** @var integer Total connections opened */
84 private $connsOpened = 0;
85 /** @var string|bool String if a requested DBO_TRX transaction round is active */
86 private $trxRoundId = false;
87 /** @var array[] Map of (name => callable) */
88 private $trxRecurringCallbacks = [];
89 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
91 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
92 private $localDomainIdAlias;
93 /** @var string Current server name */
95 /** @var bool Whether this PHP instance is for a CLI script */
97 /** @var string Agent name for query profiling */
100 /** @var callable Exception logger */
101 private $errorLogger;
104 private $disabled = false;
106 /** @var integer Warn when this many connection are held */
107 const CONN_HELD_WARN_THRESHOLD
= 10;
109 /** @var integer Default 'max lag' when unspecified */
110 const MAX_LAG_DEFAULT
= 10;
111 /** @var integer Seconds to cache master server read-only status */
112 const TTL_CACHE_READONLY
= 5;
114 public function __construct( array $params ) {
115 if ( !isset( $params['servers'] ) ) {
116 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
118 $this->mServers
= $params['servers'];
120 $this->localDomain
= isset( $params['localDomain'] )
121 ? DatabaseDomain
::newFromId( $params['localDomain'] )
122 : DatabaseDomain
::newUnspecified();
123 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
124 // always true, gracefully handle the case when they fail to account for escaping.
125 if ( $this->localDomain
->getTablePrefix() != '' ) {
126 $this->localDomainIdAlias
=
127 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
129 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
132 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
134 $this->mReadIndex
= -1;
141 $this->mWaitForPos
= false;
142 $this->mErrorConnection
= false;
143 $this->mAllowLagged
= false;
145 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
146 $this->readOnlyReason
= $params['readOnlyReason'];
149 if ( isset( $params['loadMonitor'] ) ) {
150 $this->loadMonitorConfig
= $params['loadMonitor'];
152 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
155 foreach ( $params['servers'] as $i => $server ) {
156 $this->mLoads
[$i] = $server['load'];
157 if ( isset( $server['groupLoads'] ) ) {
158 foreach ( $server['groupLoads'] as $group => $ratio ) {
159 if ( !isset( $this->mGroupLoads
[$group] ) ) {
160 $this->mGroupLoads
[$group] = [];
162 $this->mGroupLoads
[$group][$i] = $ratio;
167 if ( isset( $params['srvCache'] ) ) {
168 $this->srvCache
= $params['srvCache'];
170 $this->srvCache
= new EmptyBagOStuff();
172 if ( isset( $params['memCache'] ) ) {
173 $this->memCache
= $params['memCache'];
175 $this->memCache
= new EmptyBagOStuff();
177 if ( isset( $params['wanCache'] ) ) {
178 $this->wanCache
= $params['wanCache'];
180 $this->wanCache
= WANObjectCache
::newEmpty();
182 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
183 if ( isset( $params['trxProfiler'] ) ) {
184 $this->trxProfiler
= $params['trxProfiler'];
186 $this->trxProfiler
= new TransactionProfiler();
189 $this->errorLogger
= isset( $params['errorLogger'] )
190 ?
$params['errorLogger']
191 : function ( Exception
$e ) {
192 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
195 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
196 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
199 $this->host
= isset( $params['hostname'] )
200 ?
$params['hostname']
201 : ( gethostname() ?
: 'unknown' );
202 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
203 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
207 * Get a LoadMonitor instance
209 * @return ILoadMonitor
211 private function getLoadMonitor() {
212 if ( !isset( $this->loadMonitor
) ) {
213 $class = $this->loadMonitorConfig
['class'];
214 $this->loadMonitor
= new $class(
215 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
216 $this->loadMonitor
->setLogger( $this->replLogger
);
219 return $this->loadMonitor
;
223 * @param array $loads
224 * @param bool|string $domain Domain to get non-lagged for
225 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
226 * @return bool|int|string
228 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
229 $lags = $this->getLagTimes( $domain );
231 # Unset excessively lagged servers
232 foreach ( $lags as $i => $lag ) {
234 # How much lag this server nominally is allowed to have
235 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
236 ?
$this->mServers
[$i]['max lag']
237 : self
::MAX_LAG_DEFAULT
; // default
238 # Constrain that futher by $maxLag argument
239 $maxServerLag = min( $maxServerLag, $maxLag );
241 $host = $this->getServerName( $i );
242 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
243 $this->replLogger
->error( "Server $host (#$i) is not replicating?" );
245 } elseif ( $lag > $maxServerLag ) {
246 $this->replLogger
->warning( "Server $host (#$i) has >= $lag seconds of lag" );
252 # Find out if all the replica DBs with non-zero load are lagged
254 foreach ( $loads as $load ) {
258 # No appropriate DB servers except maybe the master and some replica DBs with zero load
259 # Do NOT use the master
260 # Instead, this function will return false, triggering read-only mode,
261 # and a lagged replica DB will be used instead.
265 if ( count( $loads ) == 0 ) {
269 # Return a random representative of the remainder
270 return ArrayUtils
::pickRandom( $loads );
273 public function getReaderIndex( $group = false, $domain = false ) {
274 if ( count( $this->mServers
) == 1 ) {
275 # Skip the load balancing if there's only one server
276 return $this->getWriterIndex();
277 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
278 # Shortcut if generic reader exists already
279 return $this->mReadIndex
;
282 # Find the relevant load array
283 if ( $group !== false ) {
284 if ( isset( $this->mGroupLoads
[$group] ) ) {
285 $nonErrorLoads = $this->mGroupLoads
[$group];
287 # No loads for this group, return false and the caller can use some other group
288 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
293 $nonErrorLoads = $this->mLoads
;
296 if ( !count( $nonErrorLoads ) ) {
297 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
300 # Scale the configured load ratios according to the dynamic load if supported
301 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
303 $laggedReplicaMode = false;
305 # No server found yet
307 # First try quickly looking through the available servers for a server that
309 $currentLoads = $nonErrorLoads;
310 while ( count( $currentLoads ) ) {
311 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
312 $i = ArrayUtils
::pickRandom( $currentLoads );
315 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
316 # ChronologyProtecter causes mWaitForPos to be set via sessions.
317 # This triggers doWait() after connect, so it's especially good to
318 # avoid lagged servers so as to avoid just blocking in that method.
319 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
320 # Aim for <= 1 second of waiting (being too picky can backfire)
321 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
323 if ( $i === false ) {
324 # Any server with less lag than it's 'max lag' param is preferable
325 $i = $this->getRandomNonLagged( $currentLoads, $domain );
327 if ( $i === false && count( $currentLoads ) != 0 ) {
328 # All replica DBs lagged. Switch to read-only mode
329 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
330 $i = ArrayUtils
::pickRandom( $currentLoads );
331 $laggedReplicaMode = true;
335 if ( $i === false ) {
336 # pickRandom() returned false
337 # This is permanent and means the configuration or the load monitor
338 # wants us to return false.
339 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
344 $serverName = $this->getServerName( $i );
345 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
347 $conn = $this->openConnection( $i, $domain );
349 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
350 unset( $nonErrorLoads[$i] );
351 unset( $currentLoads[$i] );
356 // Decrement reference counter, we are finished with this connection.
357 // It will be incremented for the caller later.
358 if ( $domain !== false ) {
359 $this->reuseConnection( $conn );
366 # If all servers were down, quit now
367 if ( !count( $nonErrorLoads ) ) {
368 $this->connLogger
->error( "All servers down" );
371 if ( $i !== false ) {
372 # Replica DB connection successful.
373 # Wait for the session master pos for a short time.
374 if ( $this->mWaitForPos
&& $i > 0 ) {
377 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
378 $this->mReadIndex
= $i;
379 # Record if the generic reader index is in "lagged replica DB" mode
380 if ( $laggedReplicaMode ) {
381 $this->laggedReplicaMode
= true;
384 $serverName = $this->getServerName( $i );
385 $this->connLogger
->debug(
386 __METHOD__
. ": using server $serverName for group '$group'" );
392 public function waitFor( $pos ) {
393 $this->mWaitForPos
= $pos;
394 $i = $this->mReadIndex
;
397 if ( !$this->doWait( $i ) ) {
398 $this->laggedReplicaMode
= true;
403 public function waitForOne( $pos, $timeout = null ) {
404 $this->mWaitForPos
= $pos;
406 $i = $this->mReadIndex
;
408 // Pick a generic replica DB if there isn't one yet
409 $readLoads = $this->mLoads
;
410 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
411 $readLoads = array_filter( $readLoads ); // with non-zero load
412 $i = ArrayUtils
::pickRandom( $readLoads );
416 $ok = $this->doWait( $i, true, $timeout );
418 $ok = true; // no applicable loads
424 public function waitForAll( $pos, $timeout = null ) {
425 $this->mWaitForPos
= $pos;
426 $serverCount = count( $this->mServers
);
429 for ( $i = 1; $i < $serverCount; $i++
) {
430 if ( $this->mLoads
[$i] > 0 ) {
431 $ok = $this->doWait( $i, true, $timeout ) && $ok;
438 public function getAnyOpenConnection( $i ) {
439 foreach ( $this->mConns
as $connsByServer ) {
440 if ( !empty( $connsByServer[$i] ) ) {
441 return reset( $connsByServer[$i] );
449 * Wait for a given replica DB to catch up to the master pos stored in $this
450 * @param int $index Server index
451 * @param bool $open Check the server even if a new connection has to be made
452 * @param int $timeout Max seconds to wait; default is mWaitTimeout
455 protected function doWait( $index, $open = false, $timeout = null ) {
456 $close = false; // close the connection afterwards
458 // Check if we already know that the DB has reached this point
459 $server = $this->getServerName( $index );
460 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
461 /** @var DBMasterPos $knownReachedPos */
462 $knownReachedPos = $this->srvCache
->get( $key );
463 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
464 $this->replLogger
->debug( __METHOD__
.
465 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
469 // Find a connection to wait on, creating one if needed and allowed
470 $conn = $this->getAnyOpenConnection( $index );
473 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
477 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
479 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
483 // Avoid connection spam in waitForAll() when connections
484 // are made just for the sake of doing this lag check.
489 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
490 $timeout = $timeout ?
: $this->mWaitTimeout
;
491 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
493 if ( $result == -1 ||
is_null( $result ) ) {
494 // Timed out waiting for replica DB, use master instead
495 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
496 $this->replLogger
->warning( "$msg" );
499 $this->replLogger
->info( __METHOD__
. ": Done" );
501 // Remember that the DB reached this point
502 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
506 $this->closeConnection( $conn );
513 * @see ILoadBalancer::getConnection()
516 * @param array $groups
517 * @param bool $domain
519 * @throws DBConnectionError
521 public function getConnection( $i, $groups = [], $domain = false ) {
522 if ( $i === null ||
$i === false ) {
523 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
524 ' with invalid server index' );
527 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
528 $domain = false; // local connection requested
531 $groups = ( $groups === false ||
$groups === [] )
532 ?
[ false ] // check one "group": the generic pool
535 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
536 $oldConnsOpened = $this->connsOpened
; // connections open now
538 if ( $i == self
::DB_MASTER
) {
539 $i = $this->getWriterIndex();
541 # Try to find an available server in any the query groups (in order)
542 foreach ( $groups as $group ) {
543 $groupIndex = $this->getReaderIndex( $group, $domain );
544 if ( $groupIndex !== false ) {
551 # Operation-based index
552 if ( $i == self
::DB_REPLICA
) {
553 $this->mLastError
= 'Unknown error'; // reset error string
554 # Try the general server pool if $groups are unavailable.
555 $i = ( $groups === [ false ] )
556 ?
false // don't bother with this if that is what was tried above
557 : $this->getReaderIndex( false, $domain );
558 # Couldn't find a working server in getReaderIndex()?
559 if ( $i === false ) {
560 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
561 // Throw an exception
562 $this->reportConnectionError();
563 return null; // not reached
567 # Now we have an explicit index into the servers array
568 $conn = $this->openConnection( $i, $domain );
570 // Throw an exception
571 $this->reportConnectionError();
572 return null; // not reached
575 # Profile any new connections that happen
576 if ( $this->connsOpened
> $oldConnsOpened ) {
577 $host = $conn->getServer();
578 $dbname = $conn->getDBname();
579 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
583 # Make master-requested DB handles inherit any read-only mode setting
584 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
590 public function reuseConnection( $conn ) {
591 $serverIndex = $conn->getLBInfo( 'serverIndex' );
592 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
593 if ( $serverIndex === null ||
$refCount === null ) {
595 * This can happen in code like:
596 * foreach ( $dbs as $db ) {
597 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
599 * $lb->reuseConnection( $conn );
601 * When a connection to the local DB is opened in this way, reuseConnection()
605 } elseif ( $conn instanceof DBConnRef
) {
606 // DBConnRef already handles calling reuseConnection() and only passes the live
607 // Database instance to this method. Any caller passing in a DBConnRef is broken.
608 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
609 ( new RuntimeException() )->getTraceAsString() );
614 if ( $this->disabled
) {
615 return; // DBConnRef handle probably survived longer than the LoadBalancer
618 $domain = $conn->getDomainID();
619 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
620 throw new InvalidArgumentException( __METHOD__
.
621 ": connection $serverIndex/$domain not found; it may have already been freed." );
622 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
623 throw new InvalidArgumentException( __METHOD__
.
624 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
626 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
627 if ( $refCount <= 0 ) {
628 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
629 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
630 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
631 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
633 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
635 $this->connLogger
->debug( __METHOD__
.
636 ": reference count for $serverIndex/$domain reduced to $refCount" );
640 public function getConnectionRef( $db, $groups = [], $domain = false ) {
641 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
643 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
646 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
647 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
649 return new DBConnRef( $this, [ $db, $groups, $domain ] );
653 * @see ILoadBalancer::openConnection()
656 * @param bool $domain
657 * @return bool|Database
658 * @throws DBAccessError
660 public function openConnection( $i, $domain = false ) {
661 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
662 $domain = false; // local connection requested
665 if ( $domain !== false ) {
666 $conn = $this->openForeignConnection( $i, $domain );
667 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
668 $conn = $this->mConns
['local'][$i][0];
670 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
671 throw new InvalidArgumentException( "No server with index '$i'." );
673 // Open a new connection
674 $server = $this->mServers
[$i];
675 $server['serverIndex'] = $i;
676 $conn = $this->reallyOpenConnection( $server, false );
677 $serverName = $this->getServerName( $i );
678 if ( $conn->isOpen() ) {
679 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
680 $this->mConns
['local'][$i][0] = $conn;
682 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
683 $this->mErrorConnection
= $conn;
688 if ( $conn && !$conn->isOpen() ) {
689 // Connection was made but later unrecoverably lost for some reason.
690 // Do not return a handle that will just throw exceptions on use,
691 // but let the calling code (e.g. getReaderIndex) try another server.
692 // See DatabaseMyslBase::ping() for how this can happen.
693 $this->mErrorConnection
= $conn;
701 * Open a connection to a foreign DB, or return one if it is already open.
703 * Increments a reference count on the returned connection which locks the
704 * connection to the requested domain. This reference count can be
705 * decremented by calling reuseConnection().
707 * If a connection is open to the appropriate server already, but with the wrong
708 * database, it will be switched to the right database and returned, as long as
709 * it has been freed first with reuseConnection().
711 * On error, returns false, and the connection which caused the
712 * error will be available via $this->mErrorConnection.
714 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
716 * @param int $i Server index
717 * @param string $domain Domain ID to open
720 private function openForeignConnection( $i, $domain ) {
721 $domainInstance = DatabaseDomain
::newFromId( $domain );
722 $dbName = $domainInstance->getDatabase();
723 $prefix = $domainInstance->getTablePrefix();
725 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
726 // Reuse an already-used connection
727 $conn = $this->mConns
['foreignUsed'][$i][$domain];
728 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
729 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
730 // Reuse a free connection for the same domain
731 $conn = $this->mConns
['foreignFree'][$i][$domain];
732 unset( $this->mConns
['foreignFree'][$i][$domain] );
733 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
734 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
735 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
736 // Reuse a connection from another domain
737 $conn = reset( $this->mConns
['foreignFree'][$i] );
738 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
739 // The empty string as a DB name means "don't care".
740 // DatabaseMysqlBase::open() already handle this on connection.
741 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
742 $this->mLastError
= "Error selecting database '$dbName' on server " .
743 $conn->getServer() . " from client host {$this->host}";
744 $this->mErrorConnection
= $conn;
747 $conn->tablePrefix( $prefix );
748 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
749 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
750 $this->connLogger
->debug( __METHOD__
.
751 ": reusing free connection from $oldDomain for $domain" );
754 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
755 throw new InvalidArgumentException( "No server with index '$i'." );
757 // Open a new connection
758 $server = $this->mServers
[$i];
759 $server['serverIndex'] = $i;
760 $server['foreignPoolRefCount'] = 0;
761 $server['foreign'] = true;
762 $conn = $this->reallyOpenConnection( $server, $dbName );
763 if ( !$conn->isOpen() ) {
764 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
765 $this->mErrorConnection
= $conn;
768 $conn->tablePrefix( $prefix );
769 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
770 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
774 // Increment reference count
776 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
777 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
784 * Test if the specified index represents an open connection
786 * @param int $index Server index
790 private function isOpen( $index ) {
791 if ( !is_integer( $index ) ) {
795 return (bool)$this->getAnyOpenConnection( $index );
799 * Really opens a connection. Uncached.
800 * Returns a Database object whether or not the connection was successful.
803 * @param array $server
804 * @param string|bool $dbNameOverride Use "" to not select any database
806 * @throws DBAccessError
807 * @throws InvalidArgumentException
809 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
810 if ( $this->disabled
) {
811 throw new DBAccessError();
814 if ( $dbNameOverride !== false ) {
815 $server['dbname'] = $dbNameOverride;
818 // Let the handle know what the cluster master is (e.g. "db1052")
819 $masterName = $this->getServerName( $this->getWriterIndex() );
820 $server['clusterMasterHost'] = $masterName;
822 // Log when many connection are made on requests
823 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
824 $this->perfLogger
->warning( __METHOD__
. ": " .
825 "{$this->connsOpened}+ connections made (master=$masterName)" );
828 $server['srvCache'] = $this->srvCache
;
829 // Set loggers and profilers
830 $server['connLogger'] = $this->connLogger
;
831 $server['queryLogger'] = $this->queryLogger
;
832 $server['errorLogger'] = $this->errorLogger
;
833 $server['profiler'] = $this->profiler
;
834 $server['trxProfiler'] = $this->trxProfiler
;
835 // Use the same agent and PHP mode for all DB handles
836 $server['cliMode'] = $this->cliMode
;
837 $server['agent'] = $this->agent
;
838 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
839 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
840 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
842 // Create a live connection object
844 $db = Database
::factory( $server['type'], $server );
845 } catch ( DBConnectionError
$e ) {
846 // FIXME: This is probably the ugliest thing I have ever done to
847 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
851 $db->setLBInfo( $server );
852 $db->setLazyMasterHandle(
853 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
855 $db->setTableAliases( $this->tableAliases
);
857 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
858 if ( $this->trxRoundId
!== false ) {
859 $this->applyTransactionRoundFlags( $db );
861 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
862 $db->setTransactionListener( $name, $callback );
870 * @throws DBConnectionError
872 private function reportConnectionError() {
873 $conn = $this->mErrorConnection
; // the connection which caused the error
875 'method' => __METHOD__
,
876 'last_error' => $this->mLastError
,
879 if ( !is_object( $conn ) ) {
880 // No last connection, probably due to all servers being too busy
881 $this->connLogger
->error(
882 "LB failure with no last connection. Connection error: {last_error}",
886 // If all servers were busy, mLastError will contain something sensible
887 throw new DBConnectionError( null, $this->mLastError
);
889 $context['db_server'] = $conn->getServer();
890 $this->connLogger
->warning(
891 "Connection error: {last_error} ({db_server})",
895 // throws DBConnectionError
896 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
900 public function getWriterIndex() {
904 public function haveIndex( $i ) {
905 return array_key_exists( $i, $this->mServers
);
908 public function isNonZeroLoad( $i ) {
909 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
912 public function getServerCount() {
913 return count( $this->mServers
);
916 public function getServerName( $i ) {
917 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
918 $name = $this->mServers
[$i]['hostName'];
919 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
920 $name = $this->mServers
[$i]['host'];
925 return ( $name != '' ) ?
$name : 'localhost';
928 public function getServerInfo( $i ) {
929 if ( isset( $this->mServers
[$i] ) ) {
930 return $this->mServers
[$i];
936 public function setServerInfo( $i, array $serverInfo ) {
937 $this->mServers
[$i] = $serverInfo;
940 public function getMasterPos() {
941 # If this entire request was served from a replica DB without opening a connection to the
942 # master (however unlikely that may be), then we can fetch the position from the replica DB.
943 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
944 if ( !$masterConn ) {
945 $serverCount = count( $this->mServers
);
946 for ( $i = 1; $i < $serverCount; $i++
) {
947 $conn = $this->getAnyOpenConnection( $i );
949 return $conn->getReplicaPos();
953 return $masterConn->getMasterPos();
959 public function disable() {
961 $this->disabled
= true;
964 public function closeAll() {
965 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
966 $host = $conn->getServer();
967 $this->connLogger
->debug( "Closing connection to database '$host'." );
976 $this->connsOpened
= 0;
979 public function closeConnection( IDatabase
$conn ) {
980 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
981 foreach ( $this->mConns
as $type => $connsByServer ) {
982 if ( !isset( $connsByServer[$serverIndex] ) ) {
986 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
987 if ( $conn === $trackedConn ) {
988 $host = $this->getServerName( $i );
989 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
990 unset( $this->mConns
[$type][$serverIndex][$i] );
991 --$this->connsOpened
;
1000 public function commitAll( $fname = __METHOD__
) {
1003 $restore = ( $this->trxRoundId
!== false );
1004 $this->trxRoundId
= false;
1005 $this->forEachOpenConnection(
1006 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1008 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1009 } catch ( DBError
$e ) {
1010 call_user_func( $this->errorLogger
, $e );
1011 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1013 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1014 $this->undoTransactionRoundFlags( $conn );
1020 throw new DBExpectedError(
1022 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1027 public function finalizeMasterChanges() {
1028 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1029 // Any error should cause all DB transactions to be rolled back together
1030 $conn->setTrxEndCallbackSuppression( false );
1031 $conn->runOnTransactionPreCommitCallbacks();
1032 // Defer post-commit callbacks until COMMIT finishes for all DBs
1033 $conn->setTrxEndCallbackSuppression( true );
1037 public function approveMasterChanges( array $options ) {
1038 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1039 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1040 // If atomic sections or explicit transactions are still open, some caller must have
1041 // caught an exception but failed to properly rollback any changes. Detect that and
1042 // throw and error (causing rollback).
1043 if ( $conn->explicitTrxActive() ) {
1044 throw new DBTransactionError(
1046 "Explicit transaction still active. A caller may have caught an error."
1049 // Assert that the time to replicate the transaction will be sane.
1050 // If this fails, then all DB transactions will be rollback back together.
1051 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1052 if ( $limit > 0 && $time > $limit ) {
1053 throw new DBTransactionSizeError(
1055 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1059 // If a connection sits idle while slow queries execute on another, that connection
1060 // may end up dropped before the commit round is reached. Ping servers to detect this.
1061 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1062 throw new DBTransactionError(
1064 "A connection to the {$conn->getDBname()} database was lost before commit."
1070 public function beginMasterChanges( $fname = __METHOD__
) {
1071 if ( $this->trxRoundId
!== false ) {
1072 throw new DBTransactionError(
1074 "$fname: Transaction round '{$this->trxRoundId}' already started."
1077 $this->trxRoundId
= $fname;
1080 $this->forEachOpenMasterConnection(
1081 function ( Database
$conn ) use ( $fname, &$failures ) {
1082 $conn->setTrxEndCallbackSuppression( true );
1084 $conn->flushSnapshot( $fname );
1085 } catch ( DBError
$e ) {
1086 call_user_func( $this->errorLogger
, $e );
1087 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1089 $conn->setTrxEndCallbackSuppression( false );
1090 $this->applyTransactionRoundFlags( $conn );
1095 throw new DBExpectedError(
1097 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1102 public function commitMasterChanges( $fname = __METHOD__
) {
1105 /** @noinspection PhpUnusedLocalVariableInspection */
1106 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1108 $restore = ( $this->trxRoundId
!== false );
1109 $this->trxRoundId
= false;
1110 $this->forEachOpenMasterConnection(
1111 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1113 if ( $conn->writesOrCallbacksPending() ) {
1114 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1115 } elseif ( $restore ) {
1116 $conn->flushSnapshot( $fname );
1118 } catch ( DBError
$e ) {
1119 call_user_func( $this->errorLogger
, $e );
1120 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1123 $this->undoTransactionRoundFlags( $conn );
1129 throw new DBExpectedError(
1131 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1136 public function runMasterPostTrxCallbacks( $type ) {
1137 $e = null; // first exception
1138 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1139 $conn->setTrxEndCallbackSuppression( false );
1140 if ( $conn->writesOrCallbacksPending() ) {
1141 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1142 // (which finished its callbacks already). Warn and recover in this case. Let the
1143 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1144 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1146 } elseif ( $conn->trxLevel() ) {
1147 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1148 // thus leaving an implicit read-only transaction open at this point. It
1149 // also happens if onTransactionIdle() callbacks leave implicit transactions
1150 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1151 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1155 $conn->runOnTransactionIdleCallbacks( $type );
1156 } catch ( Exception
$ex ) {
1160 $conn->runTransactionListenerCallbacks( $type );
1161 } catch ( Exception
$ex ) {
1169 public function rollbackMasterChanges( $fname = __METHOD__
) {
1170 $restore = ( $this->trxRoundId
!== false );
1171 $this->trxRoundId
= false;
1172 $this->forEachOpenMasterConnection(
1173 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1174 if ( $conn->writesOrCallbacksPending() ) {
1175 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1178 $this->undoTransactionRoundFlags( $conn );
1184 public function suppressTransactionEndCallbacks() {
1185 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1186 $conn->setTrxEndCallbackSuppression( true );
1191 * @param IDatabase $conn
1193 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1194 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1195 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1196 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1197 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1198 // If config has explicitly requested DBO_TRX be either on or off by not
1199 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1200 // for things like blob stores (ExternalStore) which want auto-commit mode.
1205 * @param IDatabase $conn
1207 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1208 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1209 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1213 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1214 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1215 $conn->flushSnapshot( __METHOD__
);
1219 public function hasMasterConnection() {
1220 return $this->isOpen( $this->getWriterIndex() );
1223 public function hasMasterChanges() {
1225 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1226 $pending |
= $conn->writesOrCallbacksPending();
1229 return (bool)$pending;
1232 public function lastMasterChangeTimestamp() {
1234 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1235 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1241 public function hasOrMadeRecentMasterChanges( $age = null ) {
1242 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1244 return ( $this->hasMasterChanges()
1245 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1248 public function pendingMasterChangeCallers() {
1250 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1251 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1257 public function getLaggedReplicaMode( $domain = false ) {
1258 // No-op if there is only one DB (also avoids recursion)
1259 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1261 // See if laggedReplicaMode gets set
1262 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1263 $this->reuseConnection( $conn );
1264 } catch ( DBConnectionError
$e ) {
1265 // Avoid expensive re-connect attempts and failures
1266 $this->allReplicasDownMode
= true;
1267 $this->laggedReplicaMode
= true;
1271 return $this->laggedReplicaMode
;
1275 * @param bool $domain
1277 * @deprecated 1.28; use getLaggedReplicaMode()
1279 public function getLaggedSlaveMode( $domain = false ) {
1280 return $this->getLaggedReplicaMode( $domain );
1283 public function laggedReplicaUsed() {
1284 return $this->laggedReplicaMode
;
1290 * @deprecated Since 1.28; use laggedReplicaUsed()
1292 public function laggedSlaveUsed() {
1293 return $this->laggedReplicaUsed();
1296 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1297 if ( $this->readOnlyReason
!== false ) {
1298 return $this->readOnlyReason
;
1299 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1300 if ( $this->allReplicasDownMode
) {
1301 return 'The database has been automatically locked ' .
1302 'until the replica database servers become available';
1304 return 'The database has been automatically locked ' .
1305 'while the replica database servers catch up to the master.';
1307 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1308 return 'The database master is running in read-only mode.';
1315 * @param string $domain Domain ID, or false for the current domain
1316 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1319 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1320 $cache = $this->wanCache
;
1321 $masterServer = $this->getServerName( $this->getWriterIndex() );
1323 return (bool)$cache->getWithSetCallback(
1324 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1325 self
::TTL_CACHE_READONLY
,
1326 function () use ( $domain, $conn ) {
1327 $old = $this->trxProfiler
->setSilenced( true );
1329 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1330 $readOnly = (int)$dbw->serverIsReadOnly();
1332 $this->reuseConnection( $dbw );
1334 } catch ( DBError
$e ) {
1337 $this->trxProfiler
->setSilenced( $old );
1340 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1344 public function allowLagged( $mode = null ) {
1345 if ( $mode === null ) {
1346 return $this->mAllowLagged
;
1348 $this->mAllowLagged
= $mode;
1350 return $this->mAllowLagged
;
1353 public function pingAll() {
1355 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1356 if ( !$conn->ping() ) {
1364 public function forEachOpenConnection( $callback, array $params = [] ) {
1365 foreach ( $this->mConns
as $connsByServer ) {
1366 foreach ( $connsByServer as $serverConns ) {
1367 foreach ( $serverConns as $conn ) {
1368 $mergedParams = array_merge( [ $conn ], $params );
1369 call_user_func_array( $callback, $mergedParams );
1375 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1376 $masterIndex = $this->getWriterIndex();
1377 foreach ( $this->mConns
as $connsByServer ) {
1378 if ( isset( $connsByServer[$masterIndex] ) ) {
1379 /** @var IDatabase $conn */
1380 foreach ( $connsByServer[$masterIndex] as $conn ) {
1381 $mergedParams = array_merge( [ $conn ], $params );
1382 call_user_func_array( $callback, $mergedParams );
1388 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1389 foreach ( $this->mConns
as $connsByServer ) {
1390 foreach ( $connsByServer as $i => $serverConns ) {
1391 if ( $i === $this->getWriterIndex() ) {
1392 continue; // skip master
1394 foreach ( $serverConns as $conn ) {
1395 $mergedParams = array_merge( [ $conn ], $params );
1396 call_user_func_array( $callback, $mergedParams );
1402 public function getMaxLag( $domain = false ) {
1407 if ( $this->getServerCount() <= 1 ) {
1408 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1411 $lagTimes = $this->getLagTimes( $domain );
1412 foreach ( $lagTimes as $i => $lag ) {
1413 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1415 $host = $this->mServers
[$i]['host'];
1420 return [ $host, $maxLag, $maxIndex ];
1423 public function getLagTimes( $domain = false ) {
1424 if ( $this->getServerCount() <= 1 ) {
1425 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1428 $knownLagTimes = []; // map of (server index => 0 seconds)
1429 $indexesWithLag = [];
1430 foreach ( $this->mServers
as $i => $server ) {
1431 if ( empty( $server['is static'] ) ) {
1432 $indexesWithLag[] = $i; // DB server might have replication lag
1434 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1438 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1441 public function safeGetLag( IDatabase
$conn ) {
1442 if ( $this->getServerCount() <= 1 ) {
1445 return $conn->getLag();
1449 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1450 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1451 return true; // server is not a replica DB
1455 // Get the current master position, opening a connection if needed
1456 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1457 if ( $masterConn ) {
1458 $pos = $masterConn->getMasterPos();
1460 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1461 $pos = $masterConn->getMasterPos();
1462 $this->closeConnection( $masterConn );
1466 if ( $pos instanceof DBMasterPos
) {
1467 $result = $conn->masterPosWait( $pos, $timeout );
1468 if ( $result == -1 ||
is_null( $result ) ) {
1469 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1470 $this->replLogger
->warning( "$msg" );
1473 $this->replLogger
->info( __METHOD__
. ": Done" );
1477 $ok = false; // something is misconfigured
1478 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1484 public function setTransactionListener( $name, callable
$callback = null ) {
1486 $this->trxRecurringCallbacks
[$name] = $callback;
1488 unset( $this->trxRecurringCallbacks
[$name] );
1490 $this->forEachOpenMasterConnection(
1491 function ( IDatabase
$conn ) use ( $name, $callback ) {
1492 $conn->setTransactionListener( $name, $callback );
1497 public function setTableAliases( array $aliases ) {
1498 $this->tableAliases
= $aliases;
1501 public function setDomainPrefix( $prefix ) {
1502 if ( $this->mConns
['foreignUsed'] ) {
1503 // Do not switch connections to explicit foreign domains unless marked as free
1505 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1506 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1508 $domains = implode( ', ', $domains );
1509 throw new DBUnexpectedError( null,
1510 "Foreign domain connections are still in use ($domains)." );
1513 $this->localDomain
= new DatabaseDomain(
1514 $this->localDomain
->getDatabase(),
1519 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1520 $db->tablePrefix( $prefix );
1525 * Make PHP ignore user aborts/disconnects until the returned
1526 * value leaves scope. This returns null and does nothing in CLI mode.
1528 * @return ScopedCallback|null
1530 final protected function getScopedPHPBehaviorForCommit() {
1531 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
1532 $old = ignore_user_abort( true ); // avoid half-finished operations
1533 return new ScopedCallback( function () use ( $old ) {
1534 ignore_user_abort( $old );
1541 function __destruct() {
1542 // Avoid connection leaks for sanity