24use Psr\Log\LoggerInterface;
25use Psr\Log\NullLogger;
26use Wikimedia\ScopedCallback;
32use UnexpectedValueException;
33use InvalidArgumentException;
138 const CONN_HELD_WARN_THRESHOLD = 10;
141 const MAX_LAG_DEFAULT = 6;
143 const MAX_WAIT_DEFAULT = 10;
145 const TTL_CACHE_READONLY = 5;
156 const ROUND_CURSORY =
'cursory';
158 const ROUND_FINALIZED =
'finalized';
160 const ROUND_APPROVED =
'approved';
162 const ROUND_COMMIT_CALLBACKS =
'commit-callbacks';
164 const ROUND_ROLLBACK_CALLBACKS =
'rollback-callbacks';
166 const ROUND_ERROR =
'error';
169 if ( !isset( $params[
'servers'] ) || !count( $params[
'servers'] ) ) {
170 throw new InvalidArgumentException(
'Missing or empty "servers" parameter' );
175 $this->groupLoads = [ self::GROUP_GENERIC => [] ];
176 foreach ( $params[
'servers'] as $i => $server ) {
177 if ( ++$listKey !== $i ) {
178 throw new UnexpectedValueException(
'List expected for "servers" parameter' );
181 $server[
'master'] =
true;
183 $server[
'replica'] =
true;
185 $this->servers[$i] = $server;
186 foreach ( ( $server[
'groupLoads'] ?? [] ) as $group => $ratio ) {
187 $this->groupLoads[$group][$i] = $ratio;
189 $this->groupLoads[self::GROUP_GENERIC][$i] = $server[
'load'];
197 $this->waitTimeout = $params[
'waitTimeout'] ?? self::MAX_WAIT_DEFAULT;
200 $this->waitForPos =
false;
203 if ( isset( $params[
'readOnlyReason'] ) && is_string( $params[
'readOnlyReason'] ) ) {
204 $this->readOnlyReason = $params[
'readOnlyReason'];
207 $this->maxLag = $params[
'maxLag'] ?? self::MAX_LAG_DEFAULT;
209 $this->loadMonitorConfig = $params[
'loadMonitor'] ?? [
'class' =>
'LoadMonitorNull' ];
210 $this->loadMonitorConfig += [
'lagWarnThreshold' =>
$this->maxLag ];
213 $this->wanCache = $params[
'wanCache'] ?? WANObjectCache::newEmpty();
214 $this->profiler = $params[
'profiler'] ??
null;
217 $this->errorLogger = $params[
'errorLogger'] ??
function ( Exception $e ) {
218 trigger_error( get_class( $e ) .
': ' . $e->getMessage(), E_USER_WARNING );
220 $this->deprecationLogger = $params[
'deprecationLogger'] ??
function ( $msg ) {
221 trigger_error( $msg, E_USER_DEPRECATED );
223 foreach ( [
'replLogger',
'connLogger',
'queryLogger',
'perfLogger' ] as $key ) {
224 $this->$key = $params[$key] ??
new NullLogger();
227 $this->hostname = $params[
'hostname'] ?? ( gethostname() ?:
'unknown' );
228 $this->cliMode = $params[
'cliMode'] ?? ( PHP_SAPI ===
'cli' || PHP_SAPI ===
'phpdbg' );
229 $this->agent = $params[
'agent'] ??
'';
231 if ( isset( $params[
'chronologyCallback'] ) ) {
232 $this->chronologyCallback = $params[
'chronologyCallback'];
235 if ( isset( $params[
'roundStage'] ) ) {
236 if ( $params[
'roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) {
237 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
238 } elseif ( $params[
'roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) {
239 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
243 $group = $params[
'defaultGroup'] ?? self::GROUP_GENERIC;
244 $this->defaultGroup = isset( $this->groupLoads[$group] ) ? $group : self::GROUP_GENERIC;
247 $this->
id = $nextId = ( is_int( $nextId ) ? $nextId++ : mt_rand() );
248 $this->ownerId = $params[
'ownerId'] ??
null;
254 self::KEY_LOCAL => [],
255 self::KEY_FOREIGN_INUSE => [],
256 self::KEY_FOREIGN_FREE => [],
258 self::KEY_LOCAL_NOROUND => [],
259 self::KEY_FOREIGN_INUSE_NOROUND => [],
260 self::KEY_FOREIGN_FREE_NOROUND => []
265 return $this->localDomain->getId();
269 if ( $domain === $this->localDomainIdAlias || $domain ===
false ) {
274 return (
string)$domain;
286 if ( $i > 0 && $groups !== [] && $groups !==
false ) {
287 $list = implode(
', ', (array)$groups );
288 throw new LogicException(
"Query group(s) ($list) given with server index (#$i)" );
291 if ( $groups === [] || $groups ===
false || $groups === $this->defaultGroup ) {
293 } elseif ( is_string( $groups ) && isset( $this->groupLoads[$groups] ) ) {
295 } elseif ( is_array( $groups ) ) {
296 $resolvedGroups = array_keys( array_flip( $groups ) + [ self::GROUP_GENERIC => 1 ] );
301 return $resolvedGroups;
313 $flags |= self::CONN_INTENT_WRITABLE;
316 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
323 if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) {
328 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
330 $this->connLogger->info( __METHOD__ .
": CONN_TRX_AUTOCOMMIT disallowed ($type)" );
331 } elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) {
336 $flags &= ~self::CONN_TRX_AUTOCOMMIT;
349 if ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT ) {
353 'Handle requested with CONN_TRX_AUTOCOMMIT yet it has a transaction'
367 if ( !isset( $this->loadMonitor ) ) {
369 'LoadMonitor' => LoadMonitor::class,
370 'LoadMonitorNull' => LoadMonitorNull::class,
371 'LoadMonitorMySQL' => LoadMonitorMySQL::class,
374 $class = $this->loadMonitorConfig[
'class'];
375 if ( isset( $compat[$class] ) ) {
376 $class = $compat[$class];
379 $this->loadMonitor =
new $class(
380 $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
381 $this->loadMonitor->setLogger( $this->replLogger );
396 # Unset excessively lagged servers
397 foreach ( $lags as $i => $lag ) {
399 # How much lag this server nominally is allowed to have
400 $maxServerLag = $this->servers[$i][
'max lag'] ??
$this->maxLag;
401 # Constrain that futher by $maxLag argument
402 $maxServerLag = min( $maxServerLag,
$maxLag );
405 if ( $lag ===
false && !is_infinite( $maxServerLag ) ) {
406 $this->replLogger->debug(
408 ": server {host} is not replicating?", [
'host' => $host ] );
410 } elseif ( $lag > $maxServerLag ) {
411 $this->replLogger->debug(
413 ": server {host} has {lag} seconds of lag (>= {maxlag})",
414 [
'host' => $host,
'lag' => $lag,
'maxlag' => $maxServerLag ]
421 # Find out if all the replica DBs with non-zero load are lagged
423 foreach ( $loads as $load ) {
427 # No appropriate DB servers except maybe the master and some replica DBs with zero load
428 # Do NOT use the master
429 # Instead, this function will return false, triggering read-only mode,
430 # and a lagged replica DB will be used instead.
434 if ( count( $loads ) == 0 ) {
438 # Return a random representative of the remainder
451 if ( $i === self::DB_MASTER ) {
453 } elseif ( $i === self::DB_REPLICA ) {
454 foreach ( $groups as $group ) {
456 if ( $groupIndex !==
false ) {
461 } elseif ( !isset( $this->servers[$i] ) ) {
462 throw new UnexpectedValueException(
"Invalid server index index #$i" );
465 if ( $i === self::DB_REPLICA ) {
466 $this->lastError =
'Unknown error';
481 $group = is_string( $group ) ? $group : self::GROUP_GENERIC;
490 if ( isset( $this->groupLoads[$group] ) ) {
491 $loads = $this->groupLoads[$group];
493 $this->connLogger->info( __METHOD__ .
": no loads for group $group" );
504 if ( $i ===
false ) {
520 $this->laggedReplicaMode =
true;
524 $this->connLogger->debug( __METHOD__ .
": using server $serverName for group '$group'" );
536 return $this->readIndexByGroup[$group] ?? -1;
547 throw new UnexpectedValueException(
"Cannot set a negative read server index" );
549 $this->readIndexByGroup[$group] = $index;
558 if ( $loads === [] ) {
559 throw new InvalidArgumentException(
"Server configuration array is empty" );
568 $currentLoads = $loads;
569 while ( count( $currentLoads ) ) {
574 if ( $this->waitForPos && $this->waitForPos->asOfTime() ) {
575 $this->replLogger->debug( __METHOD__ .
": replication positions detected" );
579 $ago = microtime(
true ) - $this->waitForPos->asOfTime();
583 if ( $i ===
false ) {
587 if ( $i ===
false && count( $currentLoads ) ) {
589 $this->replLogger->error(
590 __METHOD__ .
": all replica DBs lagged. Switch to read-only mode" );
596 if ( $i ===
false ) {
600 $this->connLogger->debug( __METHOD__ .
": pickRandom() returned false" );
602 return [
false, false ];
606 $this->connLogger->debug( __METHOD__ .
": Using reader #$i: $serverName..." );
611 $this->connLogger->warning( __METHOD__ .
": Failed connecting to $i/$domain" );
612 unset( $currentLoads[$i] );
619 if ( $domain !==
false ) {
628 if ( $currentLoads === [] ) {
629 $this->connLogger->error( __METHOD__ .
": all servers down" );
638 $this->waitForPos = $pos;
641 if ( $i > 0 && !$this->
doWait( $i ) ) {
642 $this->laggedReplicaMode =
true;
654 $this->waitForPos = $pos;
659 $readLoads = $this->groupLoads[self::GROUP_GENERIC];
661 $readLoads = array_filter( $readLoads );
666 $ok = $this->
doWait( $i,
true, $timeout );
672 $this->waitForPos = $oldPos;
683 $this->waitForPos = $pos;
687 for ( $i = 1; $i < $serverCount; $i++ ) {
689 $start = microtime(
true );
690 $ok = $this->
doWait( $i,
true, $timeout ) && $ok;
691 $timeout -= intval( microtime(
true ) - $start );
692 if ( $timeout <= 0 ) {
699 $this->waitForPos = $oldPos;
710 foreach ( $this->groupLoads as $loadsByIndex ) {
711 if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) {
727 if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) {
728 $this->waitForPos = $pos;
736 $autocommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
739 foreach ( $this->conns as $connsByServer ) {
741 if ( $i === self::DB_REPLICA ) {
742 $indexes = array_keys( $connsByServer );
744 $indexes = isset( $connsByServer[$i] ) ? [ $i ] : [];
747 foreach ( $indexes as $index ) {
770 foreach ( $candidateConns as $candidateConn ) {
771 if ( !$candidateConn->isOpen() ) {
777 !$candidateConn->getLBInfo(
'autoCommitOnly' ) ||
779 $candidateConn->trxLevel()
785 $conn = $candidateConn;
798 protected function doWait( $index, $open =
false, $timeout =
null ) {
803 $key = $this->srvCache->makeGlobalKey( __CLASS__,
'last-known-pos', $server,
'v1' );
805 $knownReachedPos = $this->srvCache->get( $key );
808 $knownReachedPos->
hasReached( $this->waitForPos )
810 $this->replLogger->debug(
812 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
813 [
'dbserver' => $server ]
820 $flags = self::CONN_SILENCE_ERRORS;
824 $this->replLogger->debug(
825 __METHOD__ .
': no connection open for {dbserver}',
826 [
'dbserver' => $server ]
834 $this->replLogger->warning(
835 __METHOD__ .
': failed to connect to {dbserver}',
836 [
'dbserver' => $server ]
846 $this->replLogger->info(
848 ': waiting for replica DB {dbserver} to catch up...',
849 [
'dbserver' => $server ]
852 $result = $conn->masterPosWait( $this->waitForPos, $timeout );
854 if ( $result ===
null ) {
855 $this->replLogger->warning(
856 __METHOD__ .
': Errored out waiting on {host} pos {pos}',
859 'pos' => $this->waitForPos,
860 'trace' => (
new RuntimeException() )->getTraceAsString()
864 } elseif ( $result == -1 ) {
865 $this->replLogger->warning(
866 __METHOD__ .
': Timed out waiting on {host} pos {pos}',
869 'pos' => $this->waitForPos,
870 'trace' => (
new RuntimeException() )->getTraceAsString()
875 $this->replLogger->debug( __METHOD__ .
": done waiting" );
878 $this->srvCache->set( $key, $this->waitForPos, BagOStuff::TTL_DAY );
888 public function getConnection( $i, $groups = [], $domain =
false, $flags = 0 ) {
903 !is_string( $conn->getLBInfo(
'readOnlyReason' ) )
906 ?
'The database is read-only until replication lag decreases.'
907 :
'The database is read-only until replica database servers becomes reachable.';
908 $conn->setLBInfo(
'readOnlyReason', $reason );
925 $conn = $this->localDomain->equals( $domain )
930 if ( ( $flags & self::CONN_SILENCE_ERRORS ) != self::CONN_SILENCE_ERRORS ) {
938 if ( $this->connectionCounter > $priorConnectionsMade ) {
939 $this->trxProfiler->recordConnection(
942 ( ( $flags & self::CONN_INTENT_WRITABLE ) == self::CONN_INTENT_WRITABLE )
946 if ( !$conn->isOpen() ) {
947 $this->errorConnection = $conn;
961 if ( $this->readOnlyReason !==
false ) {
964 $readOnlyReason =
'The master database server is running in read-only mode.';
975 $serverIndex = $conn->
getLBInfo(
'serverIndex' );
976 $refCount = $conn->
getLBInfo(
'foreignPoolRefCount' );
977 if ( $serverIndex ===
null || $refCount ===
null ) {
979 } elseif ( $conn instanceof
DBConnRef ) {
982 $this->connLogger->error(
983 __METHOD__ .
": got DBConnRef instance.\n" .
984 (
new LogicException() )->getTraceAsString() );
989 if ( $this->disabled ) {
993 if ( $conn->
getLBInfo(
'autoCommitOnly' ) ) {
1002 if ( !isset( $this->conns[$connInUseKey][$serverIndex][$domain] ) ) {
1003 throw new InvalidArgumentException(
1004 "Connection $serverIndex/$domain not found; it may have already been freed" );
1005 } elseif ( $this->conns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
1006 throw new InvalidArgumentException(
1007 "Connection $serverIndex/$domain mismatched; it may have already been freed" );
1010 $conn->
setLBInfo(
'foreignPoolRefCount', --$refCount );
1011 if ( $refCount <= 0 ) {
1012 $this->conns[$connFreeKey][$serverIndex][$domain] = $conn;
1013 unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
1014 if ( !$this->conns[$connInUseKey][$serverIndex] ) {
1015 unset( $this->conns[$connInUseKey][$serverIndex] );
1017 $this->connLogger->debug( __METHOD__ .
": freed connection $serverIndex/$domain" );
1019 $this->connLogger->debug( __METHOD__ .
1020 ": reference count for $serverIndex/$domain reduced to $refCount" );
1035 return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role );
1043 $this, $this->
getConnection( $i, $groups, $domain, $flags ), $role );
1051 return ( $i === self::DB_MASTER || $i === $this->
getWriterIndex() )
1064 return $this->
getConnection( $i, [], $domain, $flags | self::CONN_SILENCE_ERRORS );
1084 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1087 if ( isset( $this->conns[$connKey][$i][0] ) ) {
1088 $conn = $this->conns[$connKey][$i][0];
1092 $server[
'serverIndex'] = $i;
1093 $server[
'autoCommitOnly'] = $autoCommit;
1096 if ( $conn->isOpen() ) {
1097 $this->connLogger->debug(
1098 __METHOD__ .
": connected to database $i at '$host'." );
1099 $this->conns[$connKey][$i][0] = $conn;
1101 $this->connLogger->warning(
1102 __METHOD__ .
": failed to connect to database $i at '$host'." );
1103 $this->errorConnection = $conn;
1111 !$this->localDomain->isCompatible( $conn->getDomainID() )
1113 throw new UnexpectedValueException(
1114 "Got connection to '{$conn->getDomainID()}', " .
1115 "but expected local domain ('{$this->localDomain}')" );
1149 $autoCommit = ( ( $flags & self::CONN_TRX_AUTOCOMMIT ) == self::CONN_TRX_AUTOCOMMIT );
1151 if ( $autoCommit ) {
1162 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
1164 $conn = $this->conns[$connInUseKey][$i][$domain];
1165 $this->connLogger->debug( __METHOD__ .
": reusing connection $i/$domain" );
1166 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
1168 $conn = $this->conns[$connFreeKey][$i][$domain];
1169 unset( $this->conns[$connFreeKey][$i][$domain] );
1170 $this->conns[$connInUseKey][$i][$domain] = $conn;
1171 $this->connLogger->debug( __METHOD__ .
": reusing free connection $i/$domain" );
1172 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
1174 foreach ( $this->conns[$connFreeKey][$i] as $oldDomain => $conn ) {
1175 if ( $domainInstance->getDatabase() !==
null ) {
1181 $conn->databasesAreIndependent() &&
1182 $conn->getDBname() !== $domainInstance->getDatabase()
1187 $conn->selectDomain( $domainInstance );
1190 $conn->dbSchema( $domainInstance->getSchema() );
1191 $conn->tablePrefix( $domainInstance->getTablePrefix() );
1193 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
1195 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1196 $this->connLogger->debug( __METHOD__ .
1197 ": reusing free connection from $oldDomain for $domain" );
1205 $server[
'serverIndex'] = $i;
1206 $server[
'foreignPoolRefCount'] = 0;
1207 $server[
'foreign'] =
true;
1208 $server[
'autoCommitOnly'] = $autoCommit;
1210 if ( !$conn->isOpen() ) {
1211 $this->connLogger->warning( __METHOD__ .
": connection error for $i/$domain" );
1212 $this->errorConnection = $conn;
1216 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
1217 $this->connLogger->debug( __METHOD__ .
": opened new connection for $i/$domain" );
1223 if ( !$domainInstance->isCompatible( $conn->getDomainID() ) ) {
1224 throw new UnexpectedValueException(
1225 "Got connection to '{$conn->getDomainID()}', but expected '$domain'" );
1228 $refCount = $conn->getLBInfo(
'foreignPoolRefCount' );
1229 $conn->setLBInfo(
'foreignPoolRefCount', $refCount + 1 );
1238 $this->servers[$i][
'driver'] ??
null
1264 if ( $this->disabled ) {
1272 if ( $server[
'type'] ===
'mysql' ) {
1276 $server[
'dbname'] =
null;
1283 $server[
'schema'] = $domain->
getSchema();
1291 $server[
'clusterMasterHost'] = $masterName;
1306 $server[
'flags'] = $server[
'flags'] ?? IDatabase::DBO_DEFAULT;
1310 $conn =
Database::factory( $server[
'type'], $server, Database::NEW_UNCONNECTED );
1311 $conn->setLBInfo( $server );
1312 $conn->setLazyMasterHandle(
1315 $conn->setTableAliases( $this->tableAliases );
1316 $conn->setIndexAliases( $this->indexAliases );
1319 $conn->initConnection();
1326 if ( $this->trxRoundId !==
false ) {
1329 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1330 $conn->setTransactionListener( $name, $callback );
1338 if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) {
1339 $this->perfLogger->warning(
1340 __METHOD__ .
": {connections}+ connections made (master={masterdb})",
1342 'connections' => $count,
1343 'dbserver' => $conn->getServer(),
1344 'masterdb' => $conn->getLBInfo(
'clusterMasterHost' )
1356 if ( !$this->connectionAttempted && $this->chronologyCallback ) {
1357 $this->connectionAttempted =
true;
1359 $this->connLogger->debug( __METHOD__ .
': executed chronology callback.' );
1369 'method' => __METHOD__,
1375 $this->connLogger->warning(
1376 __METHOD__ .
": connection error: {last_error} ({db_server})",
1380 throw new DBConnectionError( $conn,
"{$this->lastError} ({$context['db_server']})" );
1383 $this->connLogger->error(
1385 ": LB failure with no last connection. Connection error: {last_error}",
1406 return array_key_exists( $i, $this->servers );
1417 return ( isset( $this->servers[$i] ) && $this->groupLoads[self::GROUP_GENERIC][$i] > 0 );
1421 return count( $this->servers );
1429 foreach ( $this->servers as $i => $server ) {
1430 if ( $i !== $this->
getWriterIndex() && empty( $server[
'is static'] ) ) {
1439 $name = $this->servers[$i][
'hostName'] ?? ( $this->servers[$i][
'host'] ??
'' );
1441 return ( $name !=
'' ) ? $name :
'localhost';
1445 return $this->servers[$i] ??
false;
1449 return $this->servers[$i][
'type'] ??
'unknown';
1457 return $conn->getMasterPos();
1460 $conn = $this->
getConnection( $index, self::CONN_SILENCE_ERRORS );
1467 $pos = $conn->getMasterPos();
1478 if ( $masterConn ) {
1479 return $masterConn->getMasterPos();
1483 $highestPos =
false;
1485 for ( $i = 1; $i < $serverCount; $i++ ) {
1486 if ( !empty( $this->servers[$i][
'is static'] ) ) {
1491 $pos = $conn ? $conn->getReplicaPos() :
false;
1496 $highestPos = $highestPos ?: $pos;
1497 if ( $pos->hasReached( $highestPos ) ) {
1505 public function disable( $fname = __METHOD__, $owner =
null ) {
1508 $this->disabled =
true;
1511 public function closeAll( $fname = __METHOD__, $owner =
null ) {
1513 if ( $this->ownerId ===
null ) {
1515 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1519 $this->connLogger->debug(
"$fname: closing connection to database '$host'." );
1520 $conn->
close( $fname, $this->
id );
1529 throw new RuntimeException(
'Cannot close DBConnRef instance; it must be shareable' );
1532 $serverIndex = $conn->
getLBInfo(
'serverIndex' );
1533 foreach ( $this->conns as
$type => $connsByServer ) {
1534 if ( !isset( $connsByServer[$serverIndex] ) ) {
1538 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1539 if ( $conn === $trackedConn ) {
1541 $this->connLogger->debug(
1542 __METHOD__ .
": closing connection to database $i at '$host'." );
1543 unset( $this->conns[
$type][$serverIndex][$i] );
1549 $conn->
close( __METHOD__ );
1552 public function commitAll( $fname = __METHOD__, $owner =
null ) {
1561 if ( $this->ownerId ===
null ) {
1563 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1566 $this->trxRoundStage = self::ROUND_ERROR;
1577 }
while ( $count > 0 );
1582 $this->trxRoundStage = self::ROUND_FINALIZED;
1590 if ( $this->ownerId ===
null ) {
1592 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1595 $limit = $options[
'maxWriteDuration'] ?? 0;
1597 $this->trxRoundStage = self::ROUND_ERROR;
1606 if ( $limit > 0 && $time > $limit ) {
1609 "Transaction spent $time second(s) in writes, exceeding the limit of $limit",
1618 "A connection to the {$conn->getDBname()} database was lost before commit"
1622 $this->trxRoundStage = self::ROUND_APPROVED;
1627 if ( $this->trxRoundId !==
false ) {
1630 "$fname: Transaction round '{$this->trxRoundId}' already started"
1634 if ( $this->ownerId ===
null ) {
1636 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1642 $this->trxRoundId = $fname;
1643 $this->trxRoundStage = self::ROUND_ERROR;
1651 $this->trxRoundStage = self::ROUND_CURSORY;
1657 if ( $this->ownerId ===
null ) {
1659 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1664 $restore = ( $this->trxRoundId !== false );
1665 $this->trxRoundId =
false;
1666 $this->trxRoundStage = self::ROUND_ERROR;
1670 function (
IDatabase $conn ) use ( $fname, &$failures ) {
1672 $conn->
commit( $fname, $conn::FLUSHING_ALL_PEERS );
1675 $failures[] =
"{$conn->getServer()}: {$e->getMessage()}";
1682 "$fname: Commit failed on server(s) " . implode(
"\n", array_unique( $failures ) )
1691 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
1696 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1697 $type = IDatabase::TRIGGER_COMMIT;
1698 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1699 $type = IDatabase::TRIGGER_ROLLBACK;
1703 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1706 if ( $this->ownerId ===
null ) {
1708 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1712 $this->trxRoundStage = self::ROUND_ERROR;
1720 $fname = __METHOD__;
1731 $count += $conn->runOnTransactionIdleCallbacks( $type );
1732 } catch ( Exception $ex ) {
1741 $this->queryLogger->warning( $fname .
": found writes pending." );
1742 $fnames = implode(
', ', $conn->pendingWriteAndCallbackCallers() );
1743 $this->queryLogger->warning(
1744 "$fname: found writes pending ($fnames).",
1746 'db_server' => $conn->getServer(),
1747 'db_name' => $conn->getDBname()
1753 $this->queryLogger->debug(
"$fname: found empty transaction." );
1756 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1757 } catch ( Exception $ex ) {
1761 }
while ( $count > 0 );
1763 $this->trxRoundStage = $oldStage;
1770 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
1771 $type = IDatabase::TRIGGER_COMMIT;
1772 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
1773 $type = IDatabase::TRIGGER_ROLLBACK;
1777 "Transaction should be in the callback stage (not '{$this->trxRoundStage}')"
1780 if ( $this->ownerId ===
null ) {
1782 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1787 $this->trxRoundStage = self::ROUND_ERROR;
1791 }
catch ( Exception $ex ) {
1795 $this->trxRoundStage = self::ROUND_CURSORY;
1802 if ( $this->ownerId ===
null ) {
1804 $scope = ScopedCallback::newScopedIgnoreUserAbort();
1807 $restore = ( $this->trxRoundId !== false );
1808 $this->trxRoundId =
false;
1809 $this->trxRoundStage = self::ROUND_ERROR;
1811 $conn->
rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1819 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
1827 $stages = (array)$stage;
1829 if ( !in_array( $this->trxRoundStage, $stages,
true ) ) {
1830 $stageList = implode(
1832 array_map(
function ( $v ) {
1838 "Transaction round stage must be $stageList (not '{$this->trxRoundStage}')"
1856 if ( $this->ownerId !==
null && $owner !== $this->ownerId && $owner !== $this->
id ) {
1859 "$fname: LoadBalancer is owned by ID '{$this->ownerId}' (got '$owner')."
1874 if ( $conn->
getLBInfo(
'autoCommitOnly' ) ) {
1878 if ( $conn->
getFlag( $conn::DBO_DEFAULT ) ) {
1881 $conn->
setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1884 if ( $conn->
getFlag( $conn::DBO_TRX ) ) {
1885 $conn->
setLBInfo(
'trxRoundId', $this->trxRoundId );
1893 if ( $conn->
getLBInfo(
'autoCommitOnly' ) ) {
1897 if ( $conn->
getFlag( $conn::DBO_TRX ) ) {
1901 if ( $conn->
getFlag( $conn::DBO_DEFAULT ) ) {
1938 return (
bool)$pending;
1951 $age = ( $age === null ) ? $this->waitTimeout : $age;
1967 if ( $this->laggedReplicaMode ) {
1986 if ( $this->readOnlyReason !==
false ) {
1989 return 'The master database server is running in read-only mode.';
1992 ?
'The database is read-only until replication lag decreases.'
1993 :
'The database is read-only until a replica database server becomes reachable.';
2006 $key = $this->srvCache->makeGlobalKey(
2007 'rdbms-server-readonly',
2013 if ( ( $flags & self::CONN_REFRESH_READ_ONLY ) == self::CONN_REFRESH_READ_ONLY ) {
2019 $this->srvCache->set( $key, $readOnly, BagOStuff::TTL_PROC_SHORT );
2021 $readOnly = $this->srvCache->getWithSetCallback(
2023 BagOStuff::TTL_PROC_SHORT,
2024 function () use ( $conn ) {
2034 return (
bool)$readOnly;
2043 return (
bool)$this->wanCache->getWithSetCallback(
2045 $this->wanCache->makeGlobalKey(
2046 'rdbms-server-readonly',
2047 $this->getMasterServerName(),
2051 self::TTL_CACHE_READONLY,
2052 function () use ( $domain ) {
2053 $old = $this->trxProfiler->setSilenced(
true );
2057 $flags = self::CONN_REFRESH_READ_ONLY;
2065 $this->trxProfiler->setSilenced( $old );
2069 [
'pcTTL' => WANObjectCache::TTL_PROC_LONG,
'lockTSE' => 10,
'busyValue' => 0 ]
2074 if ( $mode ===
null ) {
2085 if ( !$conn->
ping() ) {
2094 foreach ( $this->conns as $connsByServer ) {
2095 foreach ( $connsByServer as $serverConns ) {
2096 foreach ( $serverConns as $conn ) {
2097 $callback( $conn, ...$params );
2105 foreach ( $this->conns as $connsByServer ) {
2106 if ( isset( $connsByServer[$masterIndex] ) ) {
2108 foreach ( $connsByServer[$masterIndex] as $conn ) {
2109 $callback( $conn, ...$params );
2116 foreach ( $this->conns as $connsByServer ) {
2117 foreach ( $connsByServer as $i => $serverConns ) {
2121 foreach ( $serverConns as $conn ) {
2122 $callback( $conn, ...$params );
2133 foreach ( $this->conns as $connsByServer ) {
2134 foreach ( $connsByServer as $serverConns ) {
2135 $count += count( $serverConns );
2149 foreach ( $lagTimes as $i => $lag ) {
2150 if ( $this->groupLoads[self::GROUP_GENERIC][$i] > 0 && $lag >
$maxLag ) {
2158 return [ $host,
$maxLag, $maxIndex ];
2166 $knownLagTimes = [];
2167 $indexesWithLag = [];
2168 foreach ( $this->servers as $i => $server ) {
2169 if ( empty( $server[
'is static'] ) ) {
2170 $indexesWithLag[] = $i;
2172 $knownLagTimes[$i] = 0;
2176 return $this->
getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
2195 if ( $conn->
getLBInfo(
'is static' ) ) {
2197 } elseif ( $conn->
getLBInfo(
'serverIndex' ) == $this->getWriterIndex() ) {
2214 $flags = self::CONN_SILENCE_ERRORS;
2216 if ( $masterConn ) {
2217 $pos = $masterConn->getMasterPos();
2220 if ( !$masterConn ) {
2223 "Could not obtain a master database connection to get the position"
2226 $pos = $masterConn->getMasterPos();
2232 $start = microtime(
true );
2234 $seconds = max( microtime(
true ) - $start, 0 );
2235 if ( $result == -1 || is_null( $result ) ) {
2236 $msg = __METHOD__ .
': timed out waiting on {host} pos {pos} [{seconds}s]';
2237 $this->replLogger->warning( $msg, [
2240 'seconds' => round( $seconds, 6 ),
2241 'trace' => (
new RuntimeException() )->getTraceAsString()
2245 $this->replLogger->debug( __METHOD__ .
': done waiting' );
2250 $this->replLogger->error(
2251 __METHOD__ .
': could not get master pos for {host}',
2254 'trace' => (
new RuntimeException() )->getTraceAsString()
2280 $this->trxRecurringCallbacks[$name] = $callback;
2282 unset( $this->trxRecurringCallbacks[$name] );
2285 function (
IDatabase $conn ) use ( $name, $callback ) {
2292 $this->tableAliases = $aliases;
2296 $this->indexAliases = $aliases;
2305 if ( $conn->
getLBInfo(
'foreignPoolRefCount' ) > 0 ) {
2306 $domainsInUse[] = $conn->getDomainID();
2311 if ( $domainsInUse ) {
2312 $domains = implode(
', ', $domainsInUse );
2314 "Foreign domain connections are still in use ($domains)" );
2318 $this->localDomain->getDatabase(),
2319 $this->localDomain->getSchema(),
2326 $conn->tablePrefix( $prefix );
2332 $this->
closeAll( __METHOD__, $this->
id );
2338 $old = $this->tempTablesOnlyMode[$domain] ??
false;
2340 $this->tempTablesOnlyMode[$domain] =
true;
2342 unset( $this->tempTablesOnlyMode[$domain] );
2352 $this->localDomain = $domain;
2355 if ( $this->localDomain->getTablePrefix() !=
'' ) {
2356 $this->localDomainIdAlias =
2357 $this->localDomain->
getDatabase() .
'-' . $this->localDomain->getTablePrefix();
2359 $this->localDomainIdAlias = $this->localDomain->getDatabase();
2370 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
2371 throw new InvalidArgumentException(
"No server with index '$i'" );
2374 if ( $field !==
null ) {
2375 if ( !array_key_exists( $field, $this->servers[$i] ) ) {
2376 throw new InvalidArgumentException(
"No field '$field' in server index '$i'" );
2379 return $this->servers[$i][$field];
2382 return $this->servers[$i];
2394 $this->
disable( __METHOD__, $this->ownerId );
2401class_alias( LoadBalancer::class,
'LoadBalancer' );
A collection of static methods to play with arrays.
static pickRandom( $weights)
Given an array of non-normalised probabilities, this function will select an element and return the a...
Class representing a cache/ephemeral data store.
A BagOStuff object with no objects in it.
Multi-datacenter aware caching interface.
Class to handle database/schema/prefix specifications for IDatabase.
static newFromId( $domain)
Helper class to handle automatically marking connections as reusable (via RAII pattern) as well handl...