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 Wikimedia\ScopedCallback
;
27 * Database connection, tracking, load balancing, and transaction manager for a cluster
31 class LoadBalancer
implements ILoadBalancer
{
32 /** @var array[] Map of (server index => server config array) */
34 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
36 /** @var float[] Map of (server index => weight) */
38 /** @var array[] Map of (group => server index => weight) */
40 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
41 private $mAllowLagged;
42 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
43 private $mWaitTimeout;
44 /** @var array The LoadMonitor configuration */
45 private $loadMonitorConfig;
46 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
47 private $tableAliases = [];
49 /** @var ILoadMonitor */
55 /** @var WANObjectCache */
57 /** @var object|string Class name or object With profileIn/profileOut methods */
59 /** @var TransactionProfiler */
60 protected $trxProfiler;
61 /** @var LoggerInterface */
62 protected $replLogger;
63 /** @var LoggerInterface */
64 protected $connLogger;
65 /** @var LoggerInterface */
66 protected $queryLogger;
67 /** @var LoggerInterface */
68 protected $perfLogger;
70 /** @var bool|IDatabase Database connection that caused a problem */
71 private $mErrorConnection;
72 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
74 /** @var bool|DBMasterPos False if not set */
76 /** @var bool Whether the generic reader fell back to a lagged replica DB */
77 private $laggedReplicaMode = false;
78 /** @var bool Whether the generic reader fell back to a lagged replica DB */
79 private $allReplicasDownMode = false;
80 /** @var string The last DB selection or connection error */
81 private $mLastError = 'Unknown error';
82 /** @var string|bool Reason the LB is read-only or false if not */
83 private $readOnlyReason = false;
84 /** @var integer Total connections opened */
85 private $connsOpened = 0;
86 /** @var string|bool String if a requested DBO_TRX transaction round is active */
87 private $trxRoundId = false;
88 /** @var array[] Map of (name => callable) */
89 private $trxRecurringCallbacks = [];
90 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
92 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
93 private $localDomainIdAlias;
94 /** @var string Current server name */
96 /** @var bool Whether this PHP instance is for a CLI script */
98 /** @var string Agent name for query profiling */
101 /** @var callable Exception logger */
102 private $errorLogger;
105 private $disabled = false;
107 /** @var integer Warn when this many connection are held */
108 const CONN_HELD_WARN_THRESHOLD
= 10;
110 /** @var integer Default 'max lag' when unspecified */
111 const MAX_LAG_DEFAULT
= 10;
112 /** @var integer Seconds to cache master server read-only status */
113 const TTL_CACHE_READONLY
= 5;
115 public function __construct( array $params ) {
116 if ( !isset( $params['servers'] ) ) {
117 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
119 $this->mServers
= $params['servers'];
121 $this->localDomain
= isset( $params['localDomain'] )
122 ? DatabaseDomain
::newFromId( $params['localDomain'] )
123 : DatabaseDomain
::newUnspecified();
124 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
125 // always true, gracefully handle the case when they fail to account for escaping.
126 if ( $this->localDomain
->getTablePrefix() != '' ) {
127 $this->localDomainIdAlias
=
128 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
130 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
133 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
135 $this->mReadIndex
= -1;
142 $this->mWaitForPos
= false;
143 $this->mErrorConnection
= false;
144 $this->mAllowLagged
= false;
146 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
147 $this->readOnlyReason
= $params['readOnlyReason'];
150 if ( isset( $params['loadMonitor'] ) ) {
151 $this->loadMonitorConfig
= $params['loadMonitor'];
153 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
156 foreach ( $params['servers'] as $i => $server ) {
157 $this->mLoads
[$i] = $server['load'];
158 if ( isset( $server['groupLoads'] ) ) {
159 foreach ( $server['groupLoads'] as $group => $ratio ) {
160 if ( !isset( $this->mGroupLoads
[$group] ) ) {
161 $this->mGroupLoads
[$group] = [];
163 $this->mGroupLoads
[$group][$i] = $ratio;
168 if ( isset( $params['srvCache'] ) ) {
169 $this->srvCache
= $params['srvCache'];
171 $this->srvCache
= new EmptyBagOStuff();
173 if ( isset( $params['memCache'] ) ) {
174 $this->memCache
= $params['memCache'];
176 $this->memCache
= new EmptyBagOStuff();
178 if ( isset( $params['wanCache'] ) ) {
179 $this->wanCache
= $params['wanCache'];
181 $this->wanCache
= WANObjectCache
::newEmpty();
183 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
184 if ( isset( $params['trxProfiler'] ) ) {
185 $this->trxProfiler
= $params['trxProfiler'];
187 $this->trxProfiler
= new TransactionProfiler();
190 $this->errorLogger
= isset( $params['errorLogger'] )
191 ?
$params['errorLogger']
192 : function ( Exception
$e ) {
193 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
196 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
197 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
200 $this->host
= isset( $params['hostname'] )
201 ?
$params['hostname']
202 : ( gethostname() ?
: 'unknown' );
203 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
204 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
208 * Get a LoadMonitor instance
210 * @return ILoadMonitor
212 private function getLoadMonitor() {
213 if ( !isset( $this->loadMonitor
) ) {
214 $class = $this->loadMonitorConfig
['class'];
215 $this->loadMonitor
= new $class(
216 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
217 $this->loadMonitor
->setLogger( $this->replLogger
);
220 return $this->loadMonitor
;
224 * @param array $loads
225 * @param bool|string $domain Domain to get non-lagged for
226 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
227 * @return bool|int|string
229 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
230 $lags = $this->getLagTimes( $domain );
232 # Unset excessively lagged servers
233 foreach ( $lags as $i => $lag ) {
235 # How much lag this server nominally is allowed to have
236 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
237 ?
$this->mServers
[$i]['max lag']
238 : self
::MAX_LAG_DEFAULT
; // default
239 # Constrain that futher by $maxLag argument
240 $maxServerLag = min( $maxServerLag, $maxLag );
242 $host = $this->getServerName( $i );
243 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
244 $this->replLogger
->error( "Server $host (#$i) is not replicating?" );
246 } elseif ( $lag > $maxServerLag ) {
247 $this->replLogger
->warning( "Server $host (#$i) has >= $lag seconds of lag" );
253 # Find out if all the replica DBs with non-zero load are lagged
255 foreach ( $loads as $load ) {
259 # No appropriate DB servers except maybe the master and some replica DBs with zero load
260 # Do NOT use the master
261 # Instead, this function will return false, triggering read-only mode,
262 # and a lagged replica DB will be used instead.
266 if ( count( $loads ) == 0 ) {
270 # Return a random representative of the remainder
271 return ArrayUtils
::pickRandom( $loads );
274 public function getReaderIndex( $group = false, $domain = false ) {
275 if ( count( $this->mServers
) == 1 ) {
276 # Skip the load balancing if there's only one server
277 return $this->getWriterIndex();
278 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
279 # Shortcut if generic reader exists already
280 return $this->mReadIndex
;
283 # Find the relevant load array
284 if ( $group !== false ) {
285 if ( isset( $this->mGroupLoads
[$group] ) ) {
286 $nonErrorLoads = $this->mGroupLoads
[$group];
288 # No loads for this group, return false and the caller can use some other group
289 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
294 $nonErrorLoads = $this->mLoads
;
297 if ( !count( $nonErrorLoads ) ) {
298 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
301 # Scale the configured load ratios according to the dynamic load if supported
302 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
304 $laggedReplicaMode = false;
306 # No server found yet
308 # First try quickly looking through the available servers for a server that
310 $currentLoads = $nonErrorLoads;
311 while ( count( $currentLoads ) ) {
312 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
313 $i = ArrayUtils
::pickRandom( $currentLoads );
316 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
317 # ChronologyProtecter causes mWaitForPos to be set via sessions.
318 # This triggers doWait() after connect, so it's especially good to
319 # avoid lagged servers so as to avoid just blocking in that method.
320 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
321 # Aim for <= 1 second of waiting (being too picky can backfire)
322 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
324 if ( $i === false ) {
325 # Any server with less lag than it's 'max lag' param is preferable
326 $i = $this->getRandomNonLagged( $currentLoads, $domain );
328 if ( $i === false && count( $currentLoads ) != 0 ) {
329 # All replica DBs lagged. Switch to read-only mode
330 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
331 $i = ArrayUtils
::pickRandom( $currentLoads );
332 $laggedReplicaMode = true;
336 if ( $i === false ) {
337 # pickRandom() returned false
338 # This is permanent and means the configuration or the load monitor
339 # wants us to return false.
340 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
345 $serverName = $this->getServerName( $i );
346 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
348 $conn = $this->openConnection( $i, $domain );
350 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
351 unset( $nonErrorLoads[$i] );
352 unset( $currentLoads[$i] );
357 // Decrement reference counter, we are finished with this connection.
358 // It will be incremented for the caller later.
359 if ( $domain !== false ) {
360 $this->reuseConnection( $conn );
367 # If all servers were down, quit now
368 if ( !count( $nonErrorLoads ) ) {
369 $this->connLogger
->error( "All servers down" );
372 if ( $i !== false ) {
373 # Replica DB connection successful.
374 # Wait for the session master pos for a short time.
375 if ( $this->mWaitForPos
&& $i > 0 ) {
378 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
379 $this->mReadIndex
= $i;
380 # Record if the generic reader index is in "lagged replica DB" mode
381 if ( $laggedReplicaMode ) {
382 $this->laggedReplicaMode
= true;
385 $serverName = $this->getServerName( $i );
386 $this->connLogger
->debug(
387 __METHOD__
. ": using server $serverName for group '$group'" );
394 * @param DBMasterPos|false $pos
396 public function waitFor( $pos ) {
397 $this->mWaitForPos
= $pos;
398 $i = $this->mReadIndex
;
401 if ( !$this->doWait( $i ) ) {
402 $this->laggedReplicaMode
= true;
407 public function waitForOne( $pos, $timeout = null ) {
408 $this->mWaitForPos
= $pos;
410 $i = $this->mReadIndex
;
412 // Pick a generic replica DB if there isn't one yet
413 $readLoads = $this->mLoads
;
414 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
415 $readLoads = array_filter( $readLoads ); // with non-zero load
416 $i = ArrayUtils
::pickRandom( $readLoads );
420 $ok = $this->doWait( $i, true, $timeout );
422 $ok = true; // no applicable loads
428 public function waitForAll( $pos, $timeout = null ) {
429 $this->mWaitForPos
= $pos;
430 $serverCount = count( $this->mServers
);
433 for ( $i = 1; $i < $serverCount; $i++
) {
434 if ( $this->mLoads
[$i] > 0 ) {
435 $ok = $this->doWait( $i, true, $timeout ) && $ok;
444 * @return IDatabase|bool
446 public function getAnyOpenConnection( $i ) {
447 foreach ( $this->mConns
as $connsByServer ) {
448 if ( !empty( $connsByServer[$i] ) ) {
449 /** @var $serverConns IDatabase[] */
450 $serverConns = $connsByServer[$i];
452 return reset( $serverConns );
460 * Wait for a given replica DB to catch up to the master pos stored in $this
461 * @param int $index Server index
462 * @param bool $open Check the server even if a new connection has to be made
463 * @param int $timeout Max seconds to wait; default is mWaitTimeout
466 protected function doWait( $index, $open = false, $timeout = null ) {
467 $close = false; // close the connection afterwards
469 // Check if we already know that the DB has reached this point
470 $server = $this->getServerName( $index );
471 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
472 /** @var DBMasterPos $knownReachedPos */
473 $knownReachedPos = $this->srvCache
->get( $key );
474 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
475 $this->replLogger
->debug( __METHOD__
.
476 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
480 // Find a connection to wait on, creating one if needed and allowed
481 $conn = $this->getAnyOpenConnection( $index );
484 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
488 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
490 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
494 // Avoid connection spam in waitForAll() when connections
495 // are made just for the sake of doing this lag check.
500 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
501 $timeout = $timeout ?
: $this->mWaitTimeout
;
502 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
504 if ( $result == -1 ||
is_null( $result ) ) {
505 // Timed out waiting for replica DB, use master instead
506 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
507 $this->replLogger
->warning( "$msg" );
510 $this->replLogger
->info( __METHOD__
. ": Done" );
512 // Remember that the DB reached this point
513 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
517 $this->closeConnection( $conn );
524 * @see ILoadBalancer::getConnection()
527 * @param array $groups
528 * @param bool $domain
530 * @throws DBConnectionError
532 public function getConnection( $i, $groups = [], $domain = false ) {
533 if ( $i === null ||
$i === false ) {
534 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
535 ' with invalid server index' );
538 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
539 $domain = false; // local connection requested
542 $groups = ( $groups === false ||
$groups === [] )
543 ?
[ false ] // check one "group": the generic pool
546 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
547 $oldConnsOpened = $this->connsOpened
; // connections open now
549 if ( $i == self
::DB_MASTER
) {
550 $i = $this->getWriterIndex();
552 # Try to find an available server in any the query groups (in order)
553 foreach ( $groups as $group ) {
554 $groupIndex = $this->getReaderIndex( $group, $domain );
555 if ( $groupIndex !== false ) {
562 # Operation-based index
563 if ( $i == self
::DB_REPLICA
) {
564 $this->mLastError
= 'Unknown error'; // reset error string
565 # Try the general server pool if $groups are unavailable.
566 $i = ( $groups === [ false ] )
567 ?
false // don't bother with this if that is what was tried above
568 : $this->getReaderIndex( false, $domain );
569 # Couldn't find a working server in getReaderIndex()?
570 if ( $i === false ) {
571 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
572 // Throw an exception
573 $this->reportConnectionError();
574 return null; // not reached
578 # Now we have an explicit index into the servers array
579 $conn = $this->openConnection( $i, $domain );
581 // Throw an exception
582 $this->reportConnectionError();
583 return null; // not reached
586 # Profile any new connections that happen
587 if ( $this->connsOpened
> $oldConnsOpened ) {
588 $host = $conn->getServer();
589 $dbname = $conn->getDBname();
590 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
594 # Make master-requested DB handles inherit any read-only mode setting
595 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
601 public function reuseConnection( $conn ) {
602 $serverIndex = $conn->getLBInfo( 'serverIndex' );
603 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
604 if ( $serverIndex === null ||
$refCount === null ) {
606 * This can happen in code like:
607 * foreach ( $dbs as $db ) {
608 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
610 * $lb->reuseConnection( $conn );
612 * When a connection to the local DB is opened in this way, reuseConnection()
616 } elseif ( $conn instanceof DBConnRef
) {
617 // DBConnRef already handles calling reuseConnection() and only passes the live
618 // Database instance to this method. Any caller passing in a DBConnRef is broken.
619 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
620 ( new RuntimeException() )->getTraceAsString() );
625 if ( $this->disabled
) {
626 return; // DBConnRef handle probably survived longer than the LoadBalancer
629 $domain = $conn->getDomainID();
630 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
631 throw new InvalidArgumentException( __METHOD__
.
632 ": connection $serverIndex/$domain not found; it may have already been freed." );
633 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
634 throw new InvalidArgumentException( __METHOD__
.
635 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
637 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
638 if ( $refCount <= 0 ) {
639 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
640 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
641 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
642 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
644 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
646 $this->connLogger
->debug( __METHOD__
.
647 ": reference count for $serverIndex/$domain reduced to $refCount" );
651 public function getConnectionRef( $db, $groups = [], $domain = false ) {
652 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
654 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
657 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
658 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
660 return new DBConnRef( $this, [ $db, $groups, $domain ] );
663 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
664 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
666 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
670 * @see ILoadBalancer::openConnection()
673 * @param bool $domain
674 * @return bool|Database
675 * @throws DBAccessError
677 public function openConnection( $i, $domain = false ) {
678 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
679 $domain = false; // local connection requested
682 if ( $domain !== false ) {
683 $conn = $this->openForeignConnection( $i, $domain );
684 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
685 $conn = $this->mConns
['local'][$i][0];
687 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
688 throw new InvalidArgumentException( "No server with index '$i'." );
690 // Open a new connection
691 $server = $this->mServers
[$i];
692 $server['serverIndex'] = $i;
693 $conn = $this->reallyOpenConnection( $server, false );
694 $serverName = $this->getServerName( $i );
695 if ( $conn->isOpen() ) {
696 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
697 $this->mConns
['local'][$i][0] = $conn;
699 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
700 $this->mErrorConnection
= $conn;
705 if ( $conn && !$conn->isOpen() ) {
706 // Connection was made but later unrecoverably lost for some reason.
707 // Do not return a handle that will just throw exceptions on use,
708 // but let the calling code (e.g. getReaderIndex) try another server.
709 // See DatabaseMyslBase::ping() for how this can happen.
710 $this->mErrorConnection
= $conn;
718 * Open a connection to a foreign DB, or return one if it is already open.
720 * Increments a reference count on the returned connection which locks the
721 * connection to the requested domain. This reference count can be
722 * decremented by calling reuseConnection().
724 * If a connection is open to the appropriate server already, but with the wrong
725 * database, it will be switched to the right database and returned, as long as
726 * it has been freed first with reuseConnection().
728 * On error, returns false, and the connection which caused the
729 * error will be available via $this->mErrorConnection.
731 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
733 * @param int $i Server index
734 * @param string $domain Domain ID to open
737 private function openForeignConnection( $i, $domain ) {
738 $domainInstance = DatabaseDomain
::newFromId( $domain );
739 $dbName = $domainInstance->getDatabase();
740 $prefix = $domainInstance->getTablePrefix();
742 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
743 // Reuse an already-used connection
744 $conn = $this->mConns
['foreignUsed'][$i][$domain];
745 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
746 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
747 // Reuse a free connection for the same domain
748 $conn = $this->mConns
['foreignFree'][$i][$domain];
749 unset( $this->mConns
['foreignFree'][$i][$domain] );
750 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
751 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
752 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
753 // Reuse a connection from another domain
754 $conn = reset( $this->mConns
['foreignFree'][$i] );
755 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
756 // The empty string as a DB name means "don't care".
757 // DatabaseMysqlBase::open() already handle this on connection.
758 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
759 $this->mLastError
= "Error selecting database '$dbName' on server " .
760 $conn->getServer() . " from client host {$this->host}";
761 $this->mErrorConnection
= $conn;
764 $conn->tablePrefix( $prefix );
765 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
766 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
767 $this->connLogger
->debug( __METHOD__
.
768 ": reusing free connection from $oldDomain for $domain" );
771 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
772 throw new InvalidArgumentException( "No server with index '$i'." );
774 // Open a new connection
775 $server = $this->mServers
[$i];
776 $server['serverIndex'] = $i;
777 $server['foreignPoolRefCount'] = 0;
778 $server['foreign'] = true;
779 $conn = $this->reallyOpenConnection( $server, $dbName );
780 if ( !$conn->isOpen() ) {
781 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
782 $this->mErrorConnection
= $conn;
785 $conn->tablePrefix( $prefix );
786 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
787 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
791 // Increment reference count
793 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
794 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
801 * Test if the specified index represents an open connection
803 * @param int $index Server index
807 private function isOpen( $index ) {
808 if ( !is_integer( $index ) ) {
812 return (bool)$this->getAnyOpenConnection( $index );
816 * Really opens a connection. Uncached.
817 * Returns a Database object whether or not the connection was successful.
820 * @param array $server
821 * @param string|bool $dbNameOverride Use "" to not select any database
823 * @throws DBAccessError
824 * @throws InvalidArgumentException
826 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
827 if ( $this->disabled
) {
828 throw new DBAccessError();
831 if ( $dbNameOverride !== false ) {
832 $server['dbname'] = $dbNameOverride;
835 // Let the handle know what the cluster master is (e.g. "db1052")
836 $masterName = $this->getServerName( $this->getWriterIndex() );
837 $server['clusterMasterHost'] = $masterName;
839 // Log when many connection are made on requests
840 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
841 $this->perfLogger
->warning( __METHOD__
. ": " .
842 "{$this->connsOpened}+ connections made (master=$masterName)" );
845 $server['srvCache'] = $this->srvCache
;
846 // Set loggers and profilers
847 $server['connLogger'] = $this->connLogger
;
848 $server['queryLogger'] = $this->queryLogger
;
849 $server['errorLogger'] = $this->errorLogger
;
850 $server['profiler'] = $this->profiler
;
851 $server['trxProfiler'] = $this->trxProfiler
;
852 // Use the same agent and PHP mode for all DB handles
853 $server['cliMode'] = $this->cliMode
;
854 $server['agent'] = $this->agent
;
855 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
856 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
857 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
859 // Create a live connection object
861 $db = Database
::factory( $server['type'], $server );
862 } catch ( DBConnectionError
$e ) {
863 // FIXME: This is probably the ugliest thing I have ever done to
864 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
868 $db->setLBInfo( $server );
869 $db->setLazyMasterHandle(
870 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
872 $db->setTableAliases( $this->tableAliases
);
874 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
875 if ( $this->trxRoundId
!== false ) {
876 $this->applyTransactionRoundFlags( $db );
878 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
879 $db->setTransactionListener( $name, $callback );
887 * @throws DBConnectionError
889 private function reportConnectionError() {
890 $conn = $this->mErrorConnection
; // the connection which caused the error
892 'method' => __METHOD__
,
893 'last_error' => $this->mLastError
,
896 if ( !is_object( $conn ) ) {
897 // No last connection, probably due to all servers being too busy
898 $this->connLogger
->error(
899 "LB failure with no last connection. Connection error: {last_error}",
903 // If all servers were busy, mLastError will contain something sensible
904 throw new DBConnectionError( null, $this->mLastError
);
906 $context['db_server'] = $conn->getServer();
907 $this->connLogger
->warning(
908 "Connection error: {last_error} ({db_server})",
912 // throws DBConnectionError
913 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
917 public function getWriterIndex() {
921 public function haveIndex( $i ) {
922 return array_key_exists( $i, $this->mServers
);
925 public function isNonZeroLoad( $i ) {
926 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
929 public function getServerCount() {
930 return count( $this->mServers
);
933 public function getServerName( $i ) {
934 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
935 $name = $this->mServers
[$i]['hostName'];
936 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
937 $name = $this->mServers
[$i]['host'];
942 return ( $name != '' ) ?
$name : 'localhost';
945 public function getServerInfo( $i ) {
946 if ( isset( $this->mServers
[$i] ) ) {
947 return $this->mServers
[$i];
953 public function setServerInfo( $i, array $serverInfo ) {
954 $this->mServers
[$i] = $serverInfo;
957 public function getMasterPos() {
958 # If this entire request was served from a replica DB without opening a connection to the
959 # master (however unlikely that may be), then we can fetch the position from the replica DB.
960 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
961 if ( !$masterConn ) {
962 $serverCount = count( $this->mServers
);
963 for ( $i = 1; $i < $serverCount; $i++
) {
964 $conn = $this->getAnyOpenConnection( $i );
966 return $conn->getReplicaPos();
970 return $masterConn->getMasterPos();
976 public function disable() {
978 $this->disabled
= true;
981 public function closeAll() {
982 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
983 $host = $conn->getServer();
984 $this->connLogger
->debug( "Closing connection to database '$host'." );
993 $this->connsOpened
= 0;
996 public function closeConnection( IDatabase
$conn ) {
997 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
998 foreach ( $this->mConns
as $type => $connsByServer ) {
999 if ( !isset( $connsByServer[$serverIndex] ) ) {
1003 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1004 if ( $conn === $trackedConn ) {
1005 $host = $this->getServerName( $i );
1006 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1007 unset( $this->mConns
[$type][$serverIndex][$i] );
1008 --$this->connsOpened
;
1017 public function commitAll( $fname = __METHOD__
) {
1020 $restore = ( $this->trxRoundId
!== false );
1021 $this->trxRoundId
= false;
1022 $this->forEachOpenConnection(
1023 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1025 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1026 } catch ( DBError
$e ) {
1027 call_user_func( $this->errorLogger
, $e );
1028 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1030 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1031 $this->undoTransactionRoundFlags( $conn );
1037 throw new DBExpectedError(
1039 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1044 public function finalizeMasterChanges() {
1045 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1046 // Any error should cause all DB transactions to be rolled back together
1047 $conn->setTrxEndCallbackSuppression( false );
1048 $conn->runOnTransactionPreCommitCallbacks();
1049 // Defer post-commit callbacks until COMMIT finishes for all DBs
1050 $conn->setTrxEndCallbackSuppression( true );
1054 public function approveMasterChanges( array $options ) {
1055 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1056 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1057 // If atomic sections or explicit transactions are still open, some caller must have
1058 // caught an exception but failed to properly rollback any changes. Detect that and
1059 // throw and error (causing rollback).
1060 if ( $conn->explicitTrxActive() ) {
1061 throw new DBTransactionError(
1063 "Explicit transaction still active. A caller may have caught an error."
1066 // Assert that the time to replicate the transaction will be sane.
1067 // If this fails, then all DB transactions will be rollback back together.
1068 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1069 if ( $limit > 0 && $time > $limit ) {
1070 throw new DBTransactionSizeError(
1072 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1076 // If a connection sits idle while slow queries execute on another, that connection
1077 // may end up dropped before the commit round is reached. Ping servers to detect this.
1078 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1079 throw new DBTransactionError(
1081 "A connection to the {$conn->getDBname()} database was lost before commit."
1087 public function beginMasterChanges( $fname = __METHOD__
) {
1088 if ( $this->trxRoundId
!== false ) {
1089 throw new DBTransactionError(
1091 "$fname: Transaction round '{$this->trxRoundId}' already started."
1094 $this->trxRoundId
= $fname;
1097 $this->forEachOpenMasterConnection(
1098 function ( Database
$conn ) use ( $fname, &$failures ) {
1099 $conn->setTrxEndCallbackSuppression( true );
1101 $conn->flushSnapshot( $fname );
1102 } catch ( DBError
$e ) {
1103 call_user_func( $this->errorLogger
, $e );
1104 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1106 $conn->setTrxEndCallbackSuppression( false );
1107 $this->applyTransactionRoundFlags( $conn );
1112 throw new DBExpectedError(
1114 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1119 public function commitMasterChanges( $fname = __METHOD__
) {
1122 /** @noinspection PhpUnusedLocalVariableInspection */
1123 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1125 $restore = ( $this->trxRoundId
!== false );
1126 $this->trxRoundId
= false;
1127 $this->forEachOpenMasterConnection(
1128 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1130 if ( $conn->writesOrCallbacksPending() ) {
1131 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1132 } elseif ( $restore ) {
1133 $conn->flushSnapshot( $fname );
1135 } catch ( DBError
$e ) {
1136 call_user_func( $this->errorLogger
, $e );
1137 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1140 $this->undoTransactionRoundFlags( $conn );
1146 throw new DBExpectedError(
1148 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1153 public function runMasterPostTrxCallbacks( $type ) {
1154 $e = null; // first exception
1155 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1156 $conn->setTrxEndCallbackSuppression( false );
1157 if ( $conn->writesOrCallbacksPending() ) {
1158 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1159 // (which finished its callbacks already). Warn and recover in this case. Let the
1160 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1161 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1163 } elseif ( $conn->trxLevel() ) {
1164 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1165 // thus leaving an implicit read-only transaction open at this point. It
1166 // also happens if onTransactionIdle() callbacks leave implicit transactions
1167 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1168 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1172 $conn->runOnTransactionIdleCallbacks( $type );
1173 } catch ( Exception
$ex ) {
1177 $conn->runTransactionListenerCallbacks( $type );
1178 } catch ( Exception
$ex ) {
1186 public function rollbackMasterChanges( $fname = __METHOD__
) {
1187 $restore = ( $this->trxRoundId
!== false );
1188 $this->trxRoundId
= false;
1189 $this->forEachOpenMasterConnection(
1190 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1191 if ( $conn->writesOrCallbacksPending() ) {
1192 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1195 $this->undoTransactionRoundFlags( $conn );
1201 public function suppressTransactionEndCallbacks() {
1202 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1203 $conn->setTrxEndCallbackSuppression( true );
1208 * @param IDatabase $conn
1210 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1211 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1212 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1213 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1214 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1215 // If config has explicitly requested DBO_TRX be either on or off by not
1216 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1217 // for things like blob stores (ExternalStore) which want auto-commit mode.
1222 * @param IDatabase $conn
1224 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1225 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1226 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1230 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1231 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1232 $conn->flushSnapshot( __METHOD__
);
1236 public function hasMasterConnection() {
1237 return $this->isOpen( $this->getWriterIndex() );
1240 public function hasMasterChanges() {
1242 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1243 $pending |
= $conn->writesOrCallbacksPending();
1246 return (bool)$pending;
1249 public function lastMasterChangeTimestamp() {
1251 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1252 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1258 public function hasOrMadeRecentMasterChanges( $age = null ) {
1259 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1261 return ( $this->hasMasterChanges()
1262 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1265 public function pendingMasterChangeCallers() {
1267 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1268 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1274 public function getLaggedReplicaMode( $domain = false ) {
1275 // No-op if there is only one DB (also avoids recursion)
1276 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1278 // See if laggedReplicaMode gets set
1279 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1280 $this->reuseConnection( $conn );
1281 } catch ( DBConnectionError
$e ) {
1282 // Avoid expensive re-connect attempts and failures
1283 $this->allReplicasDownMode
= true;
1284 $this->laggedReplicaMode
= true;
1288 return $this->laggedReplicaMode
;
1292 * @param bool $domain
1294 * @deprecated 1.28; use getLaggedReplicaMode()
1296 public function getLaggedSlaveMode( $domain = false ) {
1297 return $this->getLaggedReplicaMode( $domain );
1300 public function laggedReplicaUsed() {
1301 return $this->laggedReplicaMode
;
1307 * @deprecated Since 1.28; use laggedReplicaUsed()
1309 public function laggedSlaveUsed() {
1310 return $this->laggedReplicaUsed();
1313 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1314 if ( $this->readOnlyReason
!== false ) {
1315 return $this->readOnlyReason
;
1316 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1317 if ( $this->allReplicasDownMode
) {
1318 return 'The database has been automatically locked ' .
1319 'until the replica database servers become available';
1321 return 'The database has been automatically locked ' .
1322 'while the replica database servers catch up to the master.';
1324 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1325 return 'The database master is running in read-only mode.';
1332 * @param string $domain Domain ID, or false for the current domain
1333 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1336 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1337 $cache = $this->wanCache
;
1338 $masterServer = $this->getServerName( $this->getWriterIndex() );
1340 return (bool)$cache->getWithSetCallback(
1341 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1342 self
::TTL_CACHE_READONLY
,
1343 function () use ( $domain, $conn ) {
1344 $old = $this->trxProfiler
->setSilenced( true );
1346 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1347 $readOnly = (int)$dbw->serverIsReadOnly();
1349 $this->reuseConnection( $dbw );
1351 } catch ( DBError
$e ) {
1354 $this->trxProfiler
->setSilenced( $old );
1357 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1361 public function allowLagged( $mode = null ) {
1362 if ( $mode === null ) {
1363 return $this->mAllowLagged
;
1365 $this->mAllowLagged
= $mode;
1367 return $this->mAllowLagged
;
1370 public function pingAll() {
1372 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1373 if ( !$conn->ping() ) {
1381 public function forEachOpenConnection( $callback, array $params = [] ) {
1382 foreach ( $this->mConns
as $connsByServer ) {
1383 foreach ( $connsByServer as $serverConns ) {
1384 foreach ( $serverConns as $conn ) {
1385 $mergedParams = array_merge( [ $conn ], $params );
1386 call_user_func_array( $callback, $mergedParams );
1392 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1393 $masterIndex = $this->getWriterIndex();
1394 foreach ( $this->mConns
as $connsByServer ) {
1395 if ( isset( $connsByServer[$masterIndex] ) ) {
1396 /** @var IDatabase $conn */
1397 foreach ( $connsByServer[$masterIndex] as $conn ) {
1398 $mergedParams = array_merge( [ $conn ], $params );
1399 call_user_func_array( $callback, $mergedParams );
1405 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1406 foreach ( $this->mConns
as $connsByServer ) {
1407 foreach ( $connsByServer as $i => $serverConns ) {
1408 if ( $i === $this->getWriterIndex() ) {
1409 continue; // skip master
1411 foreach ( $serverConns as $conn ) {
1412 $mergedParams = array_merge( [ $conn ], $params );
1413 call_user_func_array( $callback, $mergedParams );
1419 public function getMaxLag( $domain = false ) {
1424 if ( $this->getServerCount() <= 1 ) {
1425 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1428 $lagTimes = $this->getLagTimes( $domain );
1429 foreach ( $lagTimes as $i => $lag ) {
1430 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1432 $host = $this->mServers
[$i]['host'];
1437 return [ $host, $maxLag, $maxIndex ];
1440 public function getLagTimes( $domain = false ) {
1441 if ( $this->getServerCount() <= 1 ) {
1442 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1445 $knownLagTimes = []; // map of (server index => 0 seconds)
1446 $indexesWithLag = [];
1447 foreach ( $this->mServers
as $i => $server ) {
1448 if ( empty( $server['is static'] ) ) {
1449 $indexesWithLag[] = $i; // DB server might have replication lag
1451 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1455 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1458 public function safeGetLag( IDatabase
$conn ) {
1459 if ( $this->getServerCount() <= 1 ) {
1462 return $conn->getLag();
1467 * @param IDatabase $conn
1468 * @param DBMasterPos|false $pos
1469 * @param int $timeout
1471 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1472 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1473 return true; // server is not a replica DB
1477 // Get the current master position, opening a connection if needed
1478 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1479 if ( $masterConn ) {
1480 $pos = $masterConn->getMasterPos();
1482 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1483 $pos = $masterConn->getMasterPos();
1484 $this->closeConnection( $masterConn );
1488 if ( $pos instanceof DBMasterPos
) {
1489 $result = $conn->masterPosWait( $pos, $timeout );
1490 if ( $result == -1 ||
is_null( $result ) ) {
1491 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1492 $this->replLogger
->warning( "$msg" );
1495 $this->replLogger
->info( __METHOD__
. ": Done" );
1499 $ok = false; // something is misconfigured
1500 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1506 public function setTransactionListener( $name, callable
$callback = null ) {
1508 $this->trxRecurringCallbacks
[$name] = $callback;
1510 unset( $this->trxRecurringCallbacks
[$name] );
1512 $this->forEachOpenMasterConnection(
1513 function ( IDatabase
$conn ) use ( $name, $callback ) {
1514 $conn->setTransactionListener( $name, $callback );
1519 public function setTableAliases( array $aliases ) {
1520 $this->tableAliases
= $aliases;
1523 public function setDomainPrefix( $prefix ) {
1524 if ( $this->mConns
['foreignUsed'] ) {
1525 // Do not switch connections to explicit foreign domains unless marked as free
1527 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1528 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1530 $domains = implode( ', ', $domains );
1531 throw new DBUnexpectedError( null,
1532 "Foreign domain connections are still in use ($domains)." );
1535 $this->localDomain
= new DatabaseDomain(
1536 $this->localDomain
->getDatabase(),
1541 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1542 $db->tablePrefix( $prefix );
1547 * Make PHP ignore user aborts/disconnects until the returned
1548 * value leaves scope. This returns null and does nothing in CLI mode.
1550 * @return ScopedCallback|null
1552 final protected function getScopedPHPBehaviorForCommit() {
1553 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1554 $old = ignore_user_abort( true ); // avoid half-finished operations
1555 return new ScopedCallback( function () use ( $old ) {
1556 ignore_user_abort( $old );
1563 function __destruct() {
1564 // Avoid connection leaks for sanity