| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
namespace Wikimedia\Rdbms; |
| 21 |
|
| 22 |
use ArrayUtils; |
| 23 |
use InvalidArgumentException; |
| 24 |
use Liuggio\StatsdClient\Factory\StatsdDataFactoryInterface; |
| 25 |
use LogicException; |
| 26 |
use Psr\Log\LoggerInterface; |
| 27 |
use Psr\Log\NullLogger; |
| 28 |
use RuntimeException; |
| 29 |
use Throwable; |
| 30 |
use UnexpectedValueException; |
| 31 |
use Wikimedia\ObjectCache\BagOStuff; |
| 32 |
use Wikimedia\ObjectCache\EmptyBagOStuff; |
| 33 |
use Wikimedia\ObjectCache\WANObjectCache; |
| 34 |
use Wikimedia\ScopedCallback; |
| 35 |
use Wikimedia\Stats\NullStatsdDataFactory; |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
class LoadBalancer implements ILoadBalancerForOwner { |
| 42 |
|
| 43 |
private $loadMonitor; |
| 44 |
|
| 45 |
private $srvCache; |
| 46 |
|
| 47 |
private $wanCache; |
| 48 |
|
| 49 |
private $databaseFactory; |
| 50 |
|
| 51 |
|
| 52 |
private $trxProfiler; |
| 53 |
|
| 54 |
private $statsd; |
| 55 |
|
| 56 |
private $logger; |
| 57 |
|
| 58 |
private $errorLogger; |
| 59 |
|
| 60 |
private $localDomain; |
| 61 |
|
| 62 |
|
| 63 |
private $conns; |
| 64 |
|
| 65 |
|
| 66 |
private $clusterName; |
| 67 |
|
| 68 |
private $serverInfo; |
| 69 |
|
| 70 |
private $groupLoads; |
| 71 |
|
| 72 |
private $defaultGroup; |
| 73 |
|
| 74 |
|
| 75 |
private $tableAliases = []; |
| 76 |
|
| 77 |
private $indexAliases = []; |
| 78 |
|
| 79 |
private $domainAliases = []; |
| 80 |
|
| 81 |
private $trxRecurringCallbacks = []; |
| 82 |
|
| 83 |
private $tempTablesOnlyMode = []; |
| 84 |
|
| 85 |
|
| 86 |
private $trxRoundId = false; |
| 87 |
|
| 88 |
private $trxRoundStage = self::ROUND_CURSORY; |
| 89 |
|
| 90 |
private $readIndexByGroup = []; |
| 91 |
|
| 92 |
private $waitForPos; |
| 93 |
|
| 94 |
private $laggedReplicaMode = false; |
| 95 |
|
| 96 |
private $readOnlyReason = false; |
| 97 |
|
| 98 |
private $connectionCounter = 0; |
| 99 |
|
| 100 |
private $disabled = false; |
| 101 |
private ?ChronologyProtector $chronologyProtector = null; |
| 102 |
|
| 103 |
private $chronologyProtectorCalled = false; |
| 104 |
|
| 105 |
|
| 106 |
private $lastErrorConn; |
| 107 |
|
| 108 |
|
| 109 |
private $nonLocalDomainCache = []; |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
private $modcount = 0; |
| 116 |
|
| 117 |
|
| 118 |
private const INFO_SERVER_INDEX = 'serverIndex'; |
| 119 |
|
| 120 |
private const INFO_CONN_CATEGORY = 'connCategory'; |
| 121 |
|
| 122 |
|
| 123 |
private const CONN_HELD_WARN_THRESHOLD = 10; |
| 124 |
|
| 125 |
|
| 126 |
private const MAX_WAIT_DEFAULT = 10; |
| 127 |
|
| 128 |
private const TTL_CACHE_READONLY = 5; |
| 129 |
|
| 130 |
|
| 131 |
private const CATEGORY_ROUND = 'round'; |
| 132 |
|
| 133 |
private const CATEGORY_AUTOCOMMIT = 'auto-commit'; |
| 134 |
|
| 135 |
private const CATEGORY_GAUGE = 'gauge'; |
| 136 |
|
| 137 |
|
| 138 |
private const ROUND_CURSORY = 'cursory'; |
| 139 |
|
| 140 |
private const ROUND_FINALIZED = 'finalized'; |
| 141 |
|
| 142 |
private const ROUND_APPROVED = 'approved'; |
| 143 |
|
| 144 |
private const ROUND_COMMIT_CALLBACKS = 'commit-callbacks'; |
| 145 |
|
| 146 |
private const ROUND_ROLLBACK_CALLBACKS = 'rollback-callbacks'; |
| 147 |
|
| 148 |
private const ROUND_ERROR = 'error'; |
| 149 |
|
| 150 |
|
| 151 |
private const READER_INDEX_NONE = -1; |
| 152 |
|
| 153 |
public function __construct( array $params ) { |
| 154 |
$this->configure( $params ); |
| 155 |
|
| 156 |
$this->conns = self::newTrackedConnectionsArray(); |
| 157 |
} |
| 158 |
|
| 159 |
|
| 160 |
|
| 161 |
|
| 162 |
|
| 163 |
|
| 164 |
protected function configure( array $params ): void { |
| 165 |
$this->localDomain = isset( $params['localDomain'] ) |
| 166 |
? DatabaseDomain::newFromId( $params['localDomain'] ) |
| 167 |
: DatabaseDomain::newUnspecified(); |
| 168 |
|
| 169 |
$this->serverInfo = new ServerInfo(); |
| 170 |
$this->groupLoads = [ self::GROUP_GENERIC => [] ]; |
| 171 |
foreach ( $this->serverInfo->normalizeServerMaps( $params['servers'] ?? [] ) as $i => $server ) { |
| 172 |
$this->serverInfo->addServer( $i, $server ); |
| 173 |
foreach ( $server['groupLoads'] as $group => $weight ) { |
| 174 |
$this->groupLoads[$group][$i] = $weight; |
| 175 |
} |
| 176 |
$this->groupLoads[self::GROUP_GENERIC][$i] = $server['load']; |
| 177 |
} |
| 178 |
|
| 179 |
$this->clusterName = $params['clusterName'] |
| 180 |
?? $this->serverInfo->getServerName( ServerInfo::WRITER_INDEX ); |
| 181 |
|
| 182 |
if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) { |
| 183 |
$this->readOnlyReason = $params['readOnlyReason']; |
| 184 |
} |
| 185 |
|
| 186 |
$this->srvCache = $params['srvCache'] ?? new EmptyBagOStuff(); |
| 187 |
$this->wanCache = $params['wanCache'] ?? WANObjectCache::newEmpty(); |
| 188 |
|
| 189 |
|
| 190 |
$this->databaseFactory = $params['databaseFactory'] ?? new DatabaseFactory( $params ); |
| 191 |
|
| 192 |
$this->errorLogger = $params['errorLogger'] ?? static function ( Throwable $e ) { |
| 193 |
trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING ); |
| 194 |
}; |
| 195 |
$this->logger = $params['logger'] ?? new NullLogger(); |
| 196 |
|
| 197 |
$this->trxProfiler = $params['trxProfiler'] ?? new TransactionProfiler(); |
| 198 |
$this->statsd = $params['statsdDataFactory'] ?? new NullStatsdDataFactory(); |
| 199 |
|
| 200 |
|
| 201 |
$loadMonitorConfig = $params['loadMonitor'] ?? [ 'class' => LoadMonitorNull::class ]; |
| 202 |
$compat = [ |
| 203 |
'LoadMonitor' => LoadMonitor::class, |
| 204 |
'LoadMonitorNull' => LoadMonitorNull::class |
| 205 |
]; |
| 206 |
$class = $loadMonitorConfig['class']; |
| 207 |
|
| 208 |
if ( isset( $compat[$class] ) ) { |
| 209 |
$class = $compat[$class]; |
| 210 |
} |
| 211 |
$this->loadMonitor = new $class( |
| 212 |
$this, $this->srvCache, $this->wanCache, $loadMonitorConfig ); |
| 213 |
$this->loadMonitor->setLogger( $this->logger ); |
| 214 |
$this->loadMonitor->setStatsdDataFactory( $this->statsd ); |
| 215 |
|
| 216 |
if ( isset( $params['chronologyProtector'] ) ) { |
| 217 |
$this->chronologyProtector = $params['chronologyProtector']; |
| 218 |
} |
| 219 |
|
| 220 |
if ( isset( $params['roundStage'] ) ) { |
| 221 |
if ( $params['roundStage'] === self::STAGE_POSTCOMMIT_CALLBACKS ) { |
| 222 |
$this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS; |
| 223 |
} elseif ( $params['roundStage'] === self::STAGE_POSTROLLBACK_CALLBACKS ) { |
| 224 |
$this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS; |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
$group = $params['defaultGroup'] ?? self::GROUP_GENERIC; |
| 229 |
$this->defaultGroup = isset( $this->groupLoads[ $group ] ) ? $group : self::GROUP_GENERIC; |
| 230 |
} |
| 231 |
|
| 232 |
private static function newTrackedConnectionsArray() { |
| 233 |
|
| 234 |
return [ |
| 235 |
self::CATEGORY_ROUND => [], |
| 236 |
self::CATEGORY_AUTOCOMMIT => [] |
| 237 |
]; |
| 238 |
} |
| 239 |
|
| 240 |
public function getClusterName(): string { |
| 241 |
return $this->clusterName; |
| 242 |
} |
| 243 |
|
| 244 |
public function getLocalDomainID(): string { |
| 245 |
return $this->localDomain->getId(); |
| 246 |
} |
| 247 |
|
| 248 |
public function resolveDomainID( $domain ): string { |
| 249 |
return $this->resolveDomainInstance( $domain )->getId(); |
| 250 |
} |
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
final protected function resolveDomainInstance( $domain ): DatabaseDomain { |
| 257 |
if ( $domain instanceof DatabaseDomain ) { |
| 258 |
return $domain; |
| 259 |
} elseif ( $domain === false || $domain === $this->localDomain->getId() ) { |
| 260 |
return $this->localDomain; |
| 261 |
} elseif ( isset( $this->domainAliases[$domain] ) ) { |
| 262 |
$this->domainAliases[$domain] = |
| 263 |
DatabaseDomain::newFromId( $this->domainAliases[$domain] ); |
| 264 |
|
| 265 |
return $this->domainAliases[$domain]; |
| 266 |
} |
| 267 |
|
| 268 |
$cachedDomain = $this->nonLocalDomainCache[$domain] ?? null; |
| 269 |
if ( $cachedDomain === null ) { |
| 270 |
$cachedDomain = DatabaseDomain::newFromId( $domain ); |
| 271 |
$this->nonLocalDomainCache = [ $domain => $cachedDomain ]; |
| 272 |
} |
| 273 |
|
| 274 |
return $cachedDomain; |
| 275 |
} |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
private function resolveGroups( $groups, $i ) { |
| 285 |
|
| 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)" ); |
| 289 |
} |
| 290 |
|
| 291 |
if ( $groups === [] || $groups === false || $groups === $this->defaultGroup ) { |
| 292 |
$resolvedGroup = $this->defaultGroup; |
| 293 |
} elseif ( is_string( $groups ) ) { |
| 294 |
$resolvedGroup = isset( $this->groupLoads[$groups] ) ? $groups : $this->defaultGroup; |
| 295 |
} elseif ( is_array( $groups ) ) { |
| 296 |
$resolvedGroup = $this->defaultGroup; |
| 297 |
foreach ( $groups as $group ) { |
| 298 |
if ( isset( $this->groupLoads[$group] ) ) { |
| 299 |
$resolvedGroup = $group; |
| 300 |
break; |
| 301 |
} |
| 302 |
} |
| 303 |
} else { |
| 304 |
$resolvedGroup = $this->defaultGroup; |
| 305 |
} |
| 306 |
|
| 307 |
return $resolvedGroup; |
| 308 |
} |
| 309 |
|
| 310 |
|
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
|
| 315 |
|
| 316 |
|
| 317 |
protected function sanitizeConnectionFlags( $flags, $domain ) { |
| 318 |
if ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) { |
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
$attributes = $this->getServerAttributes( ServerInfo::WRITER_INDEX ); |
| 327 |
if ( $attributes[Database::ATTR_DB_LEVEL_LOCKING] ) { |
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
$flags &= ~self::CONN_TRX_AUTOCOMMIT; |
| 333 |
$type = $this->serverInfo->getServerType( ServerInfo::WRITER_INDEX ); |
| 334 |
$this->logger->info( __METHOD__ . ": CONN_TRX_AUTOCOMMIT disallowed ($type)" ); |
| 335 |
} elseif ( isset( $this->tempTablesOnlyMode[$domain] ) ) { |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
$flags &= ~self::CONN_TRX_AUTOCOMMIT; |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
return $flags; |
| 345 |
} |
| 346 |
|
| 347 |
|
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
private function enforceConnectionFlags( IDatabase $conn, $flags ) { |
| 353 |
if ( |
| 354 |
self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) || |
| 355 |
|
| 356 |
|
| 357 |
self::fieldHasBit( $flags, self::CONN_UNTRACKED_GAUGE ) |
| 358 |
) { |
| 359 |
if ( $conn->trxLevel() ) { |
| 360 |
throw new DBUnexpectedError( |
| 361 |
$conn, |
| 362 |
'Handle requested with autocommit-mode yet it has a transaction' |
| 363 |
); |
| 364 |
} |
| 365 |
|
| 366 |
$conn->clearFlag( $conn::DBO_TRX ); |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 375 |
|
| 376 |
|
| 377 |
private function getRandomNonLagged( array $loads, $sessionLagLimit = INF ) { |
| 378 |
$lags = $this->getLagTimes(); |
| 379 |
|
| 380 |
|
| 381 |
foreach ( $lags as $i => $lag ) { |
| 382 |
if ( $i !== ServerInfo::WRITER_INDEX ) { |
| 383 |
|
| 384 |
$maxServerLag = $this->serverInfo->getServerMaxLag( $i ); |
| 385 |
|
| 386 |
$maxServerLag = min( $maxServerLag, $sessionLagLimit ); |
| 387 |
|
| 388 |
$srvName = $this->serverInfo->getServerName( $i ); |
| 389 |
if ( $lag === false && !is_infinite( $maxServerLag ) ) { |
| 390 |
$this->logger->debug( |
| 391 |
__METHOD__ . ": server {db_server} is not replicating?", |
| 392 |
[ 'db_server' => $srvName ] |
| 393 |
); |
| 394 |
unset( $loads[$i] ); |
| 395 |
} elseif ( $lag > $maxServerLag ) { |
| 396 |
$this->logger->debug( |
| 397 |
__METHOD__ . |
| 398 |
": server {db_server} has {lag} seconds of lag (>= {maxlag})", |
| 399 |
[ 'db_server' => $srvName, 'lag' => $lag, 'maxlag' => $maxServerLag ] |
| 400 |
); |
| 401 |
unset( $loads[$i] ); |
| 402 |
} |
| 403 |
} |
| 404 |
} |
| 405 |
|
| 406 |
if ( array_sum( $loads ) == 0 ) { |
| 407 |
|
| 408 |
|
| 409 |
return false; |
| 410 |
} |
| 411 |
|
| 412 |
|
| 413 |
return ArrayUtils::pickRandom( $loads ); |
| 414 |
} |
| 415 |
|
| 416 |
public function getReaderIndex( $group = false ) { |
| 417 |
$group = is_string( $group ) ? $group : self::GROUP_GENERIC; |
| 418 |
|
| 419 |
if ( !$this->serverInfo->hasReplicaServers() ) { |
| 420 |
|
| 421 |
return ServerInfo::WRITER_INDEX; |
| 422 |
} |
| 423 |
|
| 424 |
$index = $this->getExistingReaderIndex( $group ); |
| 425 |
if ( $index !== self::READER_INDEX_NONE ) { |
| 426 |
|
| 427 |
|
| 428 |
|
| 429 |
return $index; |
| 430 |
} |
| 431 |
|
| 432 |
|
| 433 |
$loads = $this->groupLoads[$group] ?? []; |
| 434 |
if ( !$loads ) { |
| 435 |
$this->logger->info( __METHOD__ . ": no loads for group $group" ); |
| 436 |
return false; |
| 437 |
} |
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
$this->loadSessionPrimaryPos(); |
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
$this->loadMonitor->scaleLoads( $loads ); |
| 447 |
|
| 448 |
|
| 449 |
$i = $this->pickReaderIndex( $loads ); |
| 450 |
if ( $i === false ) { |
| 451 |
|
| 452 |
return false; |
| 453 |
} |
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
if ( !$this->awaitSessionPrimaryPos( $i ) ) { |
| 459 |
|
| 460 |
$this->setLaggedReplicaMode(); |
| 461 |
} |
| 462 |
|
| 463 |
|
| 464 |
if ( $i < 0 ) { |
| 465 |
throw new UnexpectedValueException( "Cannot set a negative read server index" ); |
| 466 |
} |
| 467 |
$this->readIndexByGroup[$group] = $i; |
| 468 |
|
| 469 |
$serverName = $this->getServerName( $i ); |
| 470 |
$this->logger->debug( __METHOD__ . ": using server $serverName for group '$group'" ); |
| 471 |
|
| 472 |
return $i; |
| 473 |
} |
| 474 |
|
| 475 |
|
| 476 |
|
| 477 |
|
| 478 |
|
| 479 |
|
| 480 |
|
| 481 |
protected function getExistingReaderIndex( $group ) { |
| 482 |
return $this->readIndexByGroup[$group] ?? self::READER_INDEX_NONE; |
| 483 |
} |
| 484 |
|
| 485 |
|
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
|
| 491 |
|
| 492 |
|
| 493 |
private function pickReaderIndex( array $loads ) { |
| 494 |
if ( $loads === [] ) { |
| 495 |
throw new InvalidArgumentException( "Load group array is empty" ); |
| 496 |
} |
| 497 |
|
| 498 |
$i = false; |
| 499 |
|
| 500 |
$currentLoads = $loads; |
| 501 |
while ( count( $currentLoads ) ) { |
| 502 |
if ( $this->waitForPos && $this->waitForPos->asOfTime() ) { |
| 503 |
$this->logger->debug( __METHOD__ . ": session has replication position" ); |
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
$ago = microtime( true ) - $this->waitForPos->asOfTime(); |
| 509 |
|
| 510 |
$i = $this->getRandomNonLagged( $currentLoads, $ago + 1 ); |
| 511 |
} else { |
| 512 |
|
| 513 |
$i = $this->getRandomNonLagged( $currentLoads ); |
| 514 |
} |
| 515 |
|
| 516 |
if ( $i === false && count( $currentLoads ) ) { |
| 517 |
$this->setLaggedReplicaMode(); |
| 518 |
|
| 519 |
$i = ArrayUtils::pickRandom( $currentLoads ); |
| 520 |
} |
| 521 |
|
| 522 |
if ( $i === false ) { |
| 523 |
|
| 524 |
|
| 525 |
|
| 526 |
$this->logger->debug( __METHOD__ . ": no suitable server found" ); |
| 527 |
return false; |
| 528 |
} |
| 529 |
|
| 530 |
$serverName = $this->getServerName( $i ); |
| 531 |
$this->logger->debug( __METHOD__ . ": connecting to $serverName..." ); |
| 532 |
|
| 533 |
|
| 534 |
|
| 535 |
|
| 536 |
$conn = $this->getServerConnection( $i, self::DOMAIN_ANY, self::CONN_SILENCE_ERRORS ); |
| 537 |
if ( !$conn ) { |
| 538 |
$this->logger->warning( __METHOD__ . ": failed connecting to $serverName" ); |
| 539 |
unset( $currentLoads[$i] ); |
| 540 |
continue; |
| 541 |
} |
| 542 |
|
| 543 |
|
| 544 |
break; |
| 545 |
} |
| 546 |
|
| 547 |
|
| 548 |
if ( $currentLoads === [] ) { |
| 549 |
$this->logger->error( __METHOD__ . ": all servers down" ); |
| 550 |
} |
| 551 |
|
| 552 |
return $i; |
| 553 |
} |
| 554 |
|
| 555 |
public function waitForAll( DBPrimaryPos $pos, $timeout = null ) { |
| 556 |
$timeout = $timeout ?: self::MAX_WAIT_DEFAULT; |
| 557 |
|
| 558 |
$oldPos = $this->waitForPos; |
| 559 |
try { |
| 560 |
$this->waitForPos = $pos; |
| 561 |
|
| 562 |
$failedReplicas = []; |
| 563 |
foreach ( $this->serverInfo->getStreamingReplicaIndexes() as $i ) { |
| 564 |
if ( $this->serverHasLoadInAnyGroup( $i ) ) { |
| 565 |
$start = microtime( true ); |
| 566 |
$ok = $this->awaitSessionPrimaryPos( $i, $timeout ); |
| 567 |
if ( !$ok ) { |
| 568 |
$failedReplicas[] = $this->getServerName( $i ); |
| 569 |
} |
| 570 |
$timeout -= intval( microtime( true ) - $start ); |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
|
| 575 |
|
| 576 |
$failed = $failedReplicas && ( count( $failedReplicas ) > 1 || $this->getServerCount() < 5 ); |
| 577 |
if ( $failed ) { |
| 578 |
$this->logger->error( |
| 579 |
"Timed out waiting for replication to reach {raw_pos}", |
| 580 |
[ |
| 581 |
'raw_pos' => $pos->__toString(), |
| 582 |
'failed_hosts' => $failedReplicas, |
| 583 |
'timeout' => $timeout, |
| 584 |
'exception' => new RuntimeException() |
| 585 |
] |
| 586 |
); |
| 587 |
} |
| 588 |
|
| 589 |
return !$failed; |
| 590 |
} finally { |
| 591 |
|
| 592 |
$this->waitForPos = $oldPos; |
| 593 |
} |
| 594 |
} |
| 595 |
|
| 596 |
|
| 597 |
|
| 598 |
|
| 599 |
|
| 600 |
private function serverHasLoadInAnyGroup( $i ) { |
| 601 |
foreach ( $this->groupLoads as $loadsByIndex ) { |
| 602 |
if ( ( $loadsByIndex[$i] ?? 0 ) > 0 ) { |
| 603 |
return true; |
| 604 |
} |
| 605 |
} |
| 606 |
|
| 607 |
return false; |
| 608 |
} |
| 609 |
|
| 610 |
public function getAnyOpenConnection( $i, $flags = 0 ) { |
| 611 |
$i = ( $i === self::DB_PRIMARY ) ? ServerInfo::WRITER_INDEX : $i; |
| 612 |
$conn = false; |
| 613 |
foreach ( $this->conns as $type => $poolConnsByServer ) { |
| 614 |
if ( $i === self::DB_REPLICA ) { |
| 615 |
|
| 616 |
$applicableConnsByServer = $poolConnsByServer; |
| 617 |
} else { |
| 618 |
|
| 619 |
$applicableConnsByServer = isset( $poolConnsByServer[$i] ) |
| 620 |
? [ $i => $poolConnsByServer[$i] ] |
| 621 |
: []; |
| 622 |
} |
| 623 |
|
| 624 |
$conn = $this->pickAnyOpenConnection( $applicableConnsByServer ); |
| 625 |
if ( $conn ) { |
| 626 |
$this->logger->debug( __METHOD__ . ": found '$type' connection to #$i." ); |
| 627 |
break; |
| 628 |
} |
| 629 |
} |
| 630 |
|
| 631 |
if ( $conn ) { |
| 632 |
$this->enforceConnectionFlags( $conn, $flags ); |
| 633 |
} |
| 634 |
|
| 635 |
return $conn; |
| 636 |
} |
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
|
| 641 |
|
| 642 |
private function pickAnyOpenConnection( array $connsByServer ) { |
| 643 |
foreach ( $connsByServer as $i => $conns ) { |
| 644 |
foreach ( $conns as $conn ) { |
| 645 |
if ( !$conn->isOpen() ) { |
| 646 |
$this->logger->warning( |
| 647 |
__METHOD__ . |
| 648 |
": pooled DB handle for {db_server} (#$i) has no open connection.", |
| 649 |
$this->getConnLogContext( $conn ) |
| 650 |
); |
| 651 |
continue; |
| 652 |
} |
| 653 |
return $conn; |
| 654 |
} |
| 655 |
} |
| 656 |
|
| 657 |
return false; |
| 658 |
} |
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
|
| 663 |
|
| 664 |
|
| 665 |
|
| 666 |
|
| 667 |
|
| 668 |
|
| 669 |
private function awaitSessionPrimaryPos( $index, $timeout = null ) { |
| 670 |
$timeout = max( 1, intval( $timeout ?: self::MAX_WAIT_DEFAULT ) ); |
| 671 |
|
| 672 |
if ( !$this->waitForPos || $index === ServerInfo::WRITER_INDEX ) { |
| 673 |
return true; |
| 674 |
} |
| 675 |
|
| 676 |
$srvName = $this->getServerName( $index ); |
| 677 |
|
| 678 |
|
| 679 |
$key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $srvName, 'v2' ); |
| 680 |
|
| 681 |
|
| 682 |
$position = $this->srvCache->get( $key ); |
| 683 |
if ( !is_array( $position ) ) { |
| 684 |
$knownReachedPos = null; |
| 685 |
} else { |
| 686 |
$class = $position['_type_']; |
| 687 |
$knownReachedPos = $class::newFromArray( $position ); |
| 688 |
} |
| 689 |
if ( |
| 690 |
$knownReachedPos instanceof DBPrimaryPos && |
| 691 |
$knownReachedPos->hasReached( $this->waitForPos ) |
| 692 |
) { |
| 693 |
$this->logger->debug( |
| 694 |
__METHOD__ . |
| 695 |
": replica DB {db_server} known to be caught up (pos >= $knownReachedPos).", |
| 696 |
[ 'db_server' => $srvName ] |
| 697 |
); |
| 698 |
|
| 699 |
return true; |
| 700 |
} |
| 701 |
|
| 702 |
$close = false; |
| 703 |
$flags = self::CONN_SILENCE_ERRORS; |
| 704 |
|
| 705 |
$conn = $this->getAnyOpenConnection( $index, $flags ); |
| 706 |
if ( !$conn ) { |
| 707 |
|
| 708 |
|
| 709 |
|
| 710 |
$conn = $this->getServerConnection( $index, self::DOMAIN_ANY, $flags ); |
| 711 |
if ( !$conn ) { |
| 712 |
$this->logger->warning( |
| 713 |
__METHOD__ . ': failed to connect to {db_server}', |
| 714 |
[ 'db_server' => $srvName ] |
| 715 |
); |
| 716 |
|
| 717 |
return false; |
| 718 |
} |
| 719 |
|
| 720 |
|
| 721 |
$close = true; |
| 722 |
} |
| 723 |
|
| 724 |
$this->logger->info( |
| 725 |
__METHOD__ . |
| 726 |
': waiting for replica DB {db_server} to catch up...', |
| 727 |
$this->getConnLogContext( $conn ) |
| 728 |
); |
| 729 |
|
| 730 |
$result = $conn->primaryPosWait( $this->waitForPos, $timeout ); |
| 731 |
|
| 732 |
$ok = ( $result !== null && $result != -1 ); |
| 733 |
if ( $ok ) { |
| 734 |
|
| 735 |
$this->srvCache->set( $key, $this->waitForPos->toArray(), BagOStuff::TTL_DAY ); |
| 736 |
} |
| 737 |
|
| 738 |
if ( $close ) { |
| 739 |
$this->closeConnection( $conn ); |
| 740 |
} |
| 741 |
|
| 742 |
return $ok; |
| 743 |
} |
| 744 |
|
| 745 |
public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) { |
| 746 |
if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) { |
| 747 |
throw new UnexpectedValueException( |
| 748 |
__METHOD__ . ' got CONN_SILENCE_ERRORS; connection is already deferred' |
| 749 |
); |
| 750 |
} |
| 751 |
|
| 752 |
$domain = $this->resolveDomainID( $domain ); |
| 753 |
$role = ( $i === self::DB_PRIMARY || $i === ServerInfo::WRITER_INDEX ) |
| 754 |
? self::DB_PRIMARY |
| 755 |
: self::DB_REPLICA; |
| 756 |
|
| 757 |
return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount ); |
| 758 |
} |
| 759 |
|
| 760 |
public function getConnectionInternal( $i, $groups = [], $domain = false, $flags = 0 ): IDatabase { |
| 761 |
$domain = $this->resolveDomainID( $domain ); |
| 762 |
$group = $this->resolveGroups( $groups, $i ); |
| 763 |
$flags = $this->sanitizeConnectionFlags( $flags, $domain ); |
| 764 |
|
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
$serverIndex = $i; |
| 769 |
if ( $i === self::DB_PRIMARY ) { |
| 770 |
$serverIndex = ServerInfo::WRITER_INDEX; |
| 771 |
} elseif ( $i === self::DB_REPLICA ) { |
| 772 |
$groupIndex = $this->getReaderIndex( $group ); |
| 773 |
if ( $groupIndex !== false ) { |
| 774 |
|
| 775 |
$serverIndex = $groupIndex; |
| 776 |
} |
| 777 |
if ( $serverIndex < 0 ) { |
| 778 |
$this->reportConnectionError( 'could not connect to any replica DB server' ); |
| 779 |
} |
| 780 |
} elseif ( !$this->serverInfo->hasServerIndex( $i ) ) { |
| 781 |
throw new UnexpectedValueException( "Invalid server index index #$i" ); |
| 782 |
} |
| 783 |
|
| 784 |
return $this->getServerConnection( $serverIndex, $domain, $flags ); |
| 785 |
} |
| 786 |
|
| 787 |
public function getServerConnection( $i, $domain, $flags = 0 ) { |
| 788 |
$domainInstance = DatabaseDomain::newFromId( $domain ); |
| 789 |
|
| 790 |
$priorConnectionsMade = $this->connectionCounter; |
| 791 |
|
| 792 |
$conn = $this->reuseOrOpenConnectionForNewRef( $i, $domainInstance, $flags ); |
| 793 |
|
| 794 |
if ( !( $conn instanceof IDatabaseForOwner ) ) { |
| 795 |
if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) { |
| 796 |
$this->reportConnectionError(); |
| 797 |
} |
| 798 |
|
| 799 |
return false; |
| 800 |
} |
| 801 |
|
| 802 |
|
| 803 |
if ( $this->connectionCounter > $priorConnectionsMade ) { |
| 804 |
$this->trxProfiler->recordConnection( |
| 805 |
$conn->getServerName(), |
| 806 |
$conn->getDBname(), |
| 807 |
( $i === ServerInfo::WRITER_INDEX && $this->hasStreamingReplicaServers() ) |
| 808 |
); |
| 809 |
} |
| 810 |
|
| 811 |
if ( !$conn->isOpen() ) { |
| 812 |
$this->lastErrorConn = $conn; |
| 813 |
|
| 814 |
|
| 815 |
|
| 816 |
if ( !self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) { |
| 817 |
$this->reportConnectionError(); |
| 818 |
} |
| 819 |
return false; |
| 820 |
} |
| 821 |
|
| 822 |
return $conn; |
| 823 |
} |
| 824 |
|
| 825 |
|
| 826 |
|
| 827 |
|
| 828 |
public function getConnectionRef( $i, $groups = [], $domain = false, $flags = 0 ): DBConnRef { |
| 829 |
wfDeprecated( __METHOD__, '1.39' ); |
| 830 |
|
| 831 |
return $this->getConnection( $i, $groups, $domain, $flags ); |
| 832 |
} |
| 833 |
|
| 834 |
public function getMaintenanceConnectionRef( |
| 835 |
$i, |
| 836 |
$groups = [], |
| 837 |
$domain = false, |
| 838 |
$flags = 0 |
| 839 |
): DBConnRef { |
| 840 |
if ( self::fieldHasBit( $flags, self::CONN_SILENCE_ERRORS ) ) { |
| 841 |
throw new UnexpectedValueException( |
| 842 |
__METHOD__ . ' CONN_SILENCE_ERRORS is not supported' |
| 843 |
); |
| 844 |
} |
| 845 |
|
| 846 |
$domain = $this->resolveDomainID( $domain ); |
| 847 |
$role = ( $i === self::DB_PRIMARY || $i === ServerInfo::WRITER_INDEX ) |
| 848 |
? self::DB_PRIMARY |
| 849 |
: self::DB_REPLICA; |
| 850 |
|
| 851 |
return new DBConnRef( $this, [ $i, $groups, $domain, $flags ], $role, $this->modcount ); |
| 852 |
} |
| 853 |
|
| 854 |
|
| 855 |
|
| 856 |
|
| 857 |
|
| 858 |
|
| 859 |
|
| 860 |
|
| 861 |
|
| 862 |
|
| 863 |
|
| 864 |
|
| 865 |
|
| 866 |
|
| 867 |
|
| 868 |
|
| 869 |
|
| 870 |
private function reuseOrOpenConnectionForNewRef( $i, DatabaseDomain $domain, $flags = 0 ) { |
| 871 |
|
| 872 |
if ( $this->fieldHasBit( $flags, self::CONN_UNTRACKED_GAUGE ) ) { |
| 873 |
|
| 874 |
$category = self::CATEGORY_GAUGE; |
| 875 |
} elseif ( self::fieldHasBit( $flags, self::CONN_TRX_AUTOCOMMIT ) ) { |
| 876 |
|
| 877 |
$category = self::CATEGORY_AUTOCOMMIT; |
| 878 |
} else { |
| 879 |
|
| 880 |
$category = self::CATEGORY_ROUND; |
| 881 |
} |
| 882 |
|
| 883 |
$conn = null; |
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
foreach ( ( $this->conns[$category][$i] ?? [] ) as $poolConn ) { |
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
$isShareable = !( |
| 894 |
$poolConn->databasesAreIndependent() && |
| 895 |
$domain->getDatabase() !== null && |
| 896 |
$domain->getDatabase() !== $poolConn->getDBname() |
| 897 |
); |
| 898 |
if ( $isShareable ) { |
| 899 |
$conn = $poolConn; |
| 900 |
|
| 901 |
if ( !$domain->isUnspecified() ) { |
| 902 |
$conn->selectDomain( $domain ); |
| 903 |
} |
| 904 |
$this->logger->debug( __METHOD__ . ": reusing connection for $i/$domain" ); |
| 905 |
break; |
| 906 |
} |
| 907 |
} |
| 908 |
|
| 909 |
|
| 910 |
if ( !$conn ) { |
| 911 |
$conn = $this->reallyOpenConnection( |
| 912 |
$i, |
| 913 |
$domain, |
| 914 |
[ self::INFO_CONN_CATEGORY => $category ] |
| 915 |
); |
| 916 |
if ( $conn->isOpen() ) { |
| 917 |
|
| 918 |
|
| 919 |
|
| 920 |
if ( $i === ServerInfo::WRITER_INDEX ) { |
| 921 |
if ( $this->readOnlyReason !== false ) { |
| 922 |
$readOnlyReason = $this->readOnlyReason; |
| 923 |
} elseif ( $this->isPrimaryRunningReadOnly( $conn ) ) { |
| 924 |
$readOnlyReason = 'The primary database server is running in read-only mode.'; |
| 925 |
} else { |
| 926 |
$readOnlyReason = false; |
| 927 |
} |
| 928 |
$conn->setLBInfo( $conn::LB_READ_ONLY_REASON, $readOnlyReason ); |
| 929 |
} |
| 930 |
|
| 931 |
if ( isset( $this->conns[$category] ) ) { |
| 932 |
|
| 933 |
$this->conns[$category][$i][] = $conn; |
| 934 |
} |
| 935 |
} else { |
| 936 |
$this->logger->warning( __METHOD__ . ": connection error for $i/$domain" ); |
| 937 |
$this->lastErrorConn = $conn; |
| 938 |
$conn = null; |
| 939 |
} |
| 940 |
} |
| 941 |
|
| 942 |
if ( $conn instanceof IDatabaseForOwner ) { |
| 943 |
|
| 944 |
$this->assertConnectionDomain( $conn, $domain ); |
| 945 |
|
| 946 |
$this->enforceConnectionFlags( $conn, $flags ); |
| 947 |
} |
| 948 |
|
| 949 |
return $conn; |
| 950 |
} |
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
private function assertConnectionDomain( Database $conn, DatabaseDomain $domain ) { |
| 960 |
if ( !$domain->isCompatible( $conn->getDomainID() ) ) { |
| 961 |
throw new UnexpectedValueException( |
| 962 |
"Got connection to '{$conn->getDomainID()}', but expected one for '{$domain}'" |
| 963 |
); |
| 964 |
} |
| 965 |
} |
| 966 |
|
| 967 |
public function getServerAttributes( $i ) { |
| 968 |
return $this->databaseFactory->attributesFromType( |
| 969 |
$this->getServerType( $i ), |
| 970 |
$this->serverInfo->getServerDriver( $i ) |
| 971 |
); |
| 972 |
} |
| 973 |
|
| 974 |
|
| 975 |
|
| 976 |
|
| 977 |
|
| 978 |
|
| 979 |
|
| 980 |
|
| 981 |
|
| 982 |
|
| 983 |
|
| 984 |
|
| 985 |
|
| 986 |
protected function reallyOpenConnection( $i, DatabaseDomain $domain, array $lbInfo ) { |
| 987 |
if ( $this->disabled ) { |
| 988 |
throw new DBAccessError(); |
| 989 |
} |
| 990 |
|
| 991 |
$server = $this->serverInfo->getServerInfoStrict( $i ); |
| 992 |
if ( $lbInfo[self::INFO_CONN_CATEGORY] === self::CATEGORY_GAUGE ) { |
| 993 |
|
| 994 |
|
| 995 |
|
| 996 |
$server['connectTimeout'] = min( 1, $server['connectTimeout'] ?? INF ); |
| 997 |
$server['receiveTimeout'] = min( 1, $server['receiveTimeout'] ?? INF ); |
| 998 |
|
| 999 |
|
| 1000 |
|
| 1001 |
$server['flags'] ??= 0; |
| 1002 |
$server['flags'] &= ~IDatabase::DBO_DEFAULT; |
| 1003 |
$server['flags'] |= IDatabase::DBO_GAUGE; |
| 1004 |
} else { |
| 1005 |
|
| 1006 |
$server['flags'] ??= IDatabase::DBO_DEFAULT; |
| 1007 |
} |
| 1008 |
|
| 1009 |
if ( !empty( $server['is static'] ) ) { |
| 1010 |
$topologyRole = IDatabase::ROLE_STATIC_CLONE; |
| 1011 |
} else { |
| 1012 |
$topologyRole = ( $i === ServerInfo::WRITER_INDEX ) |
| 1013 |
? IDatabase::ROLE_STREAMING_MASTER |
| 1014 |
: IDatabase::ROLE_STREAMING_REPLICA; |
| 1015 |
} |
| 1016 |
|
| 1017 |
$conn = $this->databaseFactory->create( |
| 1018 |
$server['type'], |
| 1019 |
array_merge( $server, [ |
| 1020 |
|
| 1021 |
'topologyRole' => $topologyRole, |
| 1022 |
|
| 1023 |
|
| 1024 |
|
| 1025 |
'dbname' => $this->getServerAttributes( $i )[Database::ATTR_DB_IS_FILE] |
| 1026 |
? ( $domain->getDatabase() ?? $server['dbname'] ?? null ) |
| 1027 |
: $domain->getDatabase(), |
| 1028 |
|
| 1029 |
'schema' => $domain->getSchema(), |
| 1030 |
|
| 1031 |
'tablePrefix' => $domain->getTablePrefix(), |
| 1032 |
'srvCache' => $this->srvCache, |
| 1033 |
'logger' => $this->logger, |
| 1034 |
'errorLogger' => $this->errorLogger, |
| 1035 |
'trxProfiler' => $this->trxProfiler, |
| 1036 |
'lbInfo' => [ self::INFO_SERVER_INDEX => $i ] + $lbInfo |
| 1037 |
] ), |
| 1038 |
Database::NEW_UNCONNECTED |
| 1039 |
); |
| 1040 |
|
| 1041 |
$conn->setTableAliases( $this->tableAliases ); |
| 1042 |
$conn->setIndexAliases( $this->indexAliases ); |
| 1043 |
|
| 1044 |
if ( $i === ServerInfo::WRITER_INDEX ) { |
| 1045 |
if ( $this->trxRoundId !== false ) { |
| 1046 |
$this->applyTransactionRoundFlags( $conn ); |
| 1047 |
} |
| 1048 |
foreach ( $this->trxRecurringCallbacks as $name => $callback ) { |
| 1049 |
$conn->setTransactionListener( $name, $callback ); |
| 1050 |
} |
| 1051 |
} |
| 1052 |
|
| 1053 |
|
| 1054 |
try { |
| 1055 |
$conn->initConnection(); |
| 1056 |
++$this->connectionCounter; |
| 1057 |
} catch ( DBConnectionError $e ) { |
| 1058 |
$this->lastErrorConn = $conn; |
| 1059 |
|
| 1060 |
} |
| 1061 |
|
| 1062 |
if ( $conn->isOpen() ) { |
| 1063 |
$this->logger->debug( __METHOD__ . ": opened new connection for $i/$domain" ); |
| 1064 |
} else { |
| 1065 |
$this->logger->warning( |
| 1066 |
__METHOD__ . ": connection error for $i/{db_domain}", |
| 1067 |
[ 'db_domain' => $domain->getId() ] |
| 1068 |
); |
| 1069 |
} |
| 1070 |
|
| 1071 |
|
| 1072 |
$count = 0; |
| 1073 |
foreach ( $this->conns as $poolConnsByServer ) { |
| 1074 |
foreach ( $poolConnsByServer as $serverConns ) { |
| 1075 |
$count += count( $serverConns ); |
| 1076 |
} |
| 1077 |
} |
| 1078 |
if ( $count >= self::CONN_HELD_WARN_THRESHOLD ) { |
| 1079 |
$this->logger->warning( |
| 1080 |
__METHOD__ . ": {connections}+ connections made (primary={primarydb})", |
| 1081 |
$this->getConnLogContext( |
| 1082 |
$conn, |
| 1083 |
[ |
| 1084 |
'connections' => $count, |
| 1085 |
'primarydb' => $this->serverInfo->getPrimaryServerName(), |
| 1086 |
'db_domain' => $domain->getId() |
| 1087 |
] |
| 1088 |
) |
| 1089 |
); |
| 1090 |
} |
| 1091 |
|
| 1092 |
$this->assertConnectionDomain( $conn, $domain ); |
| 1093 |
|
| 1094 |
return $conn; |
| 1095 |
} |
| 1096 |
|
| 1097 |
|
| 1098 |
|
| 1099 |
|
| 1100 |
|
| 1101 |
|
| 1102 |
|
| 1103 |
|
| 1104 |
|
| 1105 |
|
| 1106 |
private function loadSessionPrimaryPos() { |
| 1107 |
if ( !$this->chronologyProtectorCalled && $this->chronologyProtector ) { |
| 1108 |
$this->chronologyProtectorCalled = true; |
| 1109 |
$pos = $this->chronologyProtector->getSessionPrimaryPos( $this ); |
| 1110 |
$this->logger->debug( __METHOD__ . ': executed chronology callback.' ); |
| 1111 |
if ( $pos ) { |
| 1112 |
if ( !$this->waitForPos || $pos->hasReached( $this->waitForPos ) ) { |
| 1113 |
$this->waitForPos = $pos; |
| 1114 |
} |
| 1115 |
} |
| 1116 |
} |
| 1117 |
} |
| 1118 |
|
| 1119 |
|
| 1120 |
|
| 1121 |
|
| 1122 |
|
| 1123 |
|
| 1124 |
private function reportConnectionError( $extraLbError = '' ) { |
| 1125 |
if ( $this->lastErrorConn instanceof IDatabaseForOwner ) { |
| 1126 |
$srvName = $this->lastErrorConn->getServerName(); |
| 1127 |
$lastDbError = $this->lastErrorConn->lastError() ?: 'unknown error'; |
| 1128 |
|
| 1129 |
$exception = new DBConnectionError( |
| 1130 |
$this->lastErrorConn, |
| 1131 |
$extraLbError |
| 1132 |
? "{$extraLbError}; {$lastDbError} ({$srvName})" |
| 1133 |
: "{$lastDbError} ({$srvName})" |
| 1134 |
); |
| 1135 |
|
| 1136 |
if ( $extraLbError ) { |
| 1137 |
$this->logger->warning( |
| 1138 |
__METHOD__ . ": $extraLbError; {last_error} ({db_server})", |
| 1139 |
$this->getConnLogContext( |
| 1140 |
$this->lastErrorConn, |
| 1141 |
[ |
| 1142 |
'method' => __METHOD__, |
| 1143 |
'last_error' => $lastDbError |
| 1144 |
] |
| 1145 |
) |
| 1146 |
); |
| 1147 |
} |
| 1148 |
} else { |
| 1149 |
$exception = new DBConnectionError( |
| 1150 |
null, |
| 1151 |
$extraLbError ?: 'could not connect to the DB server' |
| 1152 |
); |
| 1153 |
|
| 1154 |
if ( $extraLbError ) { |
| 1155 |
$this->logger->error( |
| 1156 |
__METHOD__ . ": $extraLbError", |
| 1157 |
[ |
| 1158 |
'method' => __METHOD__, |
| 1159 |
'last_error' => '(last connection error missing)' |
| 1160 |
] |
| 1161 |
); |
| 1162 |
} |
| 1163 |
} |
| 1164 |
|
| 1165 |
throw $exception; |
| 1166 |
} |
| 1167 |
|
| 1168 |
public function getServerCount() { |
| 1169 |
return $this->serverInfo->getServerCount(); |
| 1170 |
} |
| 1171 |
|
| 1172 |
public function hasReplicaServers() { |
| 1173 |
return $this->serverInfo->hasReplicaServers(); |
| 1174 |
} |
| 1175 |
|
| 1176 |
public function hasStreamingReplicaServers() { |
| 1177 |
return $this->serverInfo->hasStreamingReplicaServers(); |
| 1178 |
} |
| 1179 |
|
| 1180 |
public function getServerName( $i ): string { |
| 1181 |
return $this->serverInfo->getServerName( $i ); |
| 1182 |
} |
| 1183 |
|
| 1184 |
public function getServerInfo( $i ) { |
| 1185 |
return $this->serverInfo->getServerInfo( $i ); |
| 1186 |
} |
| 1187 |
|
| 1188 |
public function getServerType( $i ) { |
| 1189 |
return $this->serverInfo->getServerType( $i ); |
| 1190 |
} |
| 1191 |
|
| 1192 |
public function getPrimaryPos() { |
| 1193 |
$conn = $this->getAnyOpenConnection( ServerInfo::WRITER_INDEX ); |
| 1194 |
if ( $conn ) { |
| 1195 |
return $conn->getPrimaryPos(); |
| 1196 |
} |
| 1197 |
|
| 1198 |
$conn = $this->getConnectionInternal( ServerInfo::WRITER_INDEX, self::CONN_SILENCE_ERRORS ); |
| 1199 |
|
| 1200 |
if ( !$conn ) { |
| 1201 |
$this->reportConnectionError(); |
| 1202 |
} |
| 1203 |
|
| 1204 |
|
| 1205 |
|
| 1206 |
'@phan-var IDatabaseForOwner $conn'; |
| 1207 |
try { |
| 1208 |
return $conn->getPrimaryPos(); |
| 1209 |
} finally { |
| 1210 |
$this->closeConnection( $conn ); |
| 1211 |
} |
| 1212 |
} |
| 1213 |
|
| 1214 |
|
| 1215 |
|
| 1216 |
|
| 1217 |
|
| 1218 |
|
| 1219 |
|
| 1220 |
|
| 1221 |
|
| 1222 |
|
| 1223 |
|
| 1224 |
|
| 1225 |
|
| 1226 |
|
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
|
| 1231 |
|
| 1232 |
|
| 1233 |
|
| 1234 |
public function reconfigure( array $params ) { |
| 1235 |
$anyServerDepooled = false; |
| 1236 |
|
| 1237 |
$paramServers = $params['servers']; |
| 1238 |
$newIndexByServerIndex = $this->serverInfo->reconfigureServers( $paramServers ); |
| 1239 |
foreach ( $newIndexByServerIndex as $i => $ni ) { |
| 1240 |
if ( $ni !== null ) { |
| 1241 |
|
| 1242 |
$newWeightByGroup = $paramServers[$ni]['groupLoads'] ?? []; |
| 1243 |
$newWeightByGroup[ILoadBalancer::GROUP_GENERIC] = $paramServers[$ni]['load']; |
| 1244 |
|
| 1245 |
foreach ( $this->groupLoads as $group => $weightByIndex ) { |
| 1246 |
if ( isset( $weightByIndex[$i] ) && !isset( $newWeightByGroup[$group] ) ) { |
| 1247 |
|
| 1248 |
$anyServerDepooled = true; |
| 1249 |
unset( $this->groupLoads[$group][$i] ); |
| 1250 |
} |
| 1251 |
} |
| 1252 |
} else { |
| 1253 |
|
| 1254 |
$anyServerDepooled = true; |
| 1255 |
|
| 1256 |
|
| 1257 |
foreach ( $this->groupLoads as $group => $loads ) { |
| 1258 |
unset( $this->groupLoads[$group][$i] ); |
| 1259 |
} |
| 1260 |
} |
| 1261 |
} |
| 1262 |
|
| 1263 |
if ( $anyServerDepooled ) { |
| 1264 |
|
| 1265 |
|
| 1266 |
|
| 1267 |
|
| 1268 |
$this->logger->info( 'Reconfiguring dbs!' ); |
| 1269 |
|
| 1270 |
$this->readIndexByGroup = []; |
| 1271 |
|
| 1272 |
|
| 1273 |
|
| 1274 |
$this->conns = self::newTrackedConnectionsArray(); |
| 1275 |
|
| 1276 |
|
| 1277 |
|
| 1278 |
$this->modcount++; |
| 1279 |
} |
| 1280 |
} |
| 1281 |
|
| 1282 |
public function disable( $fname = __METHOD__ ) { |
| 1283 |
$this->closeAll( $fname ); |
| 1284 |
$this->disabled = true; |
| 1285 |
} |
| 1286 |
|
| 1287 |
public function closeAll( $fname = __METHOD__ ) { |
| 1288 |
|
| 1289 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1290 |
foreach ( $this->getOpenConnections() as $conn ) { |
| 1291 |
$conn->close( $fname ); |
| 1292 |
} |
| 1293 |
|
| 1294 |
$this->conns = self::newTrackedConnectionsArray(); |
| 1295 |
} |
| 1296 |
|
| 1297 |
|
| 1298 |
|
| 1299 |
|
| 1300 |
|
| 1301 |
|
| 1302 |
|
| 1303 |
|
| 1304 |
|
| 1305 |
private function closeConnection( IDatabaseForOwner $conn ) { |
| 1306 |
if ( $conn instanceof DBConnRef ) { |
| 1307 |
|
| 1308 |
throw new RuntimeException( 'Cannot close DBConnRef instance; it must be shareable' ); |
| 1309 |
} |
| 1310 |
|
| 1311 |
$domain = $conn->getDomainID(); |
| 1312 |
$serverIndex = $conn->getLBInfo( self::INFO_SERVER_INDEX ); |
| 1313 |
if ( $serverIndex === null ) { |
| 1314 |
throw new UnexpectedValueException( "Handle on '$domain' missing server index" ); |
| 1315 |
} |
| 1316 |
|
| 1317 |
$srvName = $this->serverInfo->getServerName( $serverIndex ); |
| 1318 |
|
| 1319 |
$found = false; |
| 1320 |
foreach ( $this->conns as $type => $poolConnsByServer ) { |
| 1321 |
$key = array_search( $conn, $poolConnsByServer[$serverIndex] ?? [], true ); |
| 1322 |
if ( $key !== false ) { |
| 1323 |
$found = true; |
| 1324 |
unset( $this->conns[$type][$serverIndex][$key] ); |
| 1325 |
} |
| 1326 |
} |
| 1327 |
|
| 1328 |
if ( !$found ) { |
| 1329 |
$this->logger->warning( |
| 1330 |
__METHOD__ . |
| 1331 |
": orphaned connection to database {$this->stringifyConn( $conn )} at '$srvName'." |
| 1332 |
); |
| 1333 |
} |
| 1334 |
|
| 1335 |
$this->logger->debug( |
| 1336 |
__METHOD__ . |
| 1337 |
": closing connection to database {$this->stringifyConn( $conn )} at '$srvName'." |
| 1338 |
); |
| 1339 |
|
| 1340 |
$conn->close( __METHOD__ ); |
| 1341 |
} |
| 1342 |
|
| 1343 |
public function finalizePrimaryChanges( $fname = __METHOD__ ) { |
| 1344 |
$this->assertTransactionRoundStage( [ self::ROUND_CURSORY, self::ROUND_FINALIZED ] ); |
| 1345 |
|
| 1346 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1347 |
|
| 1348 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1349 |
|
| 1350 |
$total = 0; |
| 1351 |
do { |
| 1352 |
$count = 0; |
| 1353 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1354 |
|
| 1355 |
|
| 1356 |
$count += $conn->runOnTransactionPreCommitCallbacks(); |
| 1357 |
} |
| 1358 |
$total += $count; |
| 1359 |
} while ( $count > 0 ); |
| 1360 |
|
| 1361 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1362 |
$conn->setTrxEndCallbackSuppression( true ); |
| 1363 |
} |
| 1364 |
$this->trxRoundStage = self::ROUND_FINALIZED; |
| 1365 |
|
| 1366 |
return $total; |
| 1367 |
} |
| 1368 |
|
| 1369 |
public function approvePrimaryChanges( int $maxWriteDuration, $fname = __METHOD__ ) { |
| 1370 |
$this->assertTransactionRoundStage( self::ROUND_FINALIZED ); |
| 1371 |
|
| 1372 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1373 |
|
| 1374 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1375 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1376 |
|
| 1377 |
|
| 1378 |
if ( $conn->explicitTrxActive() ) { |
| 1379 |
throw new DBTransactionError( |
| 1380 |
$conn, |
| 1381 |
"Explicit transaction still active; a caller might have failed to call " . |
| 1382 |
"endAtomic() or cancelAtomic()." |
| 1383 |
); |
| 1384 |
} |
| 1385 |
|
| 1386 |
|
| 1387 |
$time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY ); |
| 1388 |
if ( $maxWriteDuration > 0 ) { |
| 1389 |
if ( $time > $maxWriteDuration ) { |
| 1390 |
$humanTimeSec = round( $time, 3 ); |
| 1391 |
throw new DBTransactionSizeError( |
| 1392 |
$conn, |
| 1393 |
"Transaction spent {time}s in writes, exceeding the {$maxWriteDuration}s limit", |
| 1394 |
|
| 1395 |
[ $time, $maxWriteDuration ], |
| 1396 |
null, |
| 1397 |
[ 'time' => $humanTimeSec ] |
| 1398 |
); |
| 1399 |
} elseif ( $time > 0 ) { |
| 1400 |
$timeMs = $time * 1000; |
| 1401 |
$humanTimeMs = round( $timeMs, $timeMs > 1 ? 0 : 3 ); |
| 1402 |
$this->logger->debug( |
| 1403 |
"Transaction spent {time_ms}ms in writes, under the {$maxWriteDuration}s limit", |
| 1404 |
[ 'time_ms' => $humanTimeMs ] |
| 1405 |
); |
| 1406 |
} |
| 1407 |
} |
| 1408 |
|
| 1409 |
|
| 1410 |
|
| 1411 |
if ( $conn->writesOrCallbacksPending() || $conn->sessionLocksPending() ) { |
| 1412 |
if ( !$conn->ping() ) { |
| 1413 |
throw new DBTransactionError( |
| 1414 |
$conn, |
| 1415 |
"Pre-commit ping failed on server {$conn->getServerName()}" |
| 1416 |
); |
| 1417 |
} |
| 1418 |
} |
| 1419 |
} |
| 1420 |
$this->trxRoundStage = self::ROUND_APPROVED; |
| 1421 |
} |
| 1422 |
|
| 1423 |
public function beginPrimaryChanges( $fname = __METHOD__ ) { |
| 1424 |
if ( $this->trxRoundId !== false ) { |
| 1425 |
throw new DBTransactionError( |
| 1426 |
null, |
| 1427 |
"Transaction round '{$this->trxRoundId}' already started" |
| 1428 |
); |
| 1429 |
} |
| 1430 |
$this->assertTransactionRoundStage( self::ROUND_CURSORY ); |
| 1431 |
|
| 1432 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1433 |
|
| 1434 |
|
| 1435 |
$this->flushPrimarySnapshots( $fname ); |
| 1436 |
|
| 1437 |
$this->trxRoundId = $fname; |
| 1438 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1439 |
|
| 1440 |
|
| 1441 |
|
| 1442 |
|
| 1443 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1444 |
$this->applyTransactionRoundFlags( $conn ); |
| 1445 |
} |
| 1446 |
$this->trxRoundStage = self::ROUND_CURSORY; |
| 1447 |
} |
| 1448 |
|
| 1449 |
public function commitPrimaryChanges( $fname = __METHOD__ ) { |
| 1450 |
$this->assertTransactionRoundStage( self::ROUND_APPROVED ); |
| 1451 |
|
| 1452 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1453 |
|
| 1454 |
$failures = []; |
| 1455 |
|
| 1456 |
$restore = ( $this->trxRoundId !== false ); |
| 1457 |
$this->trxRoundId = false; |
| 1458 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1459 |
|
| 1460 |
|
| 1461 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1462 |
try { |
| 1463 |
$conn->commit( $fname, $conn::FLUSHING_ALL_PEERS ); |
| 1464 |
} catch ( DBError $e ) { |
| 1465 |
( $this->errorLogger )( $e ); |
| 1466 |
$failures[] = "{$conn->getServerName()}: {$e->getMessage()}"; |
| 1467 |
} |
| 1468 |
} |
| 1469 |
if ( $failures ) { |
| 1470 |
throw new DBTransactionError( |
| 1471 |
null, |
| 1472 |
"Commit failed on server(s) " . implode( "\n", array_unique( $failures ) ) |
| 1473 |
); |
| 1474 |
} |
| 1475 |
if ( $restore ) { |
| 1476 |
|
| 1477 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1478 |
$this->undoTransactionRoundFlags( $conn ); |
| 1479 |
} |
| 1480 |
} |
| 1481 |
$this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS; |
| 1482 |
} |
| 1483 |
|
| 1484 |
public function runPrimaryTransactionIdleCallbacks( $fname = __METHOD__ ) { |
| 1485 |
if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) { |
| 1486 |
$type = IDatabase::TRIGGER_COMMIT; |
| 1487 |
} elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) { |
| 1488 |
$type = IDatabase::TRIGGER_ROLLBACK; |
| 1489 |
} else { |
| 1490 |
throw new DBTransactionError( |
| 1491 |
null, |
| 1492 |
"Transaction should be in the callback stage (not '{$this->trxRoundStage}')" |
| 1493 |
); |
| 1494 |
} |
| 1495 |
|
| 1496 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1497 |
|
| 1498 |
$oldStage = $this->trxRoundStage; |
| 1499 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1500 |
|
| 1501 |
|
| 1502 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1503 |
$conn->setTrxEndCallbackSuppression( false ); |
| 1504 |
} |
| 1505 |
|
| 1506 |
$errors = []; |
| 1507 |
$fname = __METHOD__; |
| 1508 |
|
| 1509 |
do { |
| 1510 |
|
| 1511 |
$count = 0; |
| 1512 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1513 |
if ( $conn->trxLevel() ) { |
| 1514 |
continue; |
| 1515 |
} |
| 1516 |
$count += $conn->runOnTransactionIdleCallbacks( $type, $errors ); |
| 1517 |
} |
| 1518 |
|
| 1519 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1520 |
if ( $conn->writesPending() ) { |
| 1521 |
|
| 1522 |
$fnames = implode( ', ', $conn->pendingWriteCallers() ); |
| 1523 |
$this->logger->info( |
| 1524 |
"$fname: found writes pending ($fnames).", |
| 1525 |
$this->getConnLogContext( |
| 1526 |
$conn, |
| 1527 |
[ 'exception' => new RuntimeException() ] |
| 1528 |
) |
| 1529 |
); |
| 1530 |
} elseif ( $conn->trxLevel() ) { |
| 1531 |
|
| 1532 |
|
| 1533 |
$this->logger->debug( "$fname: found empty transaction." ); |
| 1534 |
} |
| 1535 |
try { |
| 1536 |
$conn->commit( $fname, $conn::FLUSHING_ALL_PEERS ); |
| 1537 |
} catch ( DBError $ex ) { |
| 1538 |
$errors[] = $ex; |
| 1539 |
} |
| 1540 |
} |
| 1541 |
} while ( $count > 0 ); |
| 1542 |
|
| 1543 |
$this->trxRoundStage = $oldStage; |
| 1544 |
|
| 1545 |
return $errors[0] ?? null; |
| 1546 |
} |
| 1547 |
|
| 1548 |
public function runPrimaryTransactionListenerCallbacks( $fname = __METHOD__ ) { |
| 1549 |
if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) { |
| 1550 |
$type = IDatabase::TRIGGER_COMMIT; |
| 1551 |
} elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) { |
| 1552 |
$type = IDatabase::TRIGGER_ROLLBACK; |
| 1553 |
} else { |
| 1554 |
throw new DBTransactionError( |
| 1555 |
null, |
| 1556 |
"Transaction should be in the callback stage (not '{$this->trxRoundStage}')" |
| 1557 |
); |
| 1558 |
} |
| 1559 |
|
| 1560 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1561 |
|
| 1562 |
$errors = []; |
| 1563 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1564 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1565 |
$conn->runTransactionListenerCallbacks( $type, $errors ); |
| 1566 |
} |
| 1567 |
$this->trxRoundStage = self::ROUND_CURSORY; |
| 1568 |
|
| 1569 |
return $errors[0] ?? null; |
| 1570 |
} |
| 1571 |
|
| 1572 |
public function rollbackPrimaryChanges( $fname = __METHOD__ ) { |
| 1573 |
|
| 1574 |
$scope = ScopedCallback::newScopedIgnoreUserAbort(); |
| 1575 |
|
| 1576 |
$restore = ( $this->trxRoundId !== false ); |
| 1577 |
$this->trxRoundId = false; |
| 1578 |
$this->trxRoundStage = self::ROUND_ERROR; |
| 1579 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1580 |
$conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS ); |
| 1581 |
} |
| 1582 |
if ( $restore ) { |
| 1583 |
|
| 1584 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1585 |
$this->undoTransactionRoundFlags( $conn ); |
| 1586 |
} |
| 1587 |
} |
| 1588 |
$this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS; |
| 1589 |
} |
| 1590 |
|
| 1591 |
public function flushPrimarySessions( $fname = __METHOD__ ) { |
| 1592 |
$this->assertTransactionRoundStage( [ self::ROUND_CURSORY ] ); |
| 1593 |
if ( $this->hasPrimaryChanges() ) { |
| 1594 |
|
| 1595 |
throw new DBTransactionError( null, "Cannot reset session while writes are pending" ); |
| 1596 |
} |
| 1597 |
|
| 1598 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1599 |
$conn->flushSession( $fname, $conn::FLUSHING_ALL_PEERS ); |
| 1600 |
} |
| 1601 |
} |
| 1602 |
|
| 1603 |
|
| 1604 |
|
| 1605 |
|
| 1606 |
|
| 1607 |
private function assertTransactionRoundStage( $stage ) { |
| 1608 |
$stages = (array)$stage; |
| 1609 |
|
| 1610 |
if ( !in_array( $this->trxRoundStage, $stages, true ) ) { |
| 1611 |
$stageList = implode( |
| 1612 |
'/', |
| 1613 |
array_map( static function ( $v ) { |
| 1614 |
return "'$v'"; |
| 1615 |
}, $stages ) |
| 1616 |
); |
| 1617 |
$transactionName = $this->trxRoundId ?: '<unknown>'; |
| 1618 |
throw new DBTransactionError( |
| 1619 |
null, |
| 1620 |
"Transaction '$transactionName' round stage must be '$stageList' (not '{$this->trxRoundStage}')" |
| 1621 |
); |
| 1622 |
} |
| 1623 |
} |
| 1624 |
|
| 1625 |
|
| 1626 |
|
| 1627 |
|
| 1628 |
|
| 1629 |
|
| 1630 |
|
| 1631 |
|
| 1632 |
|
| 1633 |
|
| 1634 |
private function applyTransactionRoundFlags( Database $conn ) { |
| 1635 |
if ( $conn->getLBInfo( self::INFO_CONN_CATEGORY ) !== self::CATEGORY_ROUND ) { |
| 1636 |
return; |
| 1637 |
} |
| 1638 |
|
| 1639 |
if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) { |
| 1640 |
|
| 1641 |
|
| 1642 |
$conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR ); |
| 1643 |
} |
| 1644 |
|
| 1645 |
if ( $conn->getFlag( $conn::DBO_TRX ) ) { |
| 1646 |
$conn->setLBInfo( $conn::LB_TRX_ROUND_ID, $this->trxRoundId ); |
| 1647 |
} |
| 1648 |
} |
| 1649 |
|
| 1650 |
|
| 1651 |
|
| 1652 |
|
| 1653 |
private function undoTransactionRoundFlags( Database $conn ) { |
| 1654 |
if ( $conn->getLBInfo( self::INFO_CONN_CATEGORY ) !== self::CATEGORY_ROUND ) { |
| 1655 |
return; |
| 1656 |
} |
| 1657 |
|
| 1658 |
if ( $conn->getFlag( $conn::DBO_TRX ) ) { |
| 1659 |
$conn->setLBInfo( $conn::LB_TRX_ROUND_ID, null ); |
| 1660 |
} |
| 1661 |
|
| 1662 |
if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) { |
| 1663 |
$conn->restoreFlags( $conn::RESTORE_PRIOR ); |
| 1664 |
} |
| 1665 |
} |
| 1666 |
|
| 1667 |
public function flushReplicaSnapshots( $fname = __METHOD__ ) { |
| 1668 |
foreach ( $this->conns as $poolConnsByServer ) { |
| 1669 |
foreach ( $poolConnsByServer as $serverIndex => $serverConns ) { |
| 1670 |
if ( $serverIndex === ServerInfo::WRITER_INDEX ) { |
| 1671 |
continue; |
| 1672 |
} |
| 1673 |
foreach ( $serverConns as $conn ) { |
| 1674 |
$conn->flushSnapshot( $fname ); |
| 1675 |
} |
| 1676 |
} |
| 1677 |
} |
| 1678 |
} |
| 1679 |
|
| 1680 |
public function flushPrimarySnapshots( $fname = __METHOD__ ) { |
| 1681 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1682 |
$conn->flushSnapshot( $fname ); |
| 1683 |
} |
| 1684 |
} |
| 1685 |
|
| 1686 |
public function hasPrimaryConnection() { |
| 1687 |
return (bool)$this->getAnyOpenConnection( ServerInfo::WRITER_INDEX ); |
| 1688 |
} |
| 1689 |
|
| 1690 |
public function hasPrimaryChanges() { |
| 1691 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1692 |
if ( $conn->writesOrCallbacksPending() ) { |
| 1693 |
return true; |
| 1694 |
} |
| 1695 |
} |
| 1696 |
|
| 1697 |
return false; |
| 1698 |
} |
| 1699 |
|
| 1700 |
public function lastPrimaryChangeTimestamp() { |
| 1701 |
$lastTime = false; |
| 1702 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1703 |
$lastTime = max( $lastTime, $conn->lastDoneWrites() ); |
| 1704 |
} |
| 1705 |
|
| 1706 |
return $lastTime; |
| 1707 |
} |
| 1708 |
|
| 1709 |
public function hasOrMadeRecentPrimaryChanges( $age = null ) { |
| 1710 |
$age ??= self::MAX_WAIT_DEFAULT; |
| 1711 |
|
| 1712 |
return ( $this->hasPrimaryChanges() |
| 1713 |
|| $this->lastPrimaryChangeTimestamp() > microtime( true ) - $age ); |
| 1714 |
} |
| 1715 |
|
| 1716 |
public function pendingPrimaryChangeCallers() { |
| 1717 |
$fnames = []; |
| 1718 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1719 |
$fnames = array_merge( $fnames, $conn->pendingWriteCallers() ); |
| 1720 |
} |
| 1721 |
|
| 1722 |
return $fnames; |
| 1723 |
} |
| 1724 |
|
| 1725 |
public function explicitTrxActive() { |
| 1726 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1727 |
if ( $conn->explicitTrxActive() ) { |
| 1728 |
return true; |
| 1729 |
} |
| 1730 |
} |
| 1731 |
return false; |
| 1732 |
} |
| 1733 |
|
| 1734 |
private function setLaggedReplicaMode(): void { |
| 1735 |
$this->laggedReplicaMode = true; |
| 1736 |
$this->logger->warning( __METHOD__ . ": setting lagged replica mode" ); |
| 1737 |
} |
| 1738 |
|
| 1739 |
public function laggedReplicaUsed() { |
| 1740 |
return $this->laggedReplicaMode; |
| 1741 |
} |
| 1742 |
|
| 1743 |
public function getReadOnlyReason() { |
| 1744 |
if ( $this->readOnlyReason !== false ) { |
| 1745 |
return $this->readOnlyReason; |
| 1746 |
} elseif ( $this->isPrimaryRunningReadOnly() ) { |
| 1747 |
return 'The primary database server is running in read-only mode.'; |
| 1748 |
} |
| 1749 |
|
| 1750 |
return false; |
| 1751 |
} |
| 1752 |
|
| 1753 |
|
| 1754 |
|
| 1755 |
|
| 1756 |
|
| 1757 |
|
| 1758 |
private function isPrimaryRunningReadOnly( ?IDatabaseForOwner $conn = null ) { |
| 1759 |
|
| 1760 |
return (bool)$this->wanCache->getWithSetCallback( |
| 1761 |
|
| 1762 |
$this->wanCache->makeGlobalKey( |
| 1763 |
'rdbms-server-readonly', |
| 1764 |
$this->serverInfo->getPrimaryServerName() |
| 1765 |
), |
| 1766 |
self::TTL_CACHE_READONLY, |
| 1767 |
function ( $oldValue ) use ( $conn ) { |
| 1768 |
$scope = $this->trxProfiler->silenceForScope(); |
| 1769 |
$conn ??= $this->getServerConnection( |
| 1770 |
ServerInfo::WRITER_INDEX, |
| 1771 |
self::DOMAIN_ANY, |
| 1772 |
self::CONN_SILENCE_ERRORS |
| 1773 |
); |
| 1774 |
if ( $conn ) { |
| 1775 |
try { |
| 1776 |
$value = (int)$conn->serverIsReadOnly(); |
| 1777 |
} catch ( DBError $e ) { |
| 1778 |
$value = is_int( $oldValue ) ? $oldValue : 0; |
| 1779 |
} |
| 1780 |
} else { |
| 1781 |
$value = 0; |
| 1782 |
} |
| 1783 |
ScopedCallback::consume( $scope ); |
| 1784 |
|
| 1785 |
return $value; |
| 1786 |
}, |
| 1787 |
[ |
| 1788 |
'busyValue' => 0, |
| 1789 |
'pcTTL' => WANObjectCache::TTL_PROC_LONG |
| 1790 |
] |
| 1791 |
); |
| 1792 |
} |
| 1793 |
|
| 1794 |
public function pingAll() { |
| 1795 |
$success = true; |
| 1796 |
foreach ( $this->getOpenConnections() as $conn ) { |
| 1797 |
if ( !$conn->ping() ) { |
| 1798 |
$success = false; |
| 1799 |
} |
| 1800 |
} |
| 1801 |
|
| 1802 |
return $success; |
| 1803 |
} |
| 1804 |
|
| 1805 |
|
| 1806 |
|
| 1807 |
|
| 1808 |
|
| 1809 |
private function getOpenConnections() { |
| 1810 |
foreach ( $this->conns as $poolConnsByServer ) { |
| 1811 |
foreach ( $poolConnsByServer as $serverConns ) { |
| 1812 |
foreach ( $serverConns as $conn ) { |
| 1813 |
yield $conn; |
| 1814 |
} |
| 1815 |
} |
| 1816 |
} |
| 1817 |
} |
| 1818 |
|
| 1819 |
|
| 1820 |
|
| 1821 |
|
| 1822 |
|
| 1823 |
private function getOpenPrimaryConnections() { |
| 1824 |
foreach ( $this->conns as $poolConnsByServer ) { |
| 1825 |
|
| 1826 |
foreach ( ( $poolConnsByServer[ServerInfo::WRITER_INDEX] ?? [] ) as $conn ) { |
| 1827 |
yield $conn; |
| 1828 |
} |
| 1829 |
} |
| 1830 |
} |
| 1831 |
|
| 1832 |
public function getMaxLag() { |
| 1833 |
$host = ''; |
| 1834 |
$maxLag = -1; |
| 1835 |
$maxIndex = 0; |
| 1836 |
|
| 1837 |
if ( $this->serverInfo->hasReplicaServers() ) { |
| 1838 |
$lagTimes = $this->getLagTimes(); |
| 1839 |
foreach ( $lagTimes as $i => $lag ) { |
| 1840 |
|
| 1841 |
$load = $this->groupLoads[self::GROUP_GENERIC][$i] ?? 0; |
| 1842 |
if ( $load > 0 && $lag > $maxLag ) { |
| 1843 |
$maxLag = $lag; |
| 1844 |
$host = $this->serverInfo->getServerInfoStrict( $i, 'host' ); |
| 1845 |
$maxIndex = $i; |
| 1846 |
} |
| 1847 |
} |
| 1848 |
} |
| 1849 |
|
| 1850 |
return [ $host, $maxLag, $maxIndex ]; |
| 1851 |
} |
| 1852 |
|
| 1853 |
public function getLagTimes() { |
| 1854 |
if ( !$this->hasReplicaServers() ) { |
| 1855 |
return [ ServerInfo::WRITER_INDEX => 0 ]; |
| 1856 |
} |
| 1857 |
$fname = __METHOD__; |
| 1858 |
return $this->wanCache->getWithSetCallback( |
| 1859 |
$this->wanCache->makeGlobalKey( 'rdbms-lags', $this->getClusterName() ), |
| 1860 |
|
| 1861 |
10 + mt_rand( 1, 10 ), |
| 1862 |
function () use ( $fname ) { |
| 1863 |
$lags = []; |
| 1864 |
foreach ( $this->serverInfo->getStreamingReplicaIndexes() as $i ) { |
| 1865 |
$conn = $this->getServerConnection( |
| 1866 |
$i, |
| 1867 |
self::DOMAIN_ANY, |
| 1868 |
self::CONN_SILENCE_ERRORS | self::CONN_UNTRACKED_GAUGE |
| 1869 |
); |
| 1870 |
if ( $conn ) { |
| 1871 |
$lags[$i] = $conn->getLag(); |
| 1872 |
$conn->close( $fname ); |
| 1873 |
} else { |
| 1874 |
$lags[$i] = false; |
| 1875 |
} |
| 1876 |
} |
| 1877 |
return $lags; |
| 1878 |
}, |
| 1879 |
[ 'lockTSE' => 30 ] |
| 1880 |
); |
| 1881 |
} |
| 1882 |
|
| 1883 |
public function waitForPrimaryPos( IDatabase $conn ) { |
| 1884 |
if ( $conn->getLBInfo( self::INFO_SERVER_INDEX ) === ServerInfo::WRITER_INDEX ) { |
| 1885 |
return true; |
| 1886 |
} |
| 1887 |
|
| 1888 |
|
| 1889 |
$flags = self::CONN_SILENCE_ERRORS; |
| 1890 |
$primaryConn = $this->getAnyOpenConnection( ServerInfo::WRITER_INDEX, $flags ); |
| 1891 |
if ( $primaryConn ) { |
| 1892 |
$pos = $primaryConn->getPrimaryPos(); |
| 1893 |
} else { |
| 1894 |
$primaryConn = $this->getServerConnection( ServerInfo::WRITER_INDEX, self::DOMAIN_ANY, $flags ); |
| 1895 |
if ( !$primaryConn ) { |
| 1896 |
throw new DBReplicationWaitError( |
| 1897 |
null, |
| 1898 |
"Could not obtain a primary database connection to get the position" |
| 1899 |
); |
| 1900 |
} |
| 1901 |
$pos = $primaryConn->getPrimaryPos(); |
| 1902 |
$this->closeConnection( $primaryConn ); |
| 1903 |
} |
| 1904 |
|
| 1905 |
if ( $pos instanceof DBPrimaryPos && $conn instanceof IDatabaseForOwner ) { |
| 1906 |
$this->logger->debug( __METHOD__ . ': waiting' ); |
| 1907 |
$result = $conn->primaryPosWait( $pos, self::MAX_WAIT_DEFAULT ); |
| 1908 |
$ok = ( $result !== null && $result != -1 ); |
| 1909 |
if ( $ok ) { |
| 1910 |
$this->logger->debug( __METHOD__ . ': done waiting (success)' ); |
| 1911 |
} else { |
| 1912 |
$this->logger->debug( __METHOD__ . ': done waiting (failure)' ); |
| 1913 |
} |
| 1914 |
} else { |
| 1915 |
$ok = false; |
| 1916 |
$this->logger->error( |
| 1917 |
__METHOD__ . ': could not get primary pos for {db_server}', |
| 1918 |
$this->getConnLogContext( $conn, [ 'exception' => new RuntimeException() ] ) |
| 1919 |
); |
| 1920 |
} |
| 1921 |
|
| 1922 |
return $ok; |
| 1923 |
} |
| 1924 |
|
| 1925 |
public function setTransactionListener( $name, ?callable $callback = null ) { |
| 1926 |
if ( $callback ) { |
| 1927 |
$this->trxRecurringCallbacks[$name] = $callback; |
| 1928 |
} else { |
| 1929 |
unset( $this->trxRecurringCallbacks[$name] ); |
| 1930 |
} |
| 1931 |
foreach ( $this->getOpenPrimaryConnections() as $conn ) { |
| 1932 |
$conn->setTransactionListener( $name, $callback ); |
| 1933 |
} |
| 1934 |
} |
| 1935 |
|
| 1936 |
public function setTableAliases( array $aliases ) { |
| 1937 |
$this->tableAliases = $aliases; |
| 1938 |
} |
| 1939 |
|
| 1940 |
public function setIndexAliases( array $aliases ) { |
| 1941 |
$this->indexAliases = $aliases; |
| 1942 |
} |
| 1943 |
|
| 1944 |
public function setDomainAliases( array $aliases ) { |
| 1945 |
$this->domainAliases = $aliases; |
| 1946 |
} |
| 1947 |
|
| 1948 |
public function setLocalDomainPrefix( $prefix ) { |
| 1949 |
$oldLocalDomain = $this->localDomain; |
| 1950 |
$this->localDomain = new DatabaseDomain( |
| 1951 |
$this->localDomain->getDatabase(), |
| 1952 |
$this->localDomain->getSchema(), |
| 1953 |
$prefix |
| 1954 |
); |
| 1955 |
|
| 1956 |
|
| 1957 |
|
| 1958 |
foreach ( $this->getOpenConnections() as $conn ) { |
| 1959 |
if ( $oldLocalDomain->equals( $conn->getDomainID() ) ) { |
| 1960 |
$conn->tablePrefix( $prefix ); |
| 1961 |
} |
| 1962 |
} |
| 1963 |
} |
| 1964 |
|
| 1965 |
public function redefineLocalDomain( $domain ) { |
| 1966 |
$this->closeAll( __METHOD__ ); |
| 1967 |
$this->localDomain = DatabaseDomain::newFromId( $domain ); |
| 1968 |
} |
| 1969 |
|
| 1970 |
public function setTempTablesOnlyMode( $value, $domain ) { |
| 1971 |
$old = $this->tempTablesOnlyMode[$domain] ?? false; |
| 1972 |
if ( $value ) { |
| 1973 |
$this->tempTablesOnlyMode[$domain] = true; |
| 1974 |
} else { |
| 1975 |
unset( $this->tempTablesOnlyMode[$domain] ); |
| 1976 |
} |
| 1977 |
|
| 1978 |
return $old; |
| 1979 |
} |
| 1980 |
|
| 1981 |
|
| 1982 |
|
| 1983 |
|
| 1984 |
|
| 1985 |
|
| 1986 |
private function stringifyConn( IDatabase $conn ) { |
| 1987 |
return $conn->getLBInfo( self::INFO_SERVER_INDEX ) . '/' . $conn->getDomainID(); |
| 1988 |
} |
| 1989 |
|
| 1990 |
|
| 1991 |
|
| 1992 |
|
| 1993 |
|
| 1994 |
|
| 1995 |
private function fieldHasBit( int $flags, int $bit ) { |
| 1996 |
return ( ( $flags & $bit ) === $bit ); |
| 1997 |
} |
| 1998 |
|
| 1999 |
|
| 2000 |
|
| 2001 |
|
| 2002 |
|
| 2003 |
|
| 2004 |
|
| 2005 |
|
| 2006 |
protected function getConnLogContext( IDatabase $conn, array $extras = [] ) { |
| 2007 |
return array_merge( |
| 2008 |
[ |
| 2009 |
'db_server' => $conn->getServerName(), |
| 2010 |
'db_domain' => $conn->getDomainID() |
| 2011 |
], |
| 2012 |
$extras |
| 2013 |
); |
| 2014 |
} |
| 2015 |
|
| 2016 |
|
| 2017 |
|
| 2018 |
|
| 2019 |
|
| 2020 |
|
| 2021 |
public function setMockTime( &$time ) { |
| 2022 |
$this->loadMonitor->setMockTime( $time ); |
| 2023 |
} |
| 2024 |
} |