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
;
25 use Wikimedia\Rdbms\TransactionProfiler
;
28 * Database connection, tracking, load balancing, and transaction manager for a cluster
32 class LoadBalancer
implements ILoadBalancer
{
33 /** @var array[] Map of (server index => server config array) */
35 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
37 /** @var float[] Map of (server index => weight) */
39 /** @var array[] Map of (group => server index => weight) */
41 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
42 private $mAllowLagged;
43 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
44 private $mWaitTimeout;
45 /** @var array The LoadMonitor configuration */
46 private $loadMonitorConfig;
47 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
48 private $tableAliases = [];
50 /** @var ILoadMonitor */
56 /** @var WANObjectCache */
58 /** @var object|string Class name or object With profileIn/profileOut methods */
60 /** @var TransactionProfiler */
61 protected $trxProfiler;
62 /** @var LoggerInterface */
63 protected $replLogger;
64 /** @var LoggerInterface */
65 protected $connLogger;
66 /** @var LoggerInterface */
67 protected $queryLogger;
68 /** @var LoggerInterface */
69 protected $perfLogger;
71 /** @var bool|IDatabase Database connection that caused a problem */
72 private $mErrorConnection;
73 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
75 /** @var bool|DBMasterPos False if not set */
77 /** @var bool Whether the generic reader fell back to a lagged replica DB */
78 private $laggedReplicaMode = false;
79 /** @var bool Whether the generic reader fell back to a lagged replica DB */
80 private $allReplicasDownMode = false;
81 /** @var string The last DB selection or connection error */
82 private $mLastError = 'Unknown error';
83 /** @var string|bool Reason the LB is read-only or false if not */
84 private $readOnlyReason = false;
85 /** @var integer Total connections opened */
86 private $connsOpened = 0;
87 /** @var string|bool String if a requested DBO_TRX transaction round is active */
88 private $trxRoundId = false;
89 /** @var array[] Map of (name => callable) */
90 private $trxRecurringCallbacks = [];
91 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
93 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
94 private $localDomainIdAlias;
95 /** @var string Current server name */
97 /** @var bool Whether this PHP instance is for a CLI script */
99 /** @var string Agent name for query profiling */
102 /** @var callable Exception logger */
103 private $errorLogger;
106 private $disabled = false;
108 /** @var integer Warn when this many connection are held */
109 const CONN_HELD_WARN_THRESHOLD
= 10;
111 /** @var integer Default 'max lag' when unspecified */
112 const MAX_LAG_DEFAULT
= 10;
113 /** @var integer Seconds to cache master server read-only status */
114 const TTL_CACHE_READONLY
= 5;
116 public function __construct( array $params ) {
117 if ( !isset( $params['servers'] ) ) {
118 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
120 $this->mServers
= $params['servers'];
122 $this->localDomain
= isset( $params['localDomain'] )
123 ? DatabaseDomain
::newFromId( $params['localDomain'] )
124 : DatabaseDomain
::newUnspecified();
125 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
126 // always true, gracefully handle the case when they fail to account for escaping.
127 if ( $this->localDomain
->getTablePrefix() != '' ) {
128 $this->localDomainIdAlias
=
129 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
131 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
134 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
136 $this->mReadIndex
= -1;
143 $this->mWaitForPos
= false;
144 $this->mErrorConnection
= false;
145 $this->mAllowLagged
= false;
147 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
148 $this->readOnlyReason
= $params['readOnlyReason'];
151 if ( isset( $params['loadMonitor'] ) ) {
152 $this->loadMonitorConfig
= $params['loadMonitor'];
154 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
157 foreach ( $params['servers'] as $i => $server ) {
158 $this->mLoads
[$i] = $server['load'];
159 if ( isset( $server['groupLoads'] ) ) {
160 foreach ( $server['groupLoads'] as $group => $ratio ) {
161 if ( !isset( $this->mGroupLoads
[$group] ) ) {
162 $this->mGroupLoads
[$group] = [];
164 $this->mGroupLoads
[$group][$i] = $ratio;
169 if ( isset( $params['srvCache'] ) ) {
170 $this->srvCache
= $params['srvCache'];
172 $this->srvCache
= new EmptyBagOStuff();
174 if ( isset( $params['memCache'] ) ) {
175 $this->memCache
= $params['memCache'];
177 $this->memCache
= new EmptyBagOStuff();
179 if ( isset( $params['wanCache'] ) ) {
180 $this->wanCache
= $params['wanCache'];
182 $this->wanCache
= WANObjectCache
::newEmpty();
184 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
185 if ( isset( $params['trxProfiler'] ) ) {
186 $this->trxProfiler
= $params['trxProfiler'];
188 $this->trxProfiler
= new TransactionProfiler();
191 $this->errorLogger
= isset( $params['errorLogger'] )
192 ?
$params['errorLogger']
193 : function ( Exception
$e ) {
194 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
197 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
198 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
201 $this->host
= isset( $params['hostname'] )
202 ?
$params['hostname']
203 : ( gethostname() ?
: 'unknown' );
204 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
205 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
209 * Get a LoadMonitor instance
211 * @return ILoadMonitor
213 private function getLoadMonitor() {
214 if ( !isset( $this->loadMonitor
) ) {
215 $class = $this->loadMonitorConfig
['class'];
216 $this->loadMonitor
= new $class(
217 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
218 $this->loadMonitor
->setLogger( $this->replLogger
);
221 return $this->loadMonitor
;
225 * @param array $loads
226 * @param bool|string $domain Domain to get non-lagged for
227 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
228 * @return bool|int|string
230 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
231 $lags = $this->getLagTimes( $domain );
233 # Unset excessively lagged servers
234 foreach ( $lags as $i => $lag ) {
236 # How much lag this server nominally is allowed to have
237 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
238 ?
$this->mServers
[$i]['max lag']
239 : self
::MAX_LAG_DEFAULT
; // default
240 # Constrain that futher by $maxLag argument
241 $maxServerLag = min( $maxServerLag, $maxLag );
243 $host = $this->getServerName( $i );
244 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
245 $this->replLogger
->error(
246 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
248 } elseif ( $lag > $maxServerLag ) {
249 $this->replLogger
->warning(
250 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
251 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
258 # Find out if all the replica DBs with non-zero load are lagged
260 foreach ( $loads as $load ) {
264 # No appropriate DB servers except maybe the master and some replica DBs with zero load
265 # Do NOT use the master
266 # Instead, this function will return false, triggering read-only mode,
267 # and a lagged replica DB will be used instead.
271 if ( count( $loads ) == 0 ) {
275 # Return a random representative of the remainder
276 return ArrayUtils
::pickRandom( $loads );
279 public function getReaderIndex( $group = false, $domain = false ) {
280 if ( count( $this->mServers
) == 1 ) {
281 # Skip the load balancing if there's only one server
282 return $this->getWriterIndex();
283 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
284 # Shortcut if generic reader exists already
285 return $this->mReadIndex
;
288 # Find the relevant load array
289 if ( $group !== false ) {
290 if ( isset( $this->mGroupLoads
[$group] ) ) {
291 $nonErrorLoads = $this->mGroupLoads
[$group];
293 # No loads for this group, return false and the caller can use some other group
294 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
299 $nonErrorLoads = $this->mLoads
;
302 if ( !count( $nonErrorLoads ) ) {
303 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
306 # Scale the configured load ratios according to the dynamic load if supported
307 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
309 $laggedReplicaMode = false;
311 # No server found yet
313 # First try quickly looking through the available servers for a server that
315 $currentLoads = $nonErrorLoads;
316 while ( count( $currentLoads ) ) {
317 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
318 $i = ArrayUtils
::pickRandom( $currentLoads );
321 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
322 # ChronologyProtecter causes mWaitForPos to be set via sessions.
323 # This triggers doWait() after connect, so it's especially good to
324 # avoid lagged servers so as to avoid just blocking in that method.
325 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
326 # Aim for <= 1 second of waiting (being too picky can backfire)
327 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
329 if ( $i === false ) {
330 # Any server with less lag than it's 'max lag' param is preferable
331 $i = $this->getRandomNonLagged( $currentLoads, $domain );
333 if ( $i === false && count( $currentLoads ) != 0 ) {
334 # All replica DBs lagged. Switch to read-only mode
335 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
336 $i = ArrayUtils
::pickRandom( $currentLoads );
337 $laggedReplicaMode = true;
341 if ( $i === false ) {
342 # pickRandom() returned false
343 # This is permanent and means the configuration or the load monitor
344 # wants us to return false.
345 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
350 $serverName = $this->getServerName( $i );
351 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
353 $conn = $this->openConnection( $i, $domain );
355 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
356 unset( $nonErrorLoads[$i] );
357 unset( $currentLoads[$i] );
362 // Decrement reference counter, we are finished with this connection.
363 // It will be incremented for the caller later.
364 if ( $domain !== false ) {
365 $this->reuseConnection( $conn );
372 # If all servers were down, quit now
373 if ( !count( $nonErrorLoads ) ) {
374 $this->connLogger
->error( "All servers down" );
377 if ( $i !== false ) {
378 # Replica DB connection successful.
379 # Wait for the session master pos for a short time.
380 if ( $this->mWaitForPos
&& $i > 0 ) {
383 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
384 $this->mReadIndex
= $i;
385 # Record if the generic reader index is in "lagged replica DB" mode
386 if ( $laggedReplicaMode ) {
387 $this->laggedReplicaMode
= true;
390 $serverName = $this->getServerName( $i );
391 $this->connLogger
->debug(
392 __METHOD__
. ": using server $serverName for group '$group'" );
399 * @param DBMasterPos|false $pos
401 public function waitFor( $pos ) {
402 $this->mWaitForPos
= $pos;
403 $i = $this->mReadIndex
;
406 if ( !$this->doWait( $i ) ) {
407 $this->laggedReplicaMode
= true;
412 public function waitForOne( $pos, $timeout = null ) {
413 $this->mWaitForPos
= $pos;
415 $i = $this->mReadIndex
;
417 // Pick a generic replica DB if there isn't one yet
418 $readLoads = $this->mLoads
;
419 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
420 $readLoads = array_filter( $readLoads ); // with non-zero load
421 $i = ArrayUtils
::pickRandom( $readLoads );
425 $ok = $this->doWait( $i, true, $timeout );
427 $ok = true; // no applicable loads
433 public function waitForAll( $pos, $timeout = null ) {
434 $this->mWaitForPos
= $pos;
435 $serverCount = count( $this->mServers
);
438 for ( $i = 1; $i < $serverCount; $i++
) {
439 if ( $this->mLoads
[$i] > 0 ) {
440 $ok = $this->doWait( $i, true, $timeout ) && $ok;
449 * @return IDatabase|bool
451 public function getAnyOpenConnection( $i ) {
452 foreach ( $this->mConns
as $connsByServer ) {
453 if ( !empty( $connsByServer[$i] ) ) {
454 /** @var $serverConns IDatabase[] */
455 $serverConns = $connsByServer[$i];
457 return reset( $serverConns );
465 * Wait for a given replica DB to catch up to the master pos stored in $this
466 * @param int $index Server index
467 * @param bool $open Check the server even if a new connection has to be made
468 * @param int $timeout Max seconds to wait; default is mWaitTimeout
471 protected function doWait( $index, $open = false, $timeout = null ) {
472 $close = false; // close the connection afterwards
474 // Check if we already know that the DB has reached this point
475 $server = $this->getServerName( $index );
476 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
477 /** @var DBMasterPos $knownReachedPos */
478 $knownReachedPos = $this->srvCache
->get( $key );
479 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
480 $this->replLogger
->debug( __METHOD__
.
481 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
485 // Find a connection to wait on, creating one if needed and allowed
486 $conn = $this->getAnyOpenConnection( $index );
489 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
493 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
495 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
499 // Avoid connection spam in waitForAll() when connections
500 // are made just for the sake of doing this lag check.
505 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
506 $timeout = $timeout ?
: $this->mWaitTimeout
;
507 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
509 if ( $result == -1 ||
is_null( $result ) ) {
510 // Timed out waiting for replica DB, use master instead
511 $this->replLogger
->warning(
512 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
513 [ 'host' => $server ]
517 $this->replLogger
->info( __METHOD__
. ": Done" );
519 // Remember that the DB reached this point
520 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
524 $this->closeConnection( $conn );
531 * @see ILoadBalancer::getConnection()
534 * @param array $groups
535 * @param bool $domain
537 * @throws DBConnectionError
539 public function getConnection( $i, $groups = [], $domain = false ) {
540 if ( $i === null ||
$i === false ) {
541 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
542 ' with invalid server index' );
545 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
546 $domain = false; // local connection requested
549 $groups = ( $groups === false ||
$groups === [] )
550 ?
[ false ] // check one "group": the generic pool
553 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
554 $oldConnsOpened = $this->connsOpened
; // connections open now
556 if ( $i == self
::DB_MASTER
) {
557 $i = $this->getWriterIndex();
559 # Try to find an available server in any the query groups (in order)
560 foreach ( $groups as $group ) {
561 $groupIndex = $this->getReaderIndex( $group, $domain );
562 if ( $groupIndex !== false ) {
569 # Operation-based index
570 if ( $i == self
::DB_REPLICA
) {
571 $this->mLastError
= 'Unknown error'; // reset error string
572 # Try the general server pool if $groups are unavailable.
573 $i = ( $groups === [ false ] )
574 ?
false // don't bother with this if that is what was tried above
575 : $this->getReaderIndex( false, $domain );
576 # Couldn't find a working server in getReaderIndex()?
577 if ( $i === false ) {
578 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
579 // Throw an exception
580 $this->reportConnectionError();
581 return null; // not reached
585 # Now we have an explicit index into the servers array
586 $conn = $this->openConnection( $i, $domain );
588 // Throw an exception
589 $this->reportConnectionError();
590 return null; // not reached
593 # Profile any new connections that happen
594 if ( $this->connsOpened
> $oldConnsOpened ) {
595 $host = $conn->getServer();
596 $dbname = $conn->getDBname();
597 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
601 # Make master-requested DB handles inherit any read-only mode setting
602 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
608 public function reuseConnection( $conn ) {
609 $serverIndex = $conn->getLBInfo( 'serverIndex' );
610 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
611 if ( $serverIndex === null ||
$refCount === null ) {
613 * This can happen in code like:
614 * foreach ( $dbs as $db ) {
615 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
617 * $lb->reuseConnection( $conn );
619 * When a connection to the local DB is opened in this way, reuseConnection()
623 } elseif ( $conn instanceof DBConnRef
) {
624 // DBConnRef already handles calling reuseConnection() and only passes the live
625 // Database instance to this method. Any caller passing in a DBConnRef is broken.
626 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
627 ( new RuntimeException() )->getTraceAsString() );
632 if ( $this->disabled
) {
633 return; // DBConnRef handle probably survived longer than the LoadBalancer
636 $domain = $conn->getDomainID();
637 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
638 throw new InvalidArgumentException( __METHOD__
.
639 ": connection $serverIndex/$domain not found; it may have already been freed." );
640 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
641 throw new InvalidArgumentException( __METHOD__
.
642 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
644 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
645 if ( $refCount <= 0 ) {
646 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
647 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
648 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
649 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
651 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
653 $this->connLogger
->debug( __METHOD__
.
654 ": reference count for $serverIndex/$domain reduced to $refCount" );
658 public function getConnectionRef( $db, $groups = [], $domain = false ) {
659 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
661 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
664 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
665 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
667 return new DBConnRef( $this, [ $db, $groups, $domain ] );
670 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
671 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
673 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
677 * @see ILoadBalancer::openConnection()
680 * @param bool $domain
681 * @return bool|Database
682 * @throws DBAccessError
684 public function openConnection( $i, $domain = false ) {
685 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
686 $domain = false; // local connection requested
689 if ( $domain !== false ) {
690 $conn = $this->openForeignConnection( $i, $domain );
691 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
692 $conn = $this->mConns
['local'][$i][0];
694 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
695 throw new InvalidArgumentException( "No server with index '$i'." );
697 // Open a new connection
698 $server = $this->mServers
[$i];
699 $server['serverIndex'] = $i;
700 $conn = $this->reallyOpenConnection( $server, false );
701 $serverName = $this->getServerName( $i );
702 if ( $conn->isOpen() ) {
703 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
704 $this->mConns
['local'][$i][0] = $conn;
706 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
707 $this->mErrorConnection
= $conn;
712 if ( $conn && !$conn->isOpen() ) {
713 // Connection was made but later unrecoverably lost for some reason.
714 // Do not return a handle that will just throw exceptions on use,
715 // but let the calling code (e.g. getReaderIndex) try another server.
716 // See DatabaseMyslBase::ping() for how this can happen.
717 $this->mErrorConnection
= $conn;
725 * Open a connection to a foreign DB, or return one if it is already open.
727 * Increments a reference count on the returned connection which locks the
728 * connection to the requested domain. This reference count can be
729 * decremented by calling reuseConnection().
731 * If a connection is open to the appropriate server already, but with the wrong
732 * database, it will be switched to the right database and returned, as long as
733 * it has been freed first with reuseConnection().
735 * On error, returns false, and the connection which caused the
736 * error will be available via $this->mErrorConnection.
738 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
740 * @param int $i Server index
741 * @param string $domain Domain ID to open
744 private function openForeignConnection( $i, $domain ) {
745 $domainInstance = DatabaseDomain
::newFromId( $domain );
746 $dbName = $domainInstance->getDatabase();
747 $prefix = $domainInstance->getTablePrefix();
749 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
750 // Reuse an already-used connection
751 $conn = $this->mConns
['foreignUsed'][$i][$domain];
752 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
753 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
754 // Reuse a free connection for the same domain
755 $conn = $this->mConns
['foreignFree'][$i][$domain];
756 unset( $this->mConns
['foreignFree'][$i][$domain] );
757 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
758 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
759 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
760 // Reuse a connection from another domain
761 $conn = reset( $this->mConns
['foreignFree'][$i] );
762 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
763 // The empty string as a DB name means "don't care".
764 // DatabaseMysqlBase::open() already handle this on connection.
765 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
766 $this->mLastError
= "Error selecting database '$dbName' on server " .
767 $conn->getServer() . " from client host {$this->host}";
768 $this->mErrorConnection
= $conn;
771 $conn->tablePrefix( $prefix );
772 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
773 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
774 $this->connLogger
->debug( __METHOD__
.
775 ": reusing free connection from $oldDomain for $domain" );
778 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
779 throw new InvalidArgumentException( "No server with index '$i'." );
781 // Open a new connection
782 $server = $this->mServers
[$i];
783 $server['serverIndex'] = $i;
784 $server['foreignPoolRefCount'] = 0;
785 $server['foreign'] = true;
786 $conn = $this->reallyOpenConnection( $server, $dbName );
787 if ( !$conn->isOpen() ) {
788 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
789 $this->mErrorConnection
= $conn;
792 $conn->tablePrefix( $prefix );
793 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
794 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
798 // Increment reference count
800 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
801 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
808 * Test if the specified index represents an open connection
810 * @param int $index Server index
814 private function isOpen( $index ) {
815 if ( !is_integer( $index ) ) {
819 return (bool)$this->getAnyOpenConnection( $index );
823 * Really opens a connection. Uncached.
824 * Returns a Database object whether or not the connection was successful.
827 * @param array $server
828 * @param string|bool $dbNameOverride Use "" to not select any database
830 * @throws DBAccessError
831 * @throws InvalidArgumentException
833 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
834 if ( $this->disabled
) {
835 throw new DBAccessError();
838 if ( $dbNameOverride !== false ) {
839 $server['dbname'] = $dbNameOverride;
842 // Let the handle know what the cluster master is (e.g. "db1052")
843 $masterName = $this->getServerName( $this->getWriterIndex() );
844 $server['clusterMasterHost'] = $masterName;
846 // Log when many connection are made on requests
847 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
848 $this->perfLogger
->warning( __METHOD__
. ": " .
849 "{$this->connsOpened}+ connections made (master=$masterName)" );
852 $server['srvCache'] = $this->srvCache
;
853 // Set loggers and profilers
854 $server['connLogger'] = $this->connLogger
;
855 $server['queryLogger'] = $this->queryLogger
;
856 $server['errorLogger'] = $this->errorLogger
;
857 $server['profiler'] = $this->profiler
;
858 $server['trxProfiler'] = $this->trxProfiler
;
859 // Use the same agent and PHP mode for all DB handles
860 $server['cliMode'] = $this->cliMode
;
861 $server['agent'] = $this->agent
;
862 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
863 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
864 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
866 // Create a live connection object
868 $db = Database
::factory( $server['type'], $server );
869 } catch ( DBConnectionError
$e ) {
870 // FIXME: This is probably the ugliest thing I have ever done to
871 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
875 $db->setLBInfo( $server );
876 $db->setLazyMasterHandle(
877 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
879 $db->setTableAliases( $this->tableAliases
);
881 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
882 if ( $this->trxRoundId
!== false ) {
883 $this->applyTransactionRoundFlags( $db );
885 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
886 $db->setTransactionListener( $name, $callback );
894 * @throws DBConnectionError
896 private function reportConnectionError() {
897 $conn = $this->mErrorConnection
; // the connection which caused the error
899 'method' => __METHOD__
,
900 'last_error' => $this->mLastError
,
903 if ( !is_object( $conn ) ) {
904 // No last connection, probably due to all servers being too busy
905 $this->connLogger
->error(
906 "LB failure with no last connection. Connection error: {last_error}",
910 // If all servers were busy, mLastError will contain something sensible
911 throw new DBConnectionError( null, $this->mLastError
);
913 $context['db_server'] = $conn->getServer();
914 $this->connLogger
->warning(
915 "Connection error: {last_error} ({db_server})",
919 // throws DBConnectionError
920 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
924 public function getWriterIndex() {
928 public function haveIndex( $i ) {
929 return array_key_exists( $i, $this->mServers
);
932 public function isNonZeroLoad( $i ) {
933 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
936 public function getServerCount() {
937 return count( $this->mServers
);
940 public function getServerName( $i ) {
941 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
942 $name = $this->mServers
[$i]['hostName'];
943 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
944 $name = $this->mServers
[$i]['host'];
949 return ( $name != '' ) ?
$name : 'localhost';
952 public function getServerInfo( $i ) {
953 if ( isset( $this->mServers
[$i] ) ) {
954 return $this->mServers
[$i];
960 public function setServerInfo( $i, array $serverInfo ) {
961 $this->mServers
[$i] = $serverInfo;
964 public function getMasterPos() {
965 # If this entire request was served from a replica DB without opening a connection to the
966 # master (however unlikely that may be), then we can fetch the position from the replica DB.
967 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
968 if ( !$masterConn ) {
969 $serverCount = count( $this->mServers
);
970 for ( $i = 1; $i < $serverCount; $i++
) {
971 $conn = $this->getAnyOpenConnection( $i );
973 return $conn->getReplicaPos();
977 return $masterConn->getMasterPos();
983 public function disable() {
985 $this->disabled
= true;
988 public function closeAll() {
989 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
990 $host = $conn->getServer();
991 $this->connLogger
->debug( "Closing connection to database '$host'." );
1000 $this->connsOpened
= 0;
1003 public function closeConnection( IDatabase
$conn ) {
1004 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1005 foreach ( $this->mConns
as $type => $connsByServer ) {
1006 if ( !isset( $connsByServer[$serverIndex] ) ) {
1010 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1011 if ( $conn === $trackedConn ) {
1012 $host = $this->getServerName( $i );
1013 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1014 unset( $this->mConns
[$type][$serverIndex][$i] );
1015 --$this->connsOpened
;
1024 public function commitAll( $fname = __METHOD__
) {
1027 $restore = ( $this->trxRoundId
!== false );
1028 $this->trxRoundId
= false;
1029 $this->forEachOpenConnection(
1030 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1032 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1033 } catch ( DBError
$e ) {
1034 call_user_func( $this->errorLogger
, $e );
1035 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1037 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1038 $this->undoTransactionRoundFlags( $conn );
1044 throw new DBExpectedError(
1046 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1051 public function finalizeMasterChanges() {
1052 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1053 // Any error should cause all DB transactions to be rolled back together
1054 $conn->setTrxEndCallbackSuppression( false );
1055 $conn->runOnTransactionPreCommitCallbacks();
1056 // Defer post-commit callbacks until COMMIT finishes for all DBs
1057 $conn->setTrxEndCallbackSuppression( true );
1061 public function approveMasterChanges( array $options ) {
1062 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1063 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1064 // If atomic sections or explicit transactions are still open, some caller must have
1065 // caught an exception but failed to properly rollback any changes. Detect that and
1066 // throw and error (causing rollback).
1067 if ( $conn->explicitTrxActive() ) {
1068 throw new DBTransactionError(
1070 "Explicit transaction still active. A caller may have caught an error."
1073 // Assert that the time to replicate the transaction will be sane.
1074 // If this fails, then all DB transactions will be rollback back together.
1075 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1076 if ( $limit > 0 && $time > $limit ) {
1077 throw new DBTransactionSizeError(
1079 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1083 // If a connection sits idle while slow queries execute on another, that connection
1084 // may end up dropped before the commit round is reached. Ping servers to detect this.
1085 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1086 throw new DBTransactionError(
1088 "A connection to the {$conn->getDBname()} database was lost before commit."
1094 public function beginMasterChanges( $fname = __METHOD__
) {
1095 if ( $this->trxRoundId
!== false ) {
1096 throw new DBTransactionError(
1098 "$fname: Transaction round '{$this->trxRoundId}' already started."
1101 $this->trxRoundId
= $fname;
1104 $this->forEachOpenMasterConnection(
1105 function ( Database
$conn ) use ( $fname, &$failures ) {
1106 $conn->setTrxEndCallbackSuppression( true );
1108 $conn->flushSnapshot( $fname );
1109 } catch ( DBError
$e ) {
1110 call_user_func( $this->errorLogger
, $e );
1111 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1113 $conn->setTrxEndCallbackSuppression( false );
1114 $this->applyTransactionRoundFlags( $conn );
1119 throw new DBExpectedError(
1121 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1126 public function commitMasterChanges( $fname = __METHOD__
) {
1129 /** @noinspection PhpUnusedLocalVariableInspection */
1130 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1132 $restore = ( $this->trxRoundId
!== false );
1133 $this->trxRoundId
= false;
1134 $this->forEachOpenMasterConnection(
1135 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1137 if ( $conn->writesOrCallbacksPending() ) {
1138 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1139 } elseif ( $restore ) {
1140 $conn->flushSnapshot( $fname );
1142 } catch ( DBError
$e ) {
1143 call_user_func( $this->errorLogger
, $e );
1144 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1147 $this->undoTransactionRoundFlags( $conn );
1153 throw new DBExpectedError(
1155 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1160 public function runMasterPostTrxCallbacks( $type ) {
1161 $e = null; // first exception
1162 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1163 $conn->setTrxEndCallbackSuppression( false );
1164 if ( $conn->writesOrCallbacksPending() ) {
1165 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1166 // (which finished its callbacks already). Warn and recover in this case. Let the
1167 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1168 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1170 } elseif ( $conn->trxLevel() ) {
1171 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1172 // thus leaving an implicit read-only transaction open at this point. It
1173 // also happens if onTransactionIdle() callbacks leave implicit transactions
1174 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1175 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1179 $conn->runOnTransactionIdleCallbacks( $type );
1180 } catch ( Exception
$ex ) {
1184 $conn->runTransactionListenerCallbacks( $type );
1185 } catch ( Exception
$ex ) {
1193 public function rollbackMasterChanges( $fname = __METHOD__
) {
1194 $restore = ( $this->trxRoundId
!== false );
1195 $this->trxRoundId
= false;
1196 $this->forEachOpenMasterConnection(
1197 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1198 if ( $conn->writesOrCallbacksPending() ) {
1199 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1202 $this->undoTransactionRoundFlags( $conn );
1208 public function suppressTransactionEndCallbacks() {
1209 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1210 $conn->setTrxEndCallbackSuppression( true );
1215 * @param IDatabase $conn
1217 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1218 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1219 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1220 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1221 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1222 // If config has explicitly requested DBO_TRX be either on or off by not
1223 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1224 // for things like blob stores (ExternalStore) which want auto-commit mode.
1229 * @param IDatabase $conn
1231 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1232 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1233 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1237 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1238 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1239 $conn->flushSnapshot( __METHOD__
);
1243 public function hasMasterConnection() {
1244 return $this->isOpen( $this->getWriterIndex() );
1247 public function hasMasterChanges() {
1249 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1250 $pending |
= $conn->writesOrCallbacksPending();
1253 return (bool)$pending;
1256 public function lastMasterChangeTimestamp() {
1258 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1259 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1265 public function hasOrMadeRecentMasterChanges( $age = null ) {
1266 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1268 return ( $this->hasMasterChanges()
1269 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1272 public function pendingMasterChangeCallers() {
1274 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1275 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1281 public function getLaggedReplicaMode( $domain = false ) {
1282 // No-op if there is only one DB (also avoids recursion)
1283 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1285 // See if laggedReplicaMode gets set
1286 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1287 $this->reuseConnection( $conn );
1288 } catch ( DBConnectionError
$e ) {
1289 // Avoid expensive re-connect attempts and failures
1290 $this->allReplicasDownMode
= true;
1291 $this->laggedReplicaMode
= true;
1295 return $this->laggedReplicaMode
;
1299 * @param bool $domain
1301 * @deprecated 1.28; use getLaggedReplicaMode()
1303 public function getLaggedSlaveMode( $domain = false ) {
1304 return $this->getLaggedReplicaMode( $domain );
1307 public function laggedReplicaUsed() {
1308 return $this->laggedReplicaMode
;
1314 * @deprecated Since 1.28; use laggedReplicaUsed()
1316 public function laggedSlaveUsed() {
1317 return $this->laggedReplicaUsed();
1320 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1321 if ( $this->readOnlyReason
!== false ) {
1322 return $this->readOnlyReason
;
1323 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1324 if ( $this->allReplicasDownMode
) {
1325 return 'The database has been automatically locked ' .
1326 'until the replica database servers become available';
1328 return 'The database has been automatically locked ' .
1329 'while the replica database servers catch up to the master.';
1331 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1332 return 'The database master is running in read-only mode.';
1339 * @param string $domain Domain ID, or false for the current domain
1340 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1343 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1344 $cache = $this->wanCache
;
1345 $masterServer = $this->getServerName( $this->getWriterIndex() );
1347 return (bool)$cache->getWithSetCallback(
1348 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1349 self
::TTL_CACHE_READONLY
,
1350 function () use ( $domain, $conn ) {
1351 $old = $this->trxProfiler
->setSilenced( true );
1353 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1354 $readOnly = (int)$dbw->serverIsReadOnly();
1356 $this->reuseConnection( $dbw );
1358 } catch ( DBError
$e ) {
1361 $this->trxProfiler
->setSilenced( $old );
1364 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1368 public function allowLagged( $mode = null ) {
1369 if ( $mode === null ) {
1370 return $this->mAllowLagged
;
1372 $this->mAllowLagged
= $mode;
1374 return $this->mAllowLagged
;
1377 public function pingAll() {
1379 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1380 if ( !$conn->ping() ) {
1388 public function forEachOpenConnection( $callback, array $params = [] ) {
1389 foreach ( $this->mConns
as $connsByServer ) {
1390 foreach ( $connsByServer as $serverConns ) {
1391 foreach ( $serverConns as $conn ) {
1392 $mergedParams = array_merge( [ $conn ], $params );
1393 call_user_func_array( $callback, $mergedParams );
1399 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1400 $masterIndex = $this->getWriterIndex();
1401 foreach ( $this->mConns
as $connsByServer ) {
1402 if ( isset( $connsByServer[$masterIndex] ) ) {
1403 /** @var IDatabase $conn */
1404 foreach ( $connsByServer[$masterIndex] as $conn ) {
1405 $mergedParams = array_merge( [ $conn ], $params );
1406 call_user_func_array( $callback, $mergedParams );
1412 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1413 foreach ( $this->mConns
as $connsByServer ) {
1414 foreach ( $connsByServer as $i => $serverConns ) {
1415 if ( $i === $this->getWriterIndex() ) {
1416 continue; // skip master
1418 foreach ( $serverConns as $conn ) {
1419 $mergedParams = array_merge( [ $conn ], $params );
1420 call_user_func_array( $callback, $mergedParams );
1426 public function getMaxLag( $domain = false ) {
1431 if ( $this->getServerCount() <= 1 ) {
1432 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1435 $lagTimes = $this->getLagTimes( $domain );
1436 foreach ( $lagTimes as $i => $lag ) {
1437 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1439 $host = $this->mServers
[$i]['host'];
1444 return [ $host, $maxLag, $maxIndex ];
1447 public function getLagTimes( $domain = false ) {
1448 if ( $this->getServerCount() <= 1 ) {
1449 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1452 $knownLagTimes = []; // map of (server index => 0 seconds)
1453 $indexesWithLag = [];
1454 foreach ( $this->mServers
as $i => $server ) {
1455 if ( empty( $server['is static'] ) ) {
1456 $indexesWithLag[] = $i; // DB server might have replication lag
1458 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1462 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1465 public function safeGetLag( IDatabase
$conn ) {
1466 if ( $this->getServerCount() <= 1 ) {
1469 return $conn->getLag();
1474 * @param IDatabase $conn
1475 * @param DBMasterPos|false $pos
1476 * @param int $timeout
1478 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1479 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1480 return true; // server is not a replica DB
1484 // Get the current master position, opening a connection if needed
1485 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1486 if ( $masterConn ) {
1487 $pos = $masterConn->getMasterPos();
1489 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1490 $pos = $masterConn->getMasterPos();
1491 $this->closeConnection( $masterConn );
1495 if ( $pos instanceof DBMasterPos
) {
1496 $result = $conn->masterPosWait( $pos, $timeout );
1497 if ( $result == -1 ||
is_null( $result ) ) {
1498 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1499 $this->replLogger
->warning( "$msg" );
1502 $this->replLogger
->info( __METHOD__
. ": Done" );
1506 $ok = false; // something is misconfigured
1507 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1513 public function setTransactionListener( $name, callable
$callback = null ) {
1515 $this->trxRecurringCallbacks
[$name] = $callback;
1517 unset( $this->trxRecurringCallbacks
[$name] );
1519 $this->forEachOpenMasterConnection(
1520 function ( IDatabase
$conn ) use ( $name, $callback ) {
1521 $conn->setTransactionListener( $name, $callback );
1526 public function setTableAliases( array $aliases ) {
1527 $this->tableAliases
= $aliases;
1530 public function setDomainPrefix( $prefix ) {
1531 if ( $this->mConns
['foreignUsed'] ) {
1532 // Do not switch connections to explicit foreign domains unless marked as free
1534 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1535 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1537 $domains = implode( ', ', $domains );
1538 throw new DBUnexpectedError( null,
1539 "Foreign domain connections are still in use ($domains)." );
1542 $this->localDomain
= new DatabaseDomain(
1543 $this->localDomain
->getDatabase(),
1548 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1549 $db->tablePrefix( $prefix );
1554 * Make PHP ignore user aborts/disconnects until the returned
1555 * value leaves scope. This returns null and does nothing in CLI mode.
1557 * @return ScopedCallback|null
1559 final protected function getScopedPHPBehaviorForCommit() {
1560 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1561 $old = ignore_user_abort( true ); // avoid half-finished operations
1562 return new ScopedCallback( function () use ( $old ) {
1563 ignore_user_abort( $old );
1570 function __destruct() {
1571 // Avoid connection leaks for sanity