3 * Database load balancing manager
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use Psr\Log\LoggerInterface
;
24 use Psr\Log\NullLogger
;
25 use Wikimedia\ScopedCallback
;
26 use Wikimedia\Rdbms\TransactionProfiler
;
27 use Wikimedia\Rdbms\ILoadMonitor
;
28 use Wikimedia\Rdbms\DatabaseDomain
;
29 use Wikimedia\Rdbms\ILoadBalancer
;
30 use Wikimedia\Rdbms\DBMasterPos
;
33 * Database connection, tracking, load balancing, and transaction manager for a cluster
37 class LoadBalancer
implements ILoadBalancer
{
38 /** @var array[] Map of (server index => server config array) */
40 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
42 /** @var float[] Map of (server index => weight) */
44 /** @var array[] Map of (group => server index => weight) */
46 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
47 private $mAllowLagged;
48 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
49 private $mWaitTimeout;
50 /** @var array The LoadMonitor configuration */
51 private $loadMonitorConfig;
52 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
53 private $tableAliases = [];
55 /** @var ILoadMonitor */
61 /** @var WANObjectCache */
63 /** @var object|string Class name or object With profileIn/profileOut methods */
65 /** @var TransactionProfiler */
66 protected $trxProfiler;
67 /** @var LoggerInterface */
68 protected $replLogger;
69 /** @var LoggerInterface */
70 protected $connLogger;
71 /** @var LoggerInterface */
72 protected $queryLogger;
73 /** @var LoggerInterface */
74 protected $perfLogger;
76 /** @var bool|IDatabase Database connection that caused a problem */
77 private $mErrorConnection;
78 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
80 /** @var bool|DBMasterPos False if not set */
82 /** @var bool Whether the generic reader fell back to a lagged replica DB */
83 private $laggedReplicaMode = false;
84 /** @var bool Whether the generic reader fell back to a lagged replica DB */
85 private $allReplicasDownMode = false;
86 /** @var string The last DB selection or connection error */
87 private $mLastError = 'Unknown error';
88 /** @var string|bool Reason the LB is read-only or false if not */
89 private $readOnlyReason = false;
90 /** @var integer Total connections opened */
91 private $connsOpened = 0;
92 /** @var string|bool String if a requested DBO_TRX transaction round is active */
93 private $trxRoundId = false;
94 /** @var array[] Map of (name => callable) */
95 private $trxRecurringCallbacks = [];
96 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
98 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
99 private $localDomainIdAlias;
100 /** @var string Current server name */
102 /** @var bool Whether this PHP instance is for a CLI script */
104 /** @var string Agent name for query profiling */
107 /** @var callable Exception logger */
108 private $errorLogger;
111 private $disabled = false;
113 /** @var integer Warn when this many connection are held */
114 const CONN_HELD_WARN_THRESHOLD
= 10;
116 /** @var integer Default 'max lag' when unspecified */
117 const MAX_LAG_DEFAULT
= 10;
118 /** @var integer Seconds to cache master server read-only status */
119 const TTL_CACHE_READONLY
= 5;
121 public function __construct( array $params ) {
122 if ( !isset( $params['servers'] ) ) {
123 throw new InvalidArgumentException( __CLASS__
. ': missing servers parameter' );
125 $this->mServers
= $params['servers'];
127 $this->localDomain
= isset( $params['localDomain'] )
128 ? DatabaseDomain
::newFromId( $params['localDomain'] )
129 : DatabaseDomain
::newUnspecified();
130 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
131 // always true, gracefully handle the case when they fail to account for escaping.
132 if ( $this->localDomain
->getTablePrefix() != '' ) {
133 $this->localDomainIdAlias
=
134 $this->localDomain
->getDatabase() . '-' . $this->localDomain
->getTablePrefix();
136 $this->localDomainIdAlias
= $this->localDomain
->getDatabase();
139 $this->mWaitTimeout
= isset( $params['waitTimeout'] ) ?
$params['waitTimeout'] : 10;
141 $this->mReadIndex
= -1;
148 $this->mWaitForPos
= false;
149 $this->mErrorConnection
= false;
150 $this->mAllowLagged
= false;
152 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
153 $this->readOnlyReason
= $params['readOnlyReason'];
156 if ( isset( $params['loadMonitor'] ) ) {
157 $this->loadMonitorConfig
= $params['loadMonitor'];
159 $this->loadMonitorConfig
= [ 'class' => 'LoadMonitorNull' ];
162 foreach ( $params['servers'] as $i => $server ) {
163 $this->mLoads
[$i] = $server['load'];
164 if ( isset( $server['groupLoads'] ) ) {
165 foreach ( $server['groupLoads'] as $group => $ratio ) {
166 if ( !isset( $this->mGroupLoads
[$group] ) ) {
167 $this->mGroupLoads
[$group] = [];
169 $this->mGroupLoads
[$group][$i] = $ratio;
174 if ( isset( $params['srvCache'] ) ) {
175 $this->srvCache
= $params['srvCache'];
177 $this->srvCache
= new EmptyBagOStuff();
179 if ( isset( $params['memCache'] ) ) {
180 $this->memCache
= $params['memCache'];
182 $this->memCache
= new EmptyBagOStuff();
184 if ( isset( $params['wanCache'] ) ) {
185 $this->wanCache
= $params['wanCache'];
187 $this->wanCache
= WANObjectCache
::newEmpty();
189 $this->profiler
= isset( $params['profiler'] ) ?
$params['profiler'] : null;
190 if ( isset( $params['trxProfiler'] ) ) {
191 $this->trxProfiler
= $params['trxProfiler'];
193 $this->trxProfiler
= new TransactionProfiler();
196 $this->errorLogger
= isset( $params['errorLogger'] )
197 ?
$params['errorLogger']
198 : function ( Exception
$e ) {
199 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
202 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
203 $this->$key = isset( $params[$key] ) ?
$params[$key] : new NullLogger();
206 $this->host
= isset( $params['hostname'] )
207 ?
$params['hostname']
208 : ( gethostname() ?
: 'unknown' );
209 $this->cliMode
= isset( $params['cliMode'] ) ?
$params['cliMode'] : PHP_SAPI
=== 'cli';
210 $this->agent
= isset( $params['agent'] ) ?
$params['agent'] : '';
214 * Get a LoadMonitor instance
216 * @return ILoadMonitor
218 private function getLoadMonitor() {
219 if ( !isset( $this->loadMonitor
) ) {
221 'LoadMonitor' => Wikimedia\Rdbms\LoadMonitor
::class,
222 'LoadMonitorNull' => Wikimedia\Rdbms\LoadMonitorNull
::class,
223 'LoadMonitorMySQL' => Wikimedia\Rdbms\LoadMonitorMySQL
::class,
226 $class = $this->loadMonitorConfig
['class'];
227 if ( isset( $compat[$class] ) ) {
228 $class = $compat[$class];
231 $this->loadMonitor
= new $class(
232 $this, $this->srvCache
, $this->memCache
, $this->loadMonitorConfig
);
233 $this->loadMonitor
->setLogger( $this->replLogger
);
236 return $this->loadMonitor
;
240 * @param array $loads
241 * @param bool|string $domain Domain to get non-lagged for
242 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
243 * @return bool|int|string
245 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF
) {
246 $lags = $this->getLagTimes( $domain );
248 # Unset excessively lagged servers
249 foreach ( $lags as $i => $lag ) {
251 # How much lag this server nominally is allowed to have
252 $maxServerLag = isset( $this->mServers
[$i]['max lag'] )
253 ?
$this->mServers
[$i]['max lag']
254 : self
::MAX_LAG_DEFAULT
; // default
255 # Constrain that futher by $maxLag argument
256 $maxServerLag = min( $maxServerLag, $maxLag );
258 $host = $this->getServerName( $i );
259 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
260 $this->replLogger
->error(
261 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
263 } elseif ( $lag > $maxServerLag ) {
264 $this->replLogger
->warning(
265 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
266 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
273 # Find out if all the replica DBs with non-zero load are lagged
275 foreach ( $loads as $load ) {
279 # No appropriate DB servers except maybe the master and some replica DBs with zero load
280 # Do NOT use the master
281 # Instead, this function will return false, triggering read-only mode,
282 # and a lagged replica DB will be used instead.
286 if ( count( $loads ) == 0 ) {
290 # Return a random representative of the remainder
291 return ArrayUtils
::pickRandom( $loads );
294 public function getReaderIndex( $group = false, $domain = false ) {
295 if ( count( $this->mServers
) == 1 ) {
296 # Skip the load balancing if there's only one server
297 return $this->getWriterIndex();
298 } elseif ( $group === false && $this->mReadIndex
>= 0 ) {
299 # Shortcut if generic reader exists already
300 return $this->mReadIndex
;
303 # Find the relevant load array
304 if ( $group !== false ) {
305 if ( isset( $this->mGroupLoads
[$group] ) ) {
306 $nonErrorLoads = $this->mGroupLoads
[$group];
308 # No loads for this group, return false and the caller can use some other group
309 $this->connLogger
->info( __METHOD__
. ": no loads for group $group" );
314 $nonErrorLoads = $this->mLoads
;
317 if ( !count( $nonErrorLoads ) ) {
318 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
321 # Scale the configured load ratios according to the dynamic load if supported
322 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
324 $laggedReplicaMode = false;
326 # No server found yet
328 # First try quickly looking through the available servers for a server that
330 $currentLoads = $nonErrorLoads;
331 while ( count( $currentLoads ) ) {
332 if ( $this->mAllowLagged ||
$laggedReplicaMode ) {
333 $i = ArrayUtils
::pickRandom( $currentLoads );
336 if ( $this->mWaitForPos
&& $this->mWaitForPos
->asOfTime() ) {
337 # ChronologyProtecter causes mWaitForPos to be set via sessions.
338 # This triggers doWait() after connect, so it's especially good to
339 # avoid lagged servers so as to avoid just blocking in that method.
340 $ago = microtime( true ) - $this->mWaitForPos
->asOfTime();
341 # Aim for <= 1 second of waiting (being too picky can backfire)
342 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago +
1 );
344 if ( $i === false ) {
345 # Any server with less lag than it's 'max lag' param is preferable
346 $i = $this->getRandomNonLagged( $currentLoads, $domain );
348 if ( $i === false && count( $currentLoads ) != 0 ) {
349 # All replica DBs lagged. Switch to read-only mode
350 $this->replLogger
->error( "All replica DBs lagged. Switch to read-only mode" );
351 $i = ArrayUtils
::pickRandom( $currentLoads );
352 $laggedReplicaMode = true;
356 if ( $i === false ) {
357 # pickRandom() returned false
358 # This is permanent and means the configuration or the load monitor
359 # wants us to return false.
360 $this->connLogger
->debug( __METHOD__
. ": pickRandom() returned false" );
365 $serverName = $this->getServerName( $i );
366 $this->connLogger
->debug( __METHOD__
. ": Using reader #$i: $serverName..." );
368 $conn = $this->openConnection( $i, $domain );
370 $this->connLogger
->warning( __METHOD__
. ": Failed connecting to $i/$domain" );
371 unset( $nonErrorLoads[$i] );
372 unset( $currentLoads[$i] );
377 // Decrement reference counter, we are finished with this connection.
378 // It will be incremented for the caller later.
379 if ( $domain !== false ) {
380 $this->reuseConnection( $conn );
387 # If all servers were down, quit now
388 if ( !count( $nonErrorLoads ) ) {
389 $this->connLogger
->error( "All servers down" );
392 if ( $i !== false ) {
393 # Replica DB connection successful.
394 # Wait for the session master pos for a short time.
395 if ( $this->mWaitForPos
&& $i > 0 ) {
398 if ( $this->mReadIndex
<= 0 && $this->mLoads
[$i] > 0 && $group === false ) {
399 $this->mReadIndex
= $i;
400 # Record if the generic reader index is in "lagged replica DB" mode
401 if ( $laggedReplicaMode ) {
402 $this->laggedReplicaMode
= true;
405 $serverName = $this->getServerName( $i );
406 $this->connLogger
->debug(
407 __METHOD__
. ": using server $serverName for group '$group'" );
414 * @param DBMasterPos|false $pos
416 public function waitFor( $pos ) {
417 $this->mWaitForPos
= $pos;
418 $i = $this->mReadIndex
;
421 if ( !$this->doWait( $i ) ) {
422 $this->laggedReplicaMode
= true;
427 public function waitForOne( $pos, $timeout = null ) {
428 $this->mWaitForPos
= $pos;
430 $i = $this->mReadIndex
;
432 // Pick a generic replica DB if there isn't one yet
433 $readLoads = $this->mLoads
;
434 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
435 $readLoads = array_filter( $readLoads ); // with non-zero load
436 $i = ArrayUtils
::pickRandom( $readLoads );
440 $ok = $this->doWait( $i, true, $timeout );
442 $ok = true; // no applicable loads
448 public function waitForAll( $pos, $timeout = null ) {
449 $this->mWaitForPos
= $pos;
450 $serverCount = count( $this->mServers
);
453 for ( $i = 1; $i < $serverCount; $i++
) {
454 if ( $this->mLoads
[$i] > 0 ) {
455 $ok = $this->doWait( $i, true, $timeout ) && $ok;
464 * @return IDatabase|bool
466 public function getAnyOpenConnection( $i ) {
467 foreach ( $this->mConns
as $connsByServer ) {
468 if ( !empty( $connsByServer[$i] ) ) {
469 /** @var $serverConns IDatabase[] */
470 $serverConns = $connsByServer[$i];
472 return reset( $serverConns );
480 * Wait for a given replica DB to catch up to the master pos stored in $this
481 * @param int $index Server index
482 * @param bool $open Check the server even if a new connection has to be made
483 * @param int $timeout Max seconds to wait; default is mWaitTimeout
486 protected function doWait( $index, $open = false, $timeout = null ) {
487 $close = false; // close the connection afterwards
489 // Check if we already know that the DB has reached this point
490 $server = $this->getServerName( $index );
491 $key = $this->srvCache
->makeGlobalKey( __CLASS__
, 'last-known-pos', $server );
492 /** @var DBMasterPos $knownReachedPos */
493 $knownReachedPos = $this->srvCache
->get( $key );
494 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos
) ) {
495 $this->replLogger
->debug( __METHOD__
.
496 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
500 // Find a connection to wait on, creating one if needed and allowed
501 $conn = $this->getAnyOpenConnection( $index );
504 $this->replLogger
->debug( __METHOD__
. ": no connection open for $server" );
508 $conn = $this->openConnection( $index, self
::DOMAIN_ANY
);
510 $this->replLogger
->warning( __METHOD__
. ": failed to connect to $server" );
514 // Avoid connection spam in waitForAll() when connections
515 // are made just for the sake of doing this lag check.
520 $this->replLogger
->info( __METHOD__
. ": Waiting for replica DB $server to catch up..." );
521 $timeout = $timeout ?
: $this->mWaitTimeout
;
522 $result = $conn->masterPosWait( $this->mWaitForPos
, $timeout );
524 if ( $result == -1 ||
is_null( $result ) ) {
525 // Timed out waiting for replica DB, use master instead
526 $this->replLogger
->warning(
527 __METHOD__
. ": Timed out waiting on {host} pos {$this->mWaitForPos}",
528 [ 'host' => $server ]
532 $this->replLogger
->info( __METHOD__
. ": Done" );
534 // Remember that the DB reached this point
535 $this->srvCache
->set( $key, $this->mWaitForPos
, BagOStuff
::TTL_DAY
);
539 $this->closeConnection( $conn );
546 * @see ILoadBalancer::getConnection()
549 * @param array $groups
550 * @param bool $domain
552 * @throws DBConnectionError
554 public function getConnection( $i, $groups = [], $domain = false ) {
555 if ( $i === null ||
$i === false ) {
556 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__
.
557 ' with invalid server index' );
560 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
561 $domain = false; // local connection requested
564 $groups = ( $groups === false ||
$groups === [] )
565 ?
[ false ] // check one "group": the generic pool
568 $masterOnly = ( $i == self
::DB_MASTER ||
$i == $this->getWriterIndex() );
569 $oldConnsOpened = $this->connsOpened
; // connections open now
571 if ( $i == self
::DB_MASTER
) {
572 $i = $this->getWriterIndex();
574 # Try to find an available server in any the query groups (in order)
575 foreach ( $groups as $group ) {
576 $groupIndex = $this->getReaderIndex( $group, $domain );
577 if ( $groupIndex !== false ) {
584 # Operation-based index
585 if ( $i == self
::DB_REPLICA
) {
586 $this->mLastError
= 'Unknown error'; // reset error string
587 # Try the general server pool if $groups are unavailable.
588 $i = ( $groups === [ false ] )
589 ?
false // don't bother with this if that is what was tried above
590 : $this->getReaderIndex( false, $domain );
591 # Couldn't find a working server in getReaderIndex()?
592 if ( $i === false ) {
593 $this->mLastError
= 'No working replica DB server: ' . $this->mLastError
;
594 // Throw an exception
595 $this->reportConnectionError();
596 return null; // not reached
600 # Now we have an explicit index into the servers array
601 $conn = $this->openConnection( $i, $domain );
603 // Throw an exception
604 $this->reportConnectionError();
605 return null; // not reached
608 # Profile any new connections that happen
609 if ( $this->connsOpened
> $oldConnsOpened ) {
610 $host = $conn->getServer();
611 $dbname = $conn->getDBname();
612 $this->trxProfiler
->recordConnection( $host, $dbname, $masterOnly );
616 # Make master-requested DB handles inherit any read-only mode setting
617 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
623 public function reuseConnection( $conn ) {
624 $serverIndex = $conn->getLBInfo( 'serverIndex' );
625 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
626 if ( $serverIndex === null ||
$refCount === null ) {
628 * This can happen in code like:
629 * foreach ( $dbs as $db ) {
630 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
632 * $lb->reuseConnection( $conn );
634 * When a connection to the local DB is opened in this way, reuseConnection()
638 } elseif ( $conn instanceof DBConnRef
) {
639 // DBConnRef already handles calling reuseConnection() and only passes the live
640 // Database instance to this method. Any caller passing in a DBConnRef is broken.
641 $this->connLogger
->error( __METHOD__
. ": got DBConnRef instance.\n" .
642 ( new RuntimeException() )->getTraceAsString() );
647 if ( $this->disabled
) {
648 return; // DBConnRef handle probably survived longer than the LoadBalancer
651 $domain = $conn->getDomainID();
652 if ( !isset( $this->mConns
['foreignUsed'][$serverIndex][$domain] ) ) {
653 throw new InvalidArgumentException( __METHOD__
.
654 ": connection $serverIndex/$domain not found; it may have already been freed." );
655 } elseif ( $this->mConns
['foreignUsed'][$serverIndex][$domain] !== $conn ) {
656 throw new InvalidArgumentException( __METHOD__
.
657 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
659 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
660 if ( $refCount <= 0 ) {
661 $this->mConns
['foreignFree'][$serverIndex][$domain] = $conn;
662 unset( $this->mConns
['foreignUsed'][$serverIndex][$domain] );
663 if ( !$this->mConns
['foreignUsed'][$serverIndex] ) {
664 unset( $this->mConns
[ 'foreignUsed' ][$serverIndex] ); // clean up
666 $this->connLogger
->debug( __METHOD__
. ": freed connection $serverIndex/$domain" );
668 $this->connLogger
->debug( __METHOD__
.
669 ": reference count for $serverIndex/$domain reduced to $refCount" );
673 public function getConnectionRef( $db, $groups = [], $domain = false ) {
674 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
676 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
679 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
680 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
682 return new DBConnRef( $this, [ $db, $groups, $domain ] );
685 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
686 $domain = ( $domain !== false ) ?
$domain : $this->localDomain
;
688 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
692 * @see ILoadBalancer::openConnection()
695 * @param bool $domain
696 * @return bool|Database
697 * @throws DBAccessError
699 public function openConnection( $i, $domain = false ) {
700 if ( $this->localDomain
->equals( $domain ) ||
$domain === $this->localDomainIdAlias
) {
701 $domain = false; // local connection requested
704 if ( $domain !== false ) {
705 $conn = $this->openForeignConnection( $i, $domain );
706 } elseif ( isset( $this->mConns
['local'][$i][0] ) ) {
707 $conn = $this->mConns
['local'][$i][0];
709 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
710 throw new InvalidArgumentException( "No server with index '$i'." );
712 // Open a new connection
713 $server = $this->mServers
[$i];
714 $server['serverIndex'] = $i;
715 $conn = $this->reallyOpenConnection( $server, false );
716 $serverName = $this->getServerName( $i );
717 if ( $conn->isOpen() ) {
718 $this->connLogger
->debug( "Connected to database $i at '$serverName'." );
719 $this->mConns
['local'][$i][0] = $conn;
721 $this->connLogger
->warning( "Failed to connect to database $i at '$serverName'." );
722 $this->mErrorConnection
= $conn;
727 if ( $conn && !$conn->isOpen() ) {
728 // Connection was made but later unrecoverably lost for some reason.
729 // Do not return a handle that will just throw exceptions on use,
730 // but let the calling code (e.g. getReaderIndex) try another server.
731 // See DatabaseMyslBase::ping() for how this can happen.
732 $this->mErrorConnection
= $conn;
740 * Open a connection to a foreign DB, or return one if it is already open.
742 * Increments a reference count on the returned connection which locks the
743 * connection to the requested domain. This reference count can be
744 * decremented by calling reuseConnection().
746 * If a connection is open to the appropriate server already, but with the wrong
747 * database, it will be switched to the right database and returned, as long as
748 * it has been freed first with reuseConnection().
750 * On error, returns false, and the connection which caused the
751 * error will be available via $this->mErrorConnection.
753 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
755 * @param int $i Server index
756 * @param string $domain Domain ID to open
759 private function openForeignConnection( $i, $domain ) {
760 $domainInstance = DatabaseDomain
::newFromId( $domain );
761 $dbName = $domainInstance->getDatabase();
762 $prefix = $domainInstance->getTablePrefix();
764 if ( isset( $this->mConns
['foreignUsed'][$i][$domain] ) ) {
765 // Reuse an already-used connection
766 $conn = $this->mConns
['foreignUsed'][$i][$domain];
767 $this->connLogger
->debug( __METHOD__
. ": reusing connection $i/$domain" );
768 } elseif ( isset( $this->mConns
['foreignFree'][$i][$domain] ) ) {
769 // Reuse a free connection for the same domain
770 $conn = $this->mConns
['foreignFree'][$i][$domain];
771 unset( $this->mConns
['foreignFree'][$i][$domain] );
772 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
773 $this->connLogger
->debug( __METHOD__
. ": reusing free connection $i/$domain" );
774 } elseif ( !empty( $this->mConns
['foreignFree'][$i] ) ) {
775 // Reuse a connection from another domain
776 $conn = reset( $this->mConns
['foreignFree'][$i] );
777 $oldDomain = key( $this->mConns
['foreignFree'][$i] );
778 // The empty string as a DB name means "don't care".
779 // DatabaseMysqlBase::open() already handle this on connection.
780 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
781 $this->mLastError
= "Error selecting database '$dbName' on server " .
782 $conn->getServer() . " from client host {$this->host}";
783 $this->mErrorConnection
= $conn;
786 $conn->tablePrefix( $prefix );
787 unset( $this->mConns
['foreignFree'][$i][$oldDomain] );
788 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
789 $this->connLogger
->debug( __METHOD__
.
790 ": reusing free connection from $oldDomain for $domain" );
793 if ( !isset( $this->mServers
[$i] ) ||
!is_array( $this->mServers
[$i] ) ) {
794 throw new InvalidArgumentException( "No server with index '$i'." );
796 // Open a new connection
797 $server = $this->mServers
[$i];
798 $server['serverIndex'] = $i;
799 $server['foreignPoolRefCount'] = 0;
800 $server['foreign'] = true;
801 $conn = $this->reallyOpenConnection( $server, $dbName );
802 if ( !$conn->isOpen() ) {
803 $this->connLogger
->warning( __METHOD__
. ": connection error for $i/$domain" );
804 $this->mErrorConnection
= $conn;
807 $conn->tablePrefix( $prefix );
808 $this->mConns
['foreignUsed'][$i][$domain] = $conn;
809 $this->connLogger
->debug( __METHOD__
. ": opened new connection for $i/$domain" );
813 // Increment reference count
815 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
816 $conn->setLBInfo( 'foreignPoolRefCount', $refCount +
1 );
823 * Test if the specified index represents an open connection
825 * @param int $index Server index
829 private function isOpen( $index ) {
830 if ( !is_integer( $index ) ) {
834 return (bool)$this->getAnyOpenConnection( $index );
838 * Really opens a connection. Uncached.
839 * Returns a Database object whether or not the connection was successful.
842 * @param array $server
843 * @param string|bool $dbNameOverride Use "" to not select any database
845 * @throws DBAccessError
846 * @throws InvalidArgumentException
848 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
849 if ( $this->disabled
) {
850 throw new DBAccessError();
853 if ( $dbNameOverride !== false ) {
854 $server['dbname'] = $dbNameOverride;
857 // Let the handle know what the cluster master is (e.g. "db1052")
858 $masterName = $this->getServerName( $this->getWriterIndex() );
859 $server['clusterMasterHost'] = $masterName;
861 // Log when many connection are made on requests
862 if ( ++
$this->connsOpened
>= self
::CONN_HELD_WARN_THRESHOLD
) {
863 $this->perfLogger
->warning( __METHOD__
. ": " .
864 "{$this->connsOpened}+ connections made (master=$masterName)" );
867 $server['srvCache'] = $this->srvCache
;
868 // Set loggers and profilers
869 $server['connLogger'] = $this->connLogger
;
870 $server['queryLogger'] = $this->queryLogger
;
871 $server['errorLogger'] = $this->errorLogger
;
872 $server['profiler'] = $this->profiler
;
873 $server['trxProfiler'] = $this->trxProfiler
;
874 // Use the same agent and PHP mode for all DB handles
875 $server['cliMode'] = $this->cliMode
;
876 $server['agent'] = $this->agent
;
877 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
878 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
879 $server['flags'] = isset( $server['flags'] ) ?
$server['flags'] : IDatabase
::DBO_DEFAULT
;
881 // Create a live connection object
883 $db = Database
::factory( $server['type'], $server );
884 } catch ( DBConnectionError
$e ) {
885 // FIXME: This is probably the ugliest thing I have ever done to
886 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
890 $db->setLBInfo( $server );
891 $db->setLazyMasterHandle(
892 $this->getLazyConnectionRef( self
::DB_MASTER
, [], $db->getDomainID() )
894 $db->setTableAliases( $this->tableAliases
);
896 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
897 if ( $this->trxRoundId
!== false ) {
898 $this->applyTransactionRoundFlags( $db );
900 foreach ( $this->trxRecurringCallbacks
as $name => $callback ) {
901 $db->setTransactionListener( $name, $callback );
909 * @throws DBConnectionError
911 private function reportConnectionError() {
912 $conn = $this->mErrorConnection
; // the connection which caused the error
914 'method' => __METHOD__
,
915 'last_error' => $this->mLastError
,
918 if ( !is_object( $conn ) ) {
919 // No last connection, probably due to all servers being too busy
920 $this->connLogger
->error(
921 "LB failure with no last connection. Connection error: {last_error}",
925 // If all servers were busy, mLastError will contain something sensible
926 throw new DBConnectionError( null, $this->mLastError
);
928 $context['db_server'] = $conn->getServer();
929 $this->connLogger
->warning(
930 "Connection error: {last_error} ({db_server})",
934 // throws DBConnectionError
935 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
939 public function getWriterIndex() {
943 public function haveIndex( $i ) {
944 return array_key_exists( $i, $this->mServers
);
947 public function isNonZeroLoad( $i ) {
948 return array_key_exists( $i, $this->mServers
) && $this->mLoads
[$i] != 0;
951 public function getServerCount() {
952 return count( $this->mServers
);
955 public function getServerName( $i ) {
956 if ( isset( $this->mServers
[$i]['hostName'] ) ) {
957 $name = $this->mServers
[$i]['hostName'];
958 } elseif ( isset( $this->mServers
[$i]['host'] ) ) {
959 $name = $this->mServers
[$i]['host'];
964 return ( $name != '' ) ?
$name : 'localhost';
967 public function getServerInfo( $i ) {
968 if ( isset( $this->mServers
[$i] ) ) {
969 return $this->mServers
[$i];
975 public function setServerInfo( $i, array $serverInfo ) {
976 $this->mServers
[$i] = $serverInfo;
979 public function getMasterPos() {
980 # If this entire request was served from a replica DB without opening a connection to the
981 # master (however unlikely that may be), then we can fetch the position from the replica DB.
982 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
983 if ( !$masterConn ) {
984 $serverCount = count( $this->mServers
);
985 for ( $i = 1; $i < $serverCount; $i++
) {
986 $conn = $this->getAnyOpenConnection( $i );
988 return $conn->getReplicaPos();
992 return $masterConn->getMasterPos();
998 public function disable() {
1000 $this->disabled
= true;
1003 public function closeAll() {
1004 $this->forEachOpenConnection( function ( IDatabase
$conn ) {
1005 $host = $conn->getServer();
1006 $this->connLogger
->debug( "Closing connection to database '$host'." );
1012 'foreignFree' => [],
1013 'foreignUsed' => [],
1015 $this->connsOpened
= 0;
1018 public function closeConnection( IDatabase
$conn ) {
1019 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1020 foreach ( $this->mConns
as $type => $connsByServer ) {
1021 if ( !isset( $connsByServer[$serverIndex] ) ) {
1025 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1026 if ( $conn === $trackedConn ) {
1027 $host = $this->getServerName( $i );
1028 $this->connLogger
->debug( "Closing connection to database $i at '$host'." );
1029 unset( $this->mConns
[$type][$serverIndex][$i] );
1030 --$this->connsOpened
;
1039 public function commitAll( $fname = __METHOD__
) {
1042 $restore = ( $this->trxRoundId
!== false );
1043 $this->trxRoundId
= false;
1044 $this->forEachOpenConnection(
1045 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1047 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1048 } catch ( DBError
$e ) {
1049 call_user_func( $this->errorLogger
, $e );
1050 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1052 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1053 $this->undoTransactionRoundFlags( $conn );
1059 throw new DBExpectedError(
1061 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1066 public function finalizeMasterChanges() {
1067 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1068 // Any error should cause all DB transactions to be rolled back together
1069 $conn->setTrxEndCallbackSuppression( false );
1070 $conn->runOnTransactionPreCommitCallbacks();
1071 // Defer post-commit callbacks until COMMIT finishes for all DBs
1072 $conn->setTrxEndCallbackSuppression( true );
1076 public function approveMasterChanges( array $options ) {
1077 $limit = isset( $options['maxWriteDuration'] ) ?
$options['maxWriteDuration'] : 0;
1078 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( $limit ) {
1079 // If atomic sections or explicit transactions are still open, some caller must have
1080 // caught an exception but failed to properly rollback any changes. Detect that and
1081 // throw and error (causing rollback).
1082 if ( $conn->explicitTrxActive() ) {
1083 throw new DBTransactionError(
1085 "Explicit transaction still active. A caller may have caught an error."
1088 // Assert that the time to replicate the transaction will be sane.
1089 // If this fails, then all DB transactions will be rollback back together.
1090 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY
);
1091 if ( $limit > 0 && $time > $limit ) {
1092 throw new DBTransactionSizeError(
1094 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1098 // If a connection sits idle while slow queries execute on another, that connection
1099 // may end up dropped before the commit round is reached. Ping servers to detect this.
1100 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1101 throw new DBTransactionError(
1103 "A connection to the {$conn->getDBname()} database was lost before commit."
1109 public function beginMasterChanges( $fname = __METHOD__
) {
1110 if ( $this->trxRoundId
!== false ) {
1111 throw new DBTransactionError(
1113 "$fname: Transaction round '{$this->trxRoundId}' already started."
1116 $this->trxRoundId
= $fname;
1119 $this->forEachOpenMasterConnection(
1120 function ( Database
$conn ) use ( $fname, &$failures ) {
1121 $conn->setTrxEndCallbackSuppression( true );
1123 $conn->flushSnapshot( $fname );
1124 } catch ( DBError
$e ) {
1125 call_user_func( $this->errorLogger
, $e );
1126 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1128 $conn->setTrxEndCallbackSuppression( false );
1129 $this->applyTransactionRoundFlags( $conn );
1134 throw new DBExpectedError(
1136 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1141 public function commitMasterChanges( $fname = __METHOD__
) {
1144 /** @noinspection PhpUnusedLocalVariableInspection */
1145 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1147 $restore = ( $this->trxRoundId
!== false );
1148 $this->trxRoundId
= false;
1149 $this->forEachOpenMasterConnection(
1150 function ( IDatabase
$conn ) use ( $fname, $restore, &$failures ) {
1152 if ( $conn->writesOrCallbacksPending() ) {
1153 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS
);
1154 } elseif ( $restore ) {
1155 $conn->flushSnapshot( $fname );
1157 } catch ( DBError
$e ) {
1158 call_user_func( $this->errorLogger
, $e );
1159 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1162 $this->undoTransactionRoundFlags( $conn );
1168 throw new DBExpectedError(
1170 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1175 public function runMasterPostTrxCallbacks( $type ) {
1176 $e = null; // first exception
1177 $this->forEachOpenMasterConnection( function ( Database
$conn ) use ( $type, &$e ) {
1178 $conn->setTrxEndCallbackSuppression( false );
1179 if ( $conn->writesOrCallbacksPending() ) {
1180 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1181 // (which finished its callbacks already). Warn and recover in this case. Let the
1182 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1183 $this->queryLogger
->error( __METHOD__
. ": found writes/callbacks pending." );
1185 } elseif ( $conn->trxLevel() ) {
1186 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1187 // thus leaving an implicit read-only transaction open at this point. It
1188 // also happens if onTransactionIdle() callbacks leave implicit transactions
1189 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1190 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1194 $conn->runOnTransactionIdleCallbacks( $type );
1195 } catch ( Exception
$ex ) {
1199 $conn->runTransactionListenerCallbacks( $type );
1200 } catch ( Exception
$ex ) {
1208 public function rollbackMasterChanges( $fname = __METHOD__
) {
1209 $restore = ( $this->trxRoundId
!== false );
1210 $this->trxRoundId
= false;
1211 $this->forEachOpenMasterConnection(
1212 function ( IDatabase
$conn ) use ( $fname, $restore ) {
1213 if ( $conn->writesOrCallbacksPending() ) {
1214 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS
);
1217 $this->undoTransactionRoundFlags( $conn );
1223 public function suppressTransactionEndCallbacks() {
1224 $this->forEachOpenMasterConnection( function ( Database
$conn ) {
1225 $conn->setTrxEndCallbackSuppression( true );
1230 * @param IDatabase $conn
1232 private function applyTransactionRoundFlags( IDatabase
$conn ) {
1233 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1234 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1235 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1236 $conn->setFlag( $conn::DBO_TRX
, $conn::REMEMBER_PRIOR
);
1237 // If config has explicitly requested DBO_TRX be either on or off by not
1238 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1239 // for things like blob stores (ExternalStore) which want auto-commit mode.
1244 * @param IDatabase $conn
1246 private function undoTransactionRoundFlags( IDatabase
$conn ) {
1247 if ( $conn->getFlag( $conn::DBO_DEFAULT
) ) {
1248 $conn->restoreFlags( $conn::RESTORE_PRIOR
);
1252 public function flushReplicaSnapshots( $fname = __METHOD__
) {
1253 $this->forEachOpenReplicaConnection( function ( IDatabase
$conn ) {
1254 $conn->flushSnapshot( __METHOD__
);
1258 public function hasMasterConnection() {
1259 return $this->isOpen( $this->getWriterIndex() );
1262 public function hasMasterChanges() {
1264 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$pending ) {
1265 $pending |
= $conn->writesOrCallbacksPending();
1268 return (bool)$pending;
1271 public function lastMasterChangeTimestamp() {
1273 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$lastTime ) {
1274 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1280 public function hasOrMadeRecentMasterChanges( $age = null ) {
1281 $age = ( $age === null ) ?
$this->mWaitTimeout
: $age;
1283 return ( $this->hasMasterChanges()
1284 ||
$this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1287 public function pendingMasterChangeCallers() {
1289 $this->forEachOpenMasterConnection( function ( IDatabase
$conn ) use ( &$fnames ) {
1290 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1296 public function getLaggedReplicaMode( $domain = false ) {
1297 // No-op if there is only one DB (also avoids recursion)
1298 if ( !$this->laggedReplicaMode
&& $this->getServerCount() > 1 ) {
1300 // See if laggedReplicaMode gets set
1301 $conn = $this->getConnection( self
::DB_REPLICA
, false, $domain );
1302 $this->reuseConnection( $conn );
1303 } catch ( DBConnectionError
$e ) {
1304 // Avoid expensive re-connect attempts and failures
1305 $this->allReplicasDownMode
= true;
1306 $this->laggedReplicaMode
= true;
1310 return $this->laggedReplicaMode
;
1314 * @param bool $domain
1316 * @deprecated 1.28; use getLaggedReplicaMode()
1318 public function getLaggedSlaveMode( $domain = false ) {
1319 return $this->getLaggedReplicaMode( $domain );
1322 public function laggedReplicaUsed() {
1323 return $this->laggedReplicaMode
;
1329 * @deprecated Since 1.28; use laggedReplicaUsed()
1331 public function laggedSlaveUsed() {
1332 return $this->laggedReplicaUsed();
1335 public function getReadOnlyReason( $domain = false, IDatabase
$conn = null ) {
1336 if ( $this->readOnlyReason
!== false ) {
1337 return $this->readOnlyReason
;
1338 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1339 if ( $this->allReplicasDownMode
) {
1340 return 'The database has been automatically locked ' .
1341 'until the replica database servers become available';
1343 return 'The database has been automatically locked ' .
1344 'while the replica database servers catch up to the master.';
1346 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1347 return 'The database master is running in read-only mode.';
1354 * @param string $domain Domain ID, or false for the current domain
1355 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1358 private function masterRunningReadOnly( $domain, IDatabase
$conn = null ) {
1359 $cache = $this->wanCache
;
1360 $masterServer = $this->getServerName( $this->getWriterIndex() );
1362 return (bool)$cache->getWithSetCallback(
1363 $cache->makeGlobalKey( __CLASS__
, 'server-read-only', $masterServer ),
1364 self
::TTL_CACHE_READONLY
,
1365 function () use ( $domain, $conn ) {
1366 $old = $this->trxProfiler
->setSilenced( true );
1368 $dbw = $conn ?
: $this->getConnection( self
::DB_MASTER
, [], $domain );
1369 $readOnly = (int)$dbw->serverIsReadOnly();
1371 $this->reuseConnection( $dbw );
1373 } catch ( DBError
$e ) {
1376 $this->trxProfiler
->setSilenced( $old );
1379 [ 'pcTTL' => $cache::TTL_PROC_LONG
, 'busyValue' => 0 ]
1383 public function allowLagged( $mode = null ) {
1384 if ( $mode === null ) {
1385 return $this->mAllowLagged
;
1387 $this->mAllowLagged
= $mode;
1389 return $this->mAllowLagged
;
1392 public function pingAll() {
1394 $this->forEachOpenConnection( function ( IDatabase
$conn ) use ( &$success ) {
1395 if ( !$conn->ping() ) {
1403 public function forEachOpenConnection( $callback, array $params = [] ) {
1404 foreach ( $this->mConns
as $connsByServer ) {
1405 foreach ( $connsByServer as $serverConns ) {
1406 foreach ( $serverConns as $conn ) {
1407 $mergedParams = array_merge( [ $conn ], $params );
1408 call_user_func_array( $callback, $mergedParams );
1414 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1415 $masterIndex = $this->getWriterIndex();
1416 foreach ( $this->mConns
as $connsByServer ) {
1417 if ( isset( $connsByServer[$masterIndex] ) ) {
1418 /** @var IDatabase $conn */
1419 foreach ( $connsByServer[$masterIndex] as $conn ) {
1420 $mergedParams = array_merge( [ $conn ], $params );
1421 call_user_func_array( $callback, $mergedParams );
1427 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1428 foreach ( $this->mConns
as $connsByServer ) {
1429 foreach ( $connsByServer as $i => $serverConns ) {
1430 if ( $i === $this->getWriterIndex() ) {
1431 continue; // skip master
1433 foreach ( $serverConns as $conn ) {
1434 $mergedParams = array_merge( [ $conn ], $params );
1435 call_user_func_array( $callback, $mergedParams );
1441 public function getMaxLag( $domain = false ) {
1446 if ( $this->getServerCount() <= 1 ) {
1447 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1450 $lagTimes = $this->getLagTimes( $domain );
1451 foreach ( $lagTimes as $i => $lag ) {
1452 if ( $this->mLoads
[$i] > 0 && $lag > $maxLag ) {
1454 $host = $this->mServers
[$i]['host'];
1459 return [ $host, $maxLag, $maxIndex ];
1462 public function getLagTimes( $domain = false ) {
1463 if ( $this->getServerCount() <= 1 ) {
1464 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1467 $knownLagTimes = []; // map of (server index => 0 seconds)
1468 $indexesWithLag = [];
1469 foreach ( $this->mServers
as $i => $server ) {
1470 if ( empty( $server['is static'] ) ) {
1471 $indexesWithLag[] = $i; // DB server might have replication lag
1473 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1477 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) +
$knownLagTimes;
1480 public function safeGetLag( IDatabase
$conn ) {
1481 if ( $this->getServerCount() <= 1 ) {
1484 return $conn->getLag();
1489 * @param IDatabase $conn
1490 * @param DBMasterPos|bool $pos
1491 * @param int $timeout
1494 public function safeWaitForMasterPos( IDatabase
$conn, $pos = false, $timeout = 10 ) {
1495 if ( $this->getServerCount() <= 1 ||
!$conn->getLBInfo( 'replica' ) ) {
1496 return true; // server is not a replica DB
1500 // Get the current master position, opening a connection if needed
1501 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1502 if ( $masterConn ) {
1503 $pos = $masterConn->getMasterPos();
1505 $masterConn = $this->openConnection( $this->getWriterIndex(), self
::DOMAIN_ANY
);
1506 $pos = $masterConn->getMasterPos();
1507 $this->closeConnection( $masterConn );
1511 if ( $pos instanceof DBMasterPos
) {
1512 $result = $conn->masterPosWait( $pos, $timeout );
1513 if ( $result == -1 ||
is_null( $result ) ) {
1514 $msg = __METHOD__
. ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1515 $this->replLogger
->warning( "$msg" );
1518 $this->replLogger
->info( __METHOD__
. ": Done" );
1522 $ok = false; // something is misconfigured
1523 $this->replLogger
->error( "Could not get master pos for {$conn->getServer()}." );
1529 public function setTransactionListener( $name, callable
$callback = null ) {
1531 $this->trxRecurringCallbacks
[$name] = $callback;
1533 unset( $this->trxRecurringCallbacks
[$name] );
1535 $this->forEachOpenMasterConnection(
1536 function ( IDatabase
$conn ) use ( $name, $callback ) {
1537 $conn->setTransactionListener( $name, $callback );
1542 public function setTableAliases( array $aliases ) {
1543 $this->tableAliases
= $aliases;
1546 public function setDomainPrefix( $prefix ) {
1547 if ( $this->mConns
['foreignUsed'] ) {
1548 // Do not switch connections to explicit foreign domains unless marked as free
1550 foreach ( $this->mConns
['foreignUsed'] as $i => $connsByDomain ) {
1551 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1553 $domains = implode( ', ', $domains );
1554 throw new DBUnexpectedError( null,
1555 "Foreign domain connections are still in use ($domains)." );
1558 $this->localDomain
= new DatabaseDomain(
1559 $this->localDomain
->getDatabase(),
1564 $this->forEachOpenConnection( function ( IDatabase
$db ) use ( $prefix ) {
1565 $db->tablePrefix( $prefix );
1570 * Make PHP ignore user aborts/disconnects until the returned
1571 * value leaves scope. This returns null and does nothing in CLI mode.
1573 * @return ScopedCallback|null
1575 final protected function getScopedPHPBehaviorForCommit() {
1576 if ( PHP_SAPI
!= 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1577 $old = ignore_user_abort( true ); // avoid half-finished operations
1578 return new ScopedCallback( function () use ( $old ) {
1579 ignore_user_abort( $old );
1586 function __destruct() {
1587 // Avoid connection leaks for sanity