3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Psr\Log\LoggerInterface
;
26 * Database connection, tracking, load balancing, and transaction manager for a cluster
30 class LoadBalancer
implements ILoadBalancer
{
31 /** @var array[] Map of (server index => server config array) */
33 /** @var array[] Map of (local/foreignUsed/foreignFree => server index => IDatabase array) */
35 /** @var float[] Map of (server index => weight) */
37 /** @var array[] Map of (group => server index => weight) */
39 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
40 private $mAllowLagged;
41 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
42 private $mWaitTimeout;
43 /** @var array The LoadMonitor configuration */
44 private $loadMonitorConfig;
45 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
46 private $tableAliases = [];
48 /** @var ILoadMonitor */
54 /** @var WANObjectCache */
56 /** @var object|string Class name or object With profileIn/profileOut methods */
58 /** @var TransactionProfiler */
59 protected $trxProfiler;
60 /** @var LoggerInterface */
61 protected $replLogger;
62 /** @var LoggerInterface */
63 protected $connLogger;
64 /** @var LoggerInterface */
65 protected $queryLogger;
66 /** @var LoggerInterface */
67 protected $perfLogger;
69 /** @var bool|IDatabase Database connection that caused a problem */
70 private $mErrorConnection;
71 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
73 /** @var bool|DBMasterPos False if not set */
75 /** @var bool Whether the generic reader fell back to a lagged replica DB */
76 private $laggedReplicaMode = false;
77 /** @var bool Whether the generic reader fell back to a lagged replica DB */
78 private $allReplicasDownMode = false;
79 /** @var string The last DB selection or connection error */
80 private $mLastError = 'Unknown error';
81 /** @var string|bool Reason the LB is read-only or false if not */
82 private $readOnlyReason = false;
83 /** @var integer Total connections opened */
84 private $connsOpened = 0;
85 /** @var string|bool String if a requested DBO_TRX transaction round is active */
86 private $trxRoundId = false;
87 /** @var array[] Map of (name => callable) */
88 private $trxRecurringCallbacks = [];
89 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
91 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
92 private $localDomainIdAlias;
93 /** @var string Current server name */
95 /** @var bool Whether this PHP instance is for a CLI script */
97 /** @var string Agent name for query profiling */
100 /** @var callable Exception logger */
101 private $errorLogger;
104 private $disabled = false;
106 /** @var integer Warn when this many connection are held */
107 const CONN_HELD_WARN_THRESHOLD
= 10;
108 /** @var integer Default 'max lag' when unspecified */
109 const MAX_LAG_DEFAULT
= 10;
110 /** @var integer Max time to wait for a replica DB to catch up (e.g. ChronologyProtector) */
111 const POS_WAIT_TIMEOUT
= 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'] )
134 ?
$params['waitTimeout']
135 : self
::POS_WAIT_TIMEOUT
;
137 $this->mReadIndex
= -1;
144 $this->mWaitForPos
= false;
145 $this->mErrorConnection
= false;
146 $this->mAllowLagged
= false;
148 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
149 $this->readOnlyReason
= $params['readOnlyReason'];
152 if ( isset( $params['loadMonitor'] ) ) {
153 $this->loadMonitorConfig
= $params['loadMonitor'];
155 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
158 foreach ( $params['servers'] as $i => $server ) {
159 $this->mLoads
[$i] = $server['load'];
160 if ( isset( $server['groupLoads'] ) ) {
161 foreach ( $server['groupLoads'] as $group => $ratio ) {
162 if ( !isset( $this->mGroupLoads
[$group] ) ) {
163 $this->mGroupLoads
[$group] = [];
165 $this->mGroupLoads
[$group][$i] = $ratio;
170 if ( isset( $params['srvCache'] ) ) {
171 $this->srvCache
= $params['srvCache'];
173 $this->srvCache
= new EmptyBagOStuff();
175 if ( isset( $params['memCache'] ) ) {
176 $this->memCache
= $params['memCache'];
178 $this->memCache
= new EmptyBagOStuff();
180 if ( isset( $params['wanCache'] ) ) {
181 $this->wanCache
= $params['wanCache'];
183 $this->wanCache
= WANObjectCache
::newEmpty();
185 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
186 if ( isset( $params['trxProfiler'] ) ) {
187 $this->trxProfiler
= $params['trxProfiler'];
189 $this->trxProfiler
= new TransactionProfiler();
192 $this->errorLogger
= isset( $params['errorLogger'] )
193 ?
$params['errorLogger']
194 : function ( Exception
$e ) {
195 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
198 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
199 $this->$key = isset( $params[$key] ) ?
$params[$key] : new \Psr\Log\
NullLogger();
202 $this->host
= isset( $params['hostname'] )
203 ?
$params['hostname']
204 : ( gethostname() ?
: 'unknown' );
205 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
206 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
210 * Get a LoadMonitor instance
212 * @return ILoadMonitor
214 private function getLoadMonitor() {
215 if ( !isset( $this->loadMonitor
) ) {
216 $class = $this->loadMonitorConfig
['class'];
217 $this->loadMonitor
= new $class(
218 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
219 $this->loadMonitor
->setLogger( $this->replLogger
);
222 return $this->loadMonitor
;
226 * @param array $loads
227 * @param bool|string $domain Domain to get non-lagged for
228 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
229 * @return bool|int|string
231 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
232 $lags = $this->getLagTimes( $domain );
234 # Unset excessively lagged servers
235 foreach ( $lags as $i => $lag ) {
237 # How much lag this server nominally is allowed to have
238 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
239 ?
$this->mServers
[$i]['max lag']
240 : self
::MAX_LAG_DEFAULT
; // default
241 # Constrain that futher by $maxLag argument
242 $maxServerLag = min( $maxServerLag, $maxLag );
244 $host = $this->getServerName( $i );
245 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
246 $this->replLogger
->error( "Server $host (#$i) is not replicating?" );
248 } elseif ( $lag > $maxServerLag ) {
249 $this->replLogger
->warning( "Server $host (#$i) has >= $lag seconds of lag" );
255 # Find out if all the replica DBs with non-zero load are lagged
257 foreach ( $loads as $load ) {
261 # No appropriate DB servers except maybe the master and some replica DBs with zero load
262 # Do NOT use the master
263 # Instead, this function will return false, triggering read-only mode,
264 # and a lagged replica DB will be used instead.
268 if ( count( $loads ) == 0 ) {
272 # Return a random representative of the remainder
273 return ArrayUtils
::pickRandom( $loads );
276 public function getReaderIndex( $group = false, $domain = false ) {
277 if ( count( $this->mServers
) == 1 ) {
278 # Skip the load balancing if there's only one server
279 return $this->getWriterIndex();
280 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
281 # Shortcut if generic reader exists already
282 return $this->mReadIndex
;
285 # Find the relevant load array
286 if ( $group !== false ) {
287 if ( isset( $this->mGroupLoads
[$group] ) ) {
288 $nonErrorLoads = $this->mGroupLoads
[$group];
290 # No loads for this group, return false and the caller can use some other group
291 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
296 $nonErrorLoads = $this->mLoads
;
299 if ( !count( $nonErrorLoads ) ) {
300 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
303 # Scale the configured load ratios according to the dynamic load if supported
304 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
306 $laggedReplicaMode = false;
308 # No server found yet
310 # First try quickly looking through the available servers for a server that
312 $currentLoads = $nonErrorLoads;
313 while ( count( $currentLoads ) ) {
314 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
315 $i = ArrayUtils
::pickRandom( $currentLoads );
318 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
319 # ChronologyProtecter causes mWaitForPos to be set via sessions.
320 # This triggers doWait() after connect, so it's especially good to
321 # avoid lagged servers so as to avoid just blocking in that method.
322 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
323 # Aim for <= 1 second of waiting (being too picky can backfire)
324 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
326 if ( $i === false ) {
327 # Any server with less lag than it's 'max lag' param is preferable
328 $i = $this->getRandomNonLagged( $currentLoads, $domain );
330 if ( $i === false && count( $currentLoads ) != 0 ) {
331 # All replica DBs lagged. Switch to read-only mode
332 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
333 $i = ArrayUtils
::pickRandom( $currentLoads );
334 $laggedReplicaMode = true;
338 if ( $i === false ) {
339 # pickRandom() returned false
340 # This is permanent and means the configuration or the load monitor
341 # wants us to return false.
342 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
347 $serverName = $this->getServerName( $i );
348 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
350 $conn = $this->openConnection( $i, $domain );
352 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
353 unset( $nonErrorLoads[$i] );
354 unset( $currentLoads[$i] );
359 // Decrement reference counter, we are finished with this connection.
360 // It will be incremented for the caller later.
361 if ( $domain !== false ) {
362 $this->reuseConnection( $conn );
369 # If all servers were down, quit now
370 if ( !count( $nonErrorLoads ) ) {
371 $this->connLogger
->error( "All servers down" );
374 if ( $i !== false ) {
375 # Replica DB connection successful.
376 # Wait for the session master pos for a short time.
377 if ( $this->mWaitForPos
&& $i > 0 ) {
380 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
381 $this->mReadIndex
= $i;
382 # Record if the generic reader index is in "lagged replica DB" mode
383 if ( $laggedReplicaMode ) {
384 $this->laggedReplicaMode
= true;
387 $serverName = $this->getServerName( $i );
388 $this->connLogger
->debug(
389 __METHOD__
. ": using server $serverName for group '$group'" );
395 public function waitFor( $pos ) {
396 $this->mWaitForPos
= $pos;
397 $i = $this->mReadIndex
;
400 if ( !$this->doWait( $i ) ) {
401 $this->laggedReplicaMode
= true;
406 public function waitForOne( $pos, $timeout = null ) {
407 $this->mWaitForPos
= $pos;
409 $i = $this->mReadIndex
;
411 // Pick a generic replica DB if there isn't one yet
412 $readLoads = $this->mLoads
;
413 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
414 $readLoads = array_filter( $readLoads ); // with non-zero load
415 $i = ArrayUtils
::pickRandom( $readLoads );
419 $ok = $this->doWait( $i, true, $timeout );
421 $ok = true; // no applicable loads
427 public function waitForAll( $pos, $timeout = null ) {
428 $this->mWaitForPos
= $pos;
429 $serverCount = count( $this->mServers
);
432 for ( $i = 1; $i < $serverCount; $i++
) {
433 if ( $this->mLoads
[$i] > 0 ) {
434 $ok = $this->doWait( $i, true, $timeout ) && $ok;
441 public function getAnyOpenConnection( $i ) {
442 foreach ( $this->mConns
as $connsByServer ) {
443 if ( !empty( $connsByServer[$i] ) ) {
444 return reset( $connsByServer[$i] );
452 * Wait for a given replica DB to catch up to the master pos stored in $this
453 * @param int $index Server index
454 * @param bool $open Check the server even if a new connection has to be made
455 * @param int $timeout Max seconds to wait; default is mWaitTimeout
458 protected function doWait( $index, $open = false, $timeout = null ) {
459 $close = false; // close the connection afterwards
461 // Check if we already know that the DB has reached this point
462 $server = $this->getServerName( $index );
463 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
464 /** @var DBMasterPos $knownReachedPos */
465 $knownReachedPos = $this->srvCache
->get( $key );
466 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
467 $this->replLogger
->debug( __METHOD__
.
468 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
472 // Find a connection to wait on, creating one if needed and allowed
473 $conn = $this->getAnyOpenConnection( $index );
476 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
480 $conn = $this->openConnection( $index, '' );
482 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
486 // Avoid connection spam in waitForAll() when connections
487 // are made just for the sake of doing this lag check.
492 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
493 $timeout = $timeout ?
: $this->mWaitTimeout
;
494 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
496 if ( $result == -1 ||
is_null( $result ) ) {
497 // Timed out waiting for replica DB, use master instead
498 $msg = __METHOD__
. ": Timed out waiting on $server pos {$this->mWaitForPos}";
499 $this->replLogger
->warning( "$msg" );
502 $this->replLogger
->info( __METHOD__
. ": Done" );
504 // Remember that the DB reached this point
505 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
509 $this->closeConnection( $conn );
516 * @see ILoadBalancer::getConnection()
519 * @param array $groups
520 * @param bool $domain
522 * @throws DBConnectionError
524 public function getConnection( $i, $groups = [], $domain = false ) {
525 if ( $i === null ||
$i === false ) {
526 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
527 ' with invalid server index' );
530 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
531 $domain = false; // local connection requested
534 $groups = ( $groups === false ||
$groups === [] )
535 ?
[ false ] // check one "group": the generic pool
538 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
539 $oldConnsOpened = $this->connsOpened
; // connections open now
541 if ( $i == self
::DB_MASTER
) {
542 $i = $this->getWriterIndex();
544 # Try to find an available server in any the query groups (in order)
545 foreach ( $groups as $group ) {
546 $groupIndex = $this->getReaderIndex( $group, $domain );
547 if ( $groupIndex !== false ) {
554 # Operation-based index
555 if ( $i == self
::DB_REPLICA
) {
556 $this->mLastError
= 'Unknown error'; // reset error string
557 # Try the general server pool if $groups are unavailable.
558 $i = in_array( false, $groups, true )
559 ?
false // don't bother with this if that is what was tried above
560 : $this->getReaderIndex( false, $domain );
561 # Couldn't find a working server in getReaderIndex()?
562 if ( $i === false ) {
563 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
564 // Throw an exception
565 $this->reportConnectionError();
566 return null; // not reached
570 # Now we have an explicit index into the servers array
571 $conn = $this->openConnection( $i, $domain );
573 // Throw an exception
574 $this->reportConnectionError();
575 return null; // not reached
578 # Profile any new connections that happen
579 if ( $this->connsOpened
> $oldConnsOpened ) {
580 $host = $conn->getServer();
581 $dbname = $conn->getDBname();
582 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
586 # Make master-requested DB handles inherit any read-only mode setting
587 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
593 public function reuseConnection( $conn ) {
594 $serverIndex = $conn->getLBInfo( 'serverIndex' );
595 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
596 if ( $serverIndex === null ||
$refCount === null ) {
598 * This can happen in code like:
599 * foreach ( $dbs as $db ) {
600 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
602 * $lb->reuseConnection( $conn );
604 * When a connection to the local DB is opened in this way, reuseConnection()
608 } elseif ( $conn instanceof DBConnRef
) {
609 // DBConnRef already handles calling reuseConnection() and only passes the live
610 // Database instance to this method. Any caller passing in a DBConnRef is broken.
611 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
612 ( new RuntimeException() )->getTraceAsString() );
617 if ( $this->disabled
) {
618 return; // DBConnRef handle probably survived longer than the LoadBalancer
621 $domain = $conn->getDomainID();
622 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
623 throw new InvalidArgumentException( __METHOD__
.
624 ": connection $serverIndex/$domain not found; it may have already been freed." );
625 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
626 throw new InvalidArgumentException( __METHOD__
.
627 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
629 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
630 if ( $refCount <= 0 ) {
631 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
632 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
633 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
634 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
636 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
638 $this->connLogger
->debug( __METHOD__
.
639 ": reference count for $serverIndex/$domain reduced to $refCount" );
643 public function getConnectionRef( $db, $groups = [], $domain = false ) {
644 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
646 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
649 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
650 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
652 return new DBConnRef( $this, [ $db, $groups, $domain ] );
656 * @see ILoadBalancer::openConnection()
659 * @param bool $domain
660 * @return bool|Database
661 * @throws DBAccessError
663 public function openConnection( $i, $domain = false ) {
664 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
665 $domain = false; // local connection requested
668 if ( $domain !== false ) {
669 $conn = $this->openForeignConnection( $i, $domain );
670 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
671 $conn = $this->mConns
['local'][$i][0];
673 $server = $this->mServers
[$i];
674 $server['serverIndex'] = $i;
675 $conn = $this->reallyOpenConnection( $server, false );
676 $serverName = $this->getServerName( $i );
677 if ( $conn->isOpen() ) {
678 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
679 $this->mConns
['local'][$i][0] = $conn;
681 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
682 $this->mErrorConnection
= $conn;
687 if ( $conn && !$conn->isOpen() ) {
688 // Connection was made but later unrecoverably lost for some reason.
689 // Do not return a handle that will just throw exceptions on use,
690 // but let the calling code (e.g. getReaderIndex) try another server.
691 // See DatabaseMyslBase::ping() for how this can happen.
692 $this->mErrorConnection
= $conn;
700 * Open a connection to a foreign DB, or return one if it is already open.
702 * Increments a reference count on the returned connection which locks the
703 * connection to the requested domain. This reference count can be
704 * decremented by calling reuseConnection().
706 * If a connection is open to the appropriate server already, but with the wrong
707 * database, it will be switched to the right database and returned, as long as
708 * it has been freed first with reuseConnection().
710 * On error, returns false, and the connection which caused the
711 * error will be available via $this->mErrorConnection.
713 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
715 * @param int $i Server index
716 * @param string $domain Domain ID to open
719 private function openForeignConnection( $i, $domain ) {
720 $domainInstance = DatabaseDomain
::newFromId( $domain );
721 $dbName = $domainInstance->getDatabase();
722 $prefix = $domainInstance->getTablePrefix();
724 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
725 // Reuse an already-used connection
726 $conn = $this->mConns
['foreignUsed'][$i][$domain];
727 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
728 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
729 // Reuse a free connection for the same domain
730 $conn = $this->mConns
['foreignFree'][$i][$domain];
731 unset( $this->mConns
['foreignFree'][$i][$domain] );
732 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
733 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
734 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
735 // Reuse a connection from another domain
736 $conn = reset( $this->mConns
['foreignFree'][$i] );
737 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
738 // The empty string as a DB name means "don't care".
739 // DatabaseMysqlBase::open() already handle this on connection.
740 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
741 $this->mLastError
= "Error selecting database '$dbName' on server " .
742 $conn->getServer() . " from client host {$this->host}";
743 $this->mErrorConnection
= $conn;
746 $conn->tablePrefix( $prefix );
747 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
748 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
749 $this->connLogger
->debug( __METHOD__
.
750 ": reusing free connection from $oldDomain for $domain" );
753 // Open a new connection
754 $server = $this->mServers
[$i];
755 $server['serverIndex'] = $i;
756 $server['foreignPoolRefCount'] = 0;
757 $server['foreign'] = true;
758 $conn = $this->reallyOpenConnection( $server, $dbName );
759 if ( !$conn->isOpen() ) {
760 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
761 $this->mErrorConnection
= $conn;
764 $conn->tablePrefix( $prefix );
765 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
766 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
770 // Increment reference count
772 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
773 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
780 * Test if the specified index represents an open connection
782 * @param int $index Server index
786 private function isOpen( $index ) {
787 if ( !is_integer( $index ) ) {
791 return (bool)$this->getAnyOpenConnection( $index );
795 * Really opens a connection. Uncached.
796 * Returns a Database object whether or not the connection was successful.
799 * @param array $server
800 * @param string|bool $dbNameOverride Use "" to not select any database
802 * @throws DBAccessError
803 * @throws InvalidArgumentException
805 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
806 if ( $this->disabled
) {
807 throw new DBAccessError();
810 if ( !is_array( $server ) ) {
811 throw new InvalidArgumentException(
812 'You must update your load-balancing configuration. ' .
813 'See DefaultSettings.php entry for $wgDBservers.' );
816 if ( $dbNameOverride !== false ) {
817 $server['dbname'] = $dbNameOverride;
820 // Let the handle know what the cluster master is (e.g. "db1052")
821 $masterName = $this->getServerName( $this->getWriterIndex() );
822 $server['clusterMasterHost'] = $masterName;
824 // Log when many connection are made on requests
825 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
826 $this->perfLogger
->warning( __METHOD__
. ": " .
827 "{$this->connsOpened}+ connections made (master=$masterName)" );
830 $server['srvCache'] = $this->srvCache
;
831 // Set loggers and profilers
832 $server['connLogger'] = $this->connLogger
;
833 $server['queryLogger'] = $this->queryLogger
;
834 $server['errorLogger'] = $this->errorLogger
;
835 $server['profiler'] = $this->profiler
;
836 $server['trxProfiler'] = $this->trxProfiler
;
837 // Use the same agent and PHP mode for all DB handles
838 $server['cliMode'] = $this->cliMode
;
839 $server['agent'] = $this->agent
;
840 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
841 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
842 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
844 // Create a live connection object
846 $db = Database
::factory( $server['type'], $server );
847 } catch ( DBConnectionError
$e ) {
848 // FIXME: This is probably the ugliest thing I have ever done to
849 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
853 $db->setLBInfo( $server );
854 $db->setLazyMasterHandle(
855 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
857 $db->setTableAliases( $this->tableAliases
);
859 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
860 if ( $this->trxRoundId
!== false ) {
861 $this->applyTransactionRoundFlags( $db );
863 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
864 $db->setTransactionListener( $name, $callback );
872 * @throws DBConnectionError
874 private function reportConnectionError() {
875 $conn = $this->mErrorConnection
; // the connection which caused the error
877 'method' => __METHOD__
,
878 'last_error' => $this->mLastError
,
881 if ( !is_object( $conn ) ) {
882 // No last connection, probably due to all servers being too busy
883 $this->connLogger
->error(
884 "LB failure with no last connection. Connection error: {last_error}",
888 // If all servers were busy, mLastError will contain something sensible
889 throw new DBConnectionError( null, $this->mLastError
);
891 $context['db_server'] = $conn->getProperty( 'mServer' );
892 $this->connLogger
->warning(
893 "Connection error: {last_error} ({db_server})",
897 // throws DBConnectionError
898 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
902 public function getWriterIndex() {
906 public function haveIndex( $i ) {
907 return array_key_exists( $i, $this->mServers
);
910 public function isNonZeroLoad( $i ) {
911 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
914 public function getServerCount() {
915 return count( $this->mServers
);
918 public function getServerName( $i ) {
919 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
920 $name = $this->mServers
[$i]['hostName'];
921 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
922 $name = $this->mServers
[$i]['host'];
927 return ( $name != '' ) ?
$name : 'localhost';
930 public function getServerInfo( $i ) {
931 if ( isset( $this->mServers
[$i] ) ) {
932 return $this->mServers
[$i];
938 public function setServerInfo( $i, array $serverInfo ) {
939 $this->mServers
[$i] = $serverInfo;
942 public function getMasterPos() {
943 # If this entire request was served from a replica DB without opening a connection to the
944 # master (however unlikely that may be), then we can fetch the position from the replica DB.
945 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
946 if ( !$masterConn ) {
947 $serverCount = count( $this->mServers
);
948 for ( $i = 1; $i < $serverCount; $i++
) {
949 $conn = $this->getAnyOpenConnection( $i );
951 return $conn->getReplicaPos();
955 return $masterConn->getMasterPos();
961 public function disable() {
963 $this->disabled
= true;
966 public function closeAll() {
967 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
968 $host = $conn->getServer();
969 $this->connLogger
->debug( "Closing connection to database '$host'." );
978 $this->connsOpened
= 0;
981 public function closeConnection( IDatabase
$conn ) {
982 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
983 foreach ( $this->mConns
as $type => $connsByServer ) {
984 if ( !isset( $connsByServer[$serverIndex] ) ) {
988 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
989 if ( $conn === $trackedConn ) {
990 $host = $this->getServerName( $i );
991 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
992 unset( $this->mConns
[$type][$serverIndex][$i] );
993 --$this->connsOpened
;
1002 public function commitAll( $fname = __METHOD__
) {
1005 $restore = ( $this->trxRoundId
!== false );
1006 $this->trxRoundId
= false;
1007 $this->forEachOpenConnection(
1008 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1010 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1011 } catch ( DBError
$e ) {
1012 call_user_func( $this->errorLogger
, $e );
1013 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1015 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1016 $this->undoTransactionRoundFlags( $conn );
1022 throw new DBExpectedError(
1024 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1029 public function finalizeMasterChanges() {
1030 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1031 // Any error should cause all DB transactions to be rolled back together
1032 $conn->setTrxEndCallbackSuppression( false );
1033 $conn->runOnTransactionPreCommitCallbacks();
1034 // Defer post-commit callbacks until COMMIT finishes for all DBs
1035 $conn->setTrxEndCallbackSuppression( true );
1039 public function approveMasterChanges( array $options ) {
1040 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1041 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1042 // If atomic sections or explicit transactions are still open, some caller must have
1043 // caught an exception but failed to properly rollback any changes. Detect that and
1044 // throw and error (causing rollback).
1045 if ( $conn->explicitTrxActive() ) {
1046 throw new DBTransactionError(
1048 "Explicit transaction still active. A caller may have caught an error."
1051 // Assert that the time to replicate the transaction will be sane.
1052 // If this fails, then all DB transactions will be rollback back together.
1053 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1054 if ( $limit > 0 && $time > $limit ) {
1055 throw new DBTransactionSizeError(
1057 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1061 // If a connection sits idle while slow queries execute on another, that connection
1062 // may end up dropped before the commit round is reached. Ping servers to detect this.
1063 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1064 throw new DBTransactionError(
1066 "A connection to the {$conn->getDBname()} database was lost before commit."
1072 public function beginMasterChanges( $fname = __METHOD__
) {
1073 if ( $this->trxRoundId
!== false ) {
1074 throw new DBTransactionError(
1076 "$fname: Transaction round '{$this->trxRoundId}' already started."
1079 $this->trxRoundId
= $fname;
1082 $this->forEachOpenMasterConnection(
1083 function ( Database
$conn ) use ( $fname, &$failures ) {
1084 $conn->setTrxEndCallbackSuppression( true );
1086 $conn->flushSnapshot( $fname );
1087 } catch ( DBError
$e ) {
1088 call_user_func( $this->errorLogger
, $e );
1089 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1091 $conn->setTrxEndCallbackSuppression( false );
1092 $this->applyTransactionRoundFlags( $conn );
1097 throw new DBExpectedError(
1099 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1104 public function commitMasterChanges( $fname = __METHOD__
) {
1107 /** @noinspection PhpUnusedLocalVariableInspection */
1108 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1110 $restore = ( $this->trxRoundId
!== false );
1111 $this->trxRoundId
= false;
1112 $this->forEachOpenMasterConnection(
1113 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1115 if ( $conn->writesOrCallbacksPending() ) {
1116 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1117 } elseif ( $restore ) {
1118 $conn->flushSnapshot( $fname );
1120 } catch ( DBError
$e ) {
1121 call_user_func( $this->errorLogger
, $e );
1122 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1125 $this->undoTransactionRoundFlags( $conn );
1131 throw new DBExpectedError(
1133 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1138 public function runMasterPostTrxCallbacks( $type ) {
1139 $e = null; // first exception
1140 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1141 $conn->setTrxEndCallbackSuppression( false );
1142 if ( $conn->writesOrCallbacksPending() ) {
1143 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1144 // (which finished its callbacks already). Warn and recover in this case. Let the
1145 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1146 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1148 } elseif ( $conn->trxLevel() ) {
1149 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1150 // thus leaving an implicit read-only transaction open at this point. It
1151 // also happens if onTransactionIdle() callbacks leave implicit transactions
1152 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1153 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1157 $conn->runOnTransactionIdleCallbacks( $type );
1158 } catch ( Exception
$ex ) {
1162 $conn->runTransactionListenerCallbacks( $type );
1163 } catch ( Exception
$ex ) {
1171 public function rollbackMasterChanges( $fname = __METHOD__
) {
1172 $restore = ( $this->trxRoundId
!== false );
1173 $this->trxRoundId
= false;
1174 $this->forEachOpenMasterConnection(
1175 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1176 if ( $conn->writesOrCallbacksPending() ) {
1177 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1180 $this->undoTransactionRoundFlags( $conn );
1186 public function suppressTransactionEndCallbacks() {
1187 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1188 $conn->setTrxEndCallbackSuppression( true );
1193 * @param IDatabase $conn
1195 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1196 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1197 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1198 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1199 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1200 // If config has explicitly requested DBO_TRX be either on or off by not
1201 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1202 // for things like blob stores (ExternalStore) which want auto-commit mode.
1207 * @param IDatabase $conn
1209 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1210 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1211 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1215 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1216 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1217 $conn->flushSnapshot( __METHOD__
);
1221 public function hasMasterConnection() {
1222 return $this->isOpen( $this->getWriterIndex() );
1225 public function hasMasterChanges() {
1227 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1228 $pending |
= $conn->writesOrCallbacksPending();
1231 return (bool)$pending;
1234 public function lastMasterChangeTimestamp() {
1236 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1237 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1243 public function hasOrMadeRecentMasterChanges( $age = null ) {
1244 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1246 return ( $this->hasMasterChanges()
1247 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1250 public function pendingMasterChangeCallers() {
1252 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1253 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1259 public function getLaggedReplicaMode( $domain = false ) {
1260 // No-op if there is only one DB (also avoids recursion)
1261 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1263 // See if laggedReplicaMode gets set
1264 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1265 $this->reuseConnection( $conn );
1266 } catch ( DBConnectionError
$e ) {
1267 // Avoid expensive re-connect attempts and failures
1268 $this->allReplicasDownMode
= true;
1269 $this->laggedReplicaMode
= true;
1273 return $this->laggedReplicaMode
;
1277 * @param bool $domain
1279 * @deprecated 1.28; use getLaggedReplicaMode()
1281 public function getLaggedSlaveMode( $domain = false ) {
1282 return $this->getLaggedReplicaMode( $domain );
1285 public function laggedReplicaUsed() {
1286 return $this->laggedReplicaMode
;
1292 * @deprecated Since 1.28; use laggedReplicaUsed()
1294 public function laggedSlaveUsed() {
1295 return $this->laggedReplicaUsed();
1298 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1299 if ( $this->readOnlyReason
!== false ) {
1300 return $this->readOnlyReason
;
1301 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1302 if ( $this->allReplicasDownMode
) {
1303 return 'The database has been automatically locked ' .
1304 'until the replica database servers become available';
1306 return 'The database has been automatically locked ' .
1307 'while the replica database servers catch up to the master.';
1309 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1310 return 'The database master is running in read-only mode.';
1317 * @param string $domain Domain ID, or false for the current domain
1318 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1321 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1322 $cache = $this->wanCache
;
1323 $masterServer = $this->getServerName( $this->getWriterIndex() );
1325 return (bool)$cache->getWithSetCallback(
1326 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1327 self
::TTL_CACHE_READONLY
,
1328 function () use ( $domain, $conn ) {
1329 $this->trxProfiler
->setSilenced( true );
1331 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1332 $readOnly = (int)$dbw->serverIsReadOnly();
1334 $this->reuseConnection( $dbw );
1336 } catch ( DBError
$e ) {
1339 $this->trxProfiler
->setSilenced( false );
1342 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1346 public function allowLagged( $mode = null ) {
1347 if ( $mode === null ) {
1348 return $this->mAllowLagged
;
1350 $this->mAllowLagged
= $mode;
1352 return $this->mAllowLagged
;
1355 public function pingAll() {
1357 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1358 if ( !$conn->ping() ) {
1366 public function forEachOpenConnection( $callback, array $params = [] ) {
1367 foreach ( $this->mConns
as $connsByServer ) {
1368 foreach ( $connsByServer as $serverConns ) {
1369 foreach ( $serverConns as $conn ) {
1370 $mergedParams = array_merge( [ $conn ], $params );
1371 call_user_func_array( $callback, $mergedParams );
1377 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1378 $masterIndex = $this->getWriterIndex();
1379 foreach ( $this->mConns
as $connsByServer ) {
1380 if ( isset( $connsByServer[$masterIndex] ) ) {
1381 /** @var IDatabase $conn */
1382 foreach ( $connsByServer[$masterIndex] as $conn ) {
1383 $mergedParams = array_merge( [ $conn ], $params );
1384 call_user_func_array( $callback, $mergedParams );
1390 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1391 foreach ( $this->mConns
as $connsByServer ) {
1392 foreach ( $connsByServer as $i => $serverConns ) {
1393 if ( $i === $this->getWriterIndex() ) {
1394 continue; // skip master
1396 foreach ( $serverConns as $conn ) {
1397 $mergedParams = array_merge( [ $conn ], $params );
1398 call_user_func_array( $callback, $mergedParams );
1404 public function getMaxLag( $domain = false ) {
1409 if ( $this->getServerCount() <= 1 ) {
1410 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1413 $lagTimes = $this->getLagTimes( $domain );
1414 foreach ( $lagTimes as $i => $lag ) {
1415 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1417 $host = $this->mServers
[$i]['host'];
1422 return [ $host, $maxLag, $maxIndex ];
1425 public function getLagTimes( $domain = false ) {
1426 if ( $this->getServerCount() <= 1 ) {
1427 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1430 $knownLagTimes = []; // map of (server index => 0 seconds)
1431 $indexesWithLag = [];
1432 foreach ( $this->mServers
as $i => $server ) {
1433 if ( empty( $server['is static'] ) ) {
1434 $indexesWithLag[] = $i; // DB server might have replication lag
1436 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1440 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1443 public function safeGetLag( IDatabase
$conn ) {
1444 if ( $this->getServerCount() <= 1 ) {
1447 return $conn->getLag();
1451 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1452 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1453 return true; // server is not a replica DB
1457 // Get the current master position
1458 $dbw = $this->getConnection( self
::DB_MASTER
);
1459 $pos = $dbw->getMasterPos();
1460 $this->reuseConnection( $dbw );
1463 if ( $pos instanceof DBMasterPos
) {
1464 $result = $conn->masterPosWait( $pos, $timeout );
1465 if ( $result == -1 ||
is_null( $result ) ) {
1466 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1467 $this->replLogger
->warning( "$msg" );
1470 $this->replLogger
->info( __METHOD__
. ": Done" );
1474 $ok = false; // something is misconfigured
1475 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1481 public function setTransactionListener( $name, callable
$callback = null ) {
1483 $this->trxRecurringCallbacks
[$name] = $callback;
1485 unset( $this->trxRecurringCallbacks
[$name] );
1487 $this->forEachOpenMasterConnection(
1488 function ( IDatabase
$conn ) use ( $name, $callback ) {
1489 $conn->setTransactionListener( $name, $callback );
1494 public function setTableAliases( array $aliases ) {
1495 $this->tableAliases
= $aliases;
1498 public function setDomainPrefix( $prefix ) {
1499 if ( $this->mConns
['foreignUsed'] ) {
1500 // Do not switch connections to explicit foreign domains unless marked as free
1502 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1503 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1505 $domains = implode( ', ', $domains );
1506 throw new DBUnexpectedError( null,
1507 "Foreign domain connections are still in use ($domains)." );
1510 $this->localDomain
= new DatabaseDomain(
1511 $this->localDomain
->getDatabase(),
1516 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1517 $db->tablePrefix( $prefix );
1522 * Make PHP ignore user aborts/disconnects until the returned
1523 * value leaves scope. This returns null and does nothing in CLI mode.
1525 * @return ScopedCallback|null
1527 final protected function getScopedPHPBehaviorForCommit() {
1528 if ( PHP_SAPI
!= 'cli' ) { // http://bugs.php.net/bug.php?id=47540
1529 $old = ignore_user_abort( true ); // avoid half-finished operations
1530 return new ScopedCallback( function () use ( $old ) {
1531 ignore_user_abort( $old );
1538 function __destruct() {
1539 // Avoid connection leaks for sanity