rdbms: make LBFactory close/rollback dangling handles like LoadBalancer
[lhc/web/wiklou.git] / includes / libs / rdbms / lbfactory / LBFactory.php
1 <?php
2 /**
3 * Generator and manager of database load balancing objects
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 namespace Wikimedia\Rdbms;
25
26 use Psr\Log\LoggerInterface;
27 use Psr\Log\NullLogger;
28 use Wikimedia\ScopedCallback;
29 use BagOStuff;
30 use EmptyBagOStuff;
31 use WANObjectCache;
32 use Exception;
33 use RuntimeException;
34 use LogicException;
35
36 /**
37 * An interface for generating database load balancers
38 * @ingroup Database
39 */
40 abstract class LBFactory implements ILBFactory {
41 /** @var ChronologyProtector */
42 private $chronProt;
43 /** @var object|string Class name or object With profileIn/profileOut methods */
44 private $profiler;
45 /** @var TransactionProfiler */
46 private $trxProfiler;
47 /** @var LoggerInterface */
48 private $replLogger;
49 /** @var LoggerInterface */
50 private $connLogger;
51 /** @var LoggerInterface */
52 private $queryLogger;
53 /** @var LoggerInterface */
54 private $perfLogger;
55 /** @var callable Error logger */
56 private $errorLogger;
57 /** @var callable Deprecation logger */
58 private $deprecationLogger;
59
60 /** @var BagOStuff */
61 protected $srvCache;
62 /** @var BagOStuff */
63 protected $memStash;
64 /** @var WANObjectCache */
65 protected $wanCache;
66
67 /** @var DatabaseDomain Local domain */
68 protected $localDomain;
69
70 /** @var string Local hostname of the app server */
71 private $hostname;
72 /** @var array Web request information about the client */
73 private $requestInfo;
74 /** @var bool Whether this PHP instance is for a CLI script */
75 private $cliMode;
76 /** @var string Agent name for query profiling */
77 private $agent;
78 /** @var string Secret string for HMAC hashing */
79 private $secret;
80
81 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
82 private $tableAliases = [];
83 /** @var string[] Map of (index alias => index) */
84 private $indexAliases = [];
85 /** @var callable[] */
86 private $replicationWaitCallbacks = [];
87
88 /** var int An identifier for this class instance */
89 private $id;
90 /** @var int|null Ticket used to delegate transaction ownership */
91 private $ticket;
92 /** @var string|bool String if a requested DBO_TRX transaction round is active */
93 private $trxRoundId = false;
94 /** @var string One of the ROUND_* class constants */
95 private $trxRoundStage = self::ROUND_CURSORY;
96
97 /** @var string|bool Reason all LBs are read-only or false if not */
98 protected $readOnlyReason = false;
99
100 /** @var string|null */
101 private $defaultGroup = null;
102
103 /** @var int|null */
104 protected $maxLag;
105
106 const ROUND_CURSORY = 'cursory';
107 const ROUND_BEGINNING = 'within-begin';
108 const ROUND_COMMITTING = 'within-commit';
109 const ROUND_ROLLING_BACK = 'within-rollback';
110 const ROUND_COMMIT_CALLBACKS = 'within-commit-callbacks';
111 const ROUND_ROLLBACK_CALLBACKS = 'within-rollback-callbacks';
112
113 private static $loggerFields =
114 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
115
116 public function __construct( array $conf ) {
117 $this->localDomain = isset( $conf['localDomain'] )
118 ? DatabaseDomain::newFromId( $conf['localDomain'] )
119 : DatabaseDomain::newUnspecified();
120
121 $this->maxLag = $conf['maxLag'] ?? null;
122 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
123 $this->readOnlyReason = $conf['readOnlyReason'];
124 }
125
126 $this->srvCache = $conf['srvCache'] ?? new EmptyBagOStuff();
127 $this->memStash = $conf['memStash'] ?? new EmptyBagOStuff();
128 $this->wanCache = $conf['wanCache'] ?? WANObjectCache::newEmpty();
129
130 foreach ( self::$loggerFields as $key ) {
131 $this->$key = $conf[$key] ?? new NullLogger();
132 }
133 $this->errorLogger = $conf['errorLogger'] ?? function ( Exception $e ) {
134 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
135 };
136 $this->deprecationLogger = $conf['deprecationLogger'] ?? function ( $msg ) {
137 trigger_error( $msg, E_USER_DEPRECATED );
138 };
139
140 $this->profiler = $conf['profiler'] ?? null;
141 $this->trxProfiler = $conf['trxProfiler'] ?? new TransactionProfiler();
142
143 $this->requestInfo = [
144 'IPAddress' => $_SERVER[ 'REMOTE_ADDR' ] ?? '',
145 'UserAgent' => $_SERVER['HTTP_USER_AGENT'] ?? '',
146 // Headers application can inject via LBFactory::setRequestInfo()
147 'ChronologyProtection' => null,
148 'ChronologyClientId' => null, // prior $cpClientId value from LBFactory::shutdown()
149 'ChronologyPositionIndex' => null // prior $cpIndex value from LBFactory::shutdown()
150 ];
151
152 $this->cliMode = $conf['cliMode'] ?? ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
153 $this->hostname = $conf['hostname'] ?? gethostname();
154 $this->agent = $conf['agent'] ?? '';
155 $this->defaultGroup = $conf['defaultGroup'] ?? null;
156 $this->secret = $conf['secret'] ?? '';
157
158 $this->id = mt_rand();
159 $this->ticket = mt_rand();
160 }
161
162 public function destroy() {
163 $this->forEachLBCallMethod( 'disable' );
164 }
165
166 public function getLocalDomainID() {
167 return $this->localDomain->getId();
168 }
169
170 public function resolveDomainID( $domain ) {
171 return ( $domain !== false ) ? (string)$domain : $this->getLocalDomainID();
172 }
173
174 public function shutdown(
175 $mode = self::SHUTDOWN_CHRONPROT_SYNC,
176 callable $workCallback = null,
177 &$cpIndex = null,
178 &$cpClientId = null
179 ) {
180 $chronProt = $this->getChronologyProtector();
181 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
182 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
183 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
184 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
185 }
186
187 $cpClientId = $chronProt->getClientId();
188
189 $this->commitMasterChanges( __METHOD__ ); // sanity
190 }
191
192 /**
193 * @see ILBFactory::newMainLB()
194 * @param bool $domain
195 * @return ILoadBalancer
196 */
197 abstract public function newMainLB( $domain = false );
198
199 /**
200 * @see ILBFactory::getMainLB()
201 * @param bool $domain
202 * @return ILoadBalancer
203 */
204 abstract public function getMainLB( $domain = false );
205
206 /**
207 * @see ILBFactory::newExternalLB()
208 * @param string $cluster
209 * @return ILoadBalancer
210 */
211 abstract public function newExternalLB( $cluster );
212
213 /**
214 * @see ILBFactory::getExternalLB()
215 * @param string $cluster
216 * @return ILoadBalancer
217 */
218 abstract public function getExternalLB( $cluster );
219
220 /**
221 * Call a method of each tracked load balancer
222 *
223 * @param string $methodName
224 * @param array $args
225 */
226 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
227 $this->forEachLB(
228 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
229 $loadBalancer->$methodName( ...$args );
230 },
231 [ $methodName, $args ]
232 );
233 }
234
235 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
236 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
237 $this->queryLogger->warning(
238 "$fname: transaction round '{$this->trxRoundId}' still running",
239 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
240 );
241 }
242 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
243 }
244
245 final public function commitAll( $fname = __METHOD__, array $options = [] ) {
246 $this->commitMasterChanges( $fname, $options );
247 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
248 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
249 }
250
251 final public function beginMasterChanges( $fname = __METHOD__ ) {
252 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
253 $this->trxRoundStage = self::ROUND_BEGINNING;
254 if ( $this->trxRoundId !== false ) {
255 throw new DBTransactionError(
256 null,
257 "$fname: transaction round '{$this->trxRoundId}' already started"
258 );
259 }
260 $this->trxRoundId = $fname;
261 // Set DBO_TRX flags on all appropriate DBs
262 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname, $this->id ] );
263 $this->trxRoundStage = self::ROUND_CURSORY;
264 }
265
266 final public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
267 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
268 $this->trxRoundStage = self::ROUND_COMMITTING;
269 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
270 throw new DBTransactionError(
271 null,
272 "$fname: transaction round '{$this->trxRoundId}' still running"
273 );
274 }
275 /** @noinspection PhpUnusedLocalVariableInspection */
276 $scope = ScopedCallback::newScopedIgnoreUserAbort(); // try to ignore client aborts
277 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
278 do {
279 $count = 0; // number of callbacks executed this iteration
280 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$count, $fname ) {
281 $count += $lb->finalizeMasterChanges( $fname, $this->id );
282 } );
283 } while ( $count > 0 );
284 $this->trxRoundId = false;
285 // Perform pre-commit checks, aborting on failure
286 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options, $fname, $this->id ] );
287 // Log the DBs and methods involved in multi-DB transactions
288 $this->logIfMultiDbTransaction();
289 // Actually perform the commit on all master DB connections and revert DBO_TRX
290 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname, $this->id ] );
291 // Run all post-commit callbacks in a separate step
292 $this->trxRoundStage = self::ROUND_COMMIT_CALLBACKS;
293 $e = $this->executePostTransactionCallbacks();
294 $this->trxRoundStage = self::ROUND_CURSORY;
295 // Throw any last post-commit callback error
296 if ( $e instanceof Exception ) {
297 throw $e;
298 }
299 }
300
301 final public function rollbackMasterChanges( $fname = __METHOD__ ) {
302 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
303 $this->trxRoundId = false;
304 // Actually perform the rollback on all master DB connections and revert DBO_TRX
305 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname, $this->id ] );
306 // Run all post-commit callbacks in a separate step
307 $this->trxRoundStage = self::ROUND_ROLLBACK_CALLBACKS;
308 $this->executePostTransactionCallbacks();
309 $this->trxRoundStage = self::ROUND_CURSORY;
310 }
311
312 /**
313 * @return Exception|null
314 */
315 private function executePostTransactionCallbacks() {
316 $fname = __METHOD__;
317 // Run all post-commit callbacks until new ones stop getting added
318 $e = null; // first callback exception
319 do {
320 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e, $fname ) {
321 $ex = $lb->runMasterTransactionIdleCallbacks( $fname, $this->id );
322 $e = $e ?: $ex;
323 } );
324 } while ( $this->hasMasterChanges() );
325 // Run all listener callbacks once
326 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e, $fname ) {
327 $ex = $lb->runMasterTransactionListenerCallbacks( $fname, $this->id );
328 $e = $e ?: $ex;
329 } );
330
331 return $e;
332 }
333
334 public function hasTransactionRound() {
335 return ( $this->trxRoundId !== false );
336 }
337
338 public function isReadyForRoundOperations() {
339 return ( $this->trxRoundStage === self::ROUND_CURSORY );
340 }
341
342 /**
343 * Log query info if multi DB transactions are going to be committed now
344 */
345 private function logIfMultiDbTransaction() {
346 $callersByDB = [];
347 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
348 $masterName = $lb->getServerName( $lb->getWriterIndex() );
349 $callers = $lb->pendingMasterChangeCallers();
350 if ( $callers ) {
351 $callersByDB[$masterName] = $callers;
352 }
353 } );
354
355 if ( count( $callersByDB ) >= 2 ) {
356 $dbs = implode( ', ', array_keys( $callersByDB ) );
357 $msg = "Multi-DB transaction [{$dbs}]:\n";
358 foreach ( $callersByDB as $db => $callers ) {
359 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
360 }
361 $this->queryLogger->info( $msg );
362 }
363 }
364
365 public function hasMasterChanges() {
366 $ret = false;
367 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
368 $ret = $ret || $lb->hasMasterChanges();
369 } );
370
371 return $ret;
372 }
373
374 public function laggedReplicaUsed() {
375 $ret = false;
376 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
377 $ret = $ret || $lb->laggedReplicaUsed();
378 } );
379
380 return $ret;
381 }
382
383 public function hasOrMadeRecentMasterChanges( $age = null ) {
384 $ret = false;
385 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
386 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
387 } );
388 return $ret;
389 }
390
391 public function waitForReplication( array $opts = [] ) {
392 $opts += [
393 'domain' => false,
394 'cluster' => false,
395 'timeout' => $this->cliMode ? 60 : 1,
396 'ifWritesSince' => null
397 ];
398
399 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
400 $opts['domain'] = $opts['wiki']; // b/c
401 }
402
403 // Figure out which clusters need to be checked
404 /** @var ILoadBalancer[] $lbs */
405 $lbs = [];
406 if ( $opts['cluster'] !== false ) {
407 $lbs[] = $this->getExternalLB( $opts['cluster'] );
408 } elseif ( $opts['domain'] !== false ) {
409 $lbs[] = $this->getMainLB( $opts['domain'] );
410 } else {
411 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
412 $lbs[] = $lb;
413 } );
414 if ( !$lbs ) {
415 return true; // nothing actually used
416 }
417 }
418
419 // Get all the master positions of applicable DBs right now.
420 // This can be faster since waiting on one cluster reduces the
421 // time needed to wait on the next clusters.
422 $masterPositions = array_fill( 0, count( $lbs ), false );
423 foreach ( $lbs as $i => $lb ) {
424 if (
425 // No writes to wait on getting replicated
426 !$lb->hasMasterConnection() ||
427 // No replication; avoid getMasterPos() permissions errors (T29975)
428 !$lb->hasStreamingReplicaServers() ||
429 // No writes since the last replication wait
430 (
431 $opts['ifWritesSince'] &&
432 $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
433 )
434 ) {
435 continue; // no need to wait
436 }
437
438 $masterPositions[$i] = $lb->getMasterPos();
439 }
440
441 // Run any listener callbacks *after* getting the DB positions. The more
442 // time spent in the callbacks, the less time is spent in waitForAll().
443 foreach ( $this->replicationWaitCallbacks as $callback ) {
444 $callback();
445 }
446
447 $failed = [];
448 foreach ( $lbs as $i => $lb ) {
449 if ( $masterPositions[$i] ) {
450 // The RDBMS may not support getMasterPos()
451 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
452 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
453 }
454 }
455 }
456
457 return !$failed;
458 }
459
460 public function setWaitForReplicationListener( $name, callable $callback = null ) {
461 if ( $callback ) {
462 $this->replicationWaitCallbacks[$name] = $callback;
463 } else {
464 unset( $this->replicationWaitCallbacks[$name] );
465 }
466 }
467
468 public function getEmptyTransactionTicket( $fname ) {
469 if ( $this->hasMasterChanges() ) {
470 $this->queryLogger->error(
471 __METHOD__ . ": $fname does not have outer scope",
472 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
473 );
474
475 return null;
476 }
477
478 return $this->ticket;
479 }
480
481 final public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
482 if ( $ticket !== $this->ticket ) {
483 $this->perfLogger->error(
484 __METHOD__ . ": $fname does not have outer scope",
485 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
486 );
487
488 return false;
489 }
490
491 // The transaction owner and any caller with the empty transaction ticket can commit
492 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
493 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
494 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}" );
495 $fnameEffective = $this->trxRoundId;
496 } else {
497 $fnameEffective = $fname;
498 }
499
500 $this->commitMasterChanges( $fnameEffective );
501 $waitSucceeded = $this->waitForReplication( $opts );
502 // If a nested caller committed on behalf of $fname, start another empty $fname
503 // transaction, leaving the caller with the same empty transaction state as before.
504 if ( $fnameEffective !== $fname ) {
505 $this->beginMasterChanges( $fnameEffective );
506 }
507
508 return $waitSucceeded;
509 }
510
511 public function getChronologyProtectorTouched( $dbName ) {
512 return $this->getChronologyProtector()->getTouched( $dbName );
513 }
514
515 public function disableChronologyProtection() {
516 $this->getChronologyProtector()->setEnabled( false );
517 }
518
519 /**
520 * @return ChronologyProtector
521 */
522 protected function getChronologyProtector() {
523 if ( $this->chronProt ) {
524 return $this->chronProt;
525 }
526
527 $this->chronProt = new ChronologyProtector(
528 $this->memStash,
529 [
530 'ip' => $this->requestInfo['IPAddress'],
531 'agent' => $this->requestInfo['UserAgent'],
532 'clientId' => $this->requestInfo['ChronologyClientId'] ?: null
533 ],
534 $this->requestInfo['ChronologyPositionIndex'],
535 $this->secret
536 );
537 $this->chronProt->setLogger( $this->replLogger );
538
539 if ( $this->cliMode ) {
540 $this->chronProt->setEnabled( false );
541 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
542 // Request opted out of using position wait logic. This is useful for requests
543 // done by the job queue or background ETL that do not have a meaningful session.
544 $this->chronProt->setWaitEnabled( false );
545 } elseif ( $this->memStash instanceof EmptyBagOStuff ) {
546 // No where to store any DB positions and wait for them to appear
547 $this->chronProt->setEnabled( false );
548 $this->replLogger->info( 'Cannot use ChronologyProtector with EmptyBagOStuff' );
549 }
550
551 $this->replLogger->debug(
552 __METHOD__ . ': request info ' .
553 json_encode( $this->requestInfo, JSON_PRETTY_PRINT )
554 );
555
556 return $this->chronProt;
557 }
558
559 /**
560 * Get and record all of the staged DB positions into persistent memory storage
561 *
562 * @param ChronologyProtector $cp
563 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
564 * @param string $mode One of (sync, async); whether to wait on remote datacenters
565 * @param int|null &$cpIndex DB position key write counter; incremented on update
566 */
567 protected function shutdownChronologyProtector(
568 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
569 ) {
570 // Record all the master positions needed
571 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
572 $cp->storeSessionReplicationPosition( $lb );
573 } );
574 // Write them to the persistent stash. Try to do something useful by running $work
575 // while ChronologyProtector waits for the stash write to replicate to all DCs.
576 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
577 if ( $unsavedPositions && $workCallback ) {
578 // Invoke callback in case it did not cache the result yet
579 $workCallback(); // work now to block for less time in waitForAll()
580 }
581 // If the positions failed to write to the stash, at least wait on local datacenter
582 // replica DBs to catch up before responding. Even if there are several DCs, this increases
583 // the chance that the user will see their own changes immediately afterwards. As long
584 // as the sticky DC cookie applies (same domain), this is not even an issue.
585 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
586 $masterName = $lb->getServerName( $lb->getWriterIndex() );
587 if ( isset( $unsavedPositions[$masterName] ) ) {
588 $lb->waitForAll( $unsavedPositions[$masterName] );
589 }
590 } );
591 }
592
593 /**
594 * Base parameters to ILoadBalancer::__construct()
595 * @return array
596 */
597 final protected function baseLoadBalancerParams() {
598 if ( $this->trxRoundStage === self::ROUND_COMMIT_CALLBACKS ) {
599 $initStage = ILoadBalancer::STAGE_POSTCOMMIT_CALLBACKS;
600 } elseif ( $this->trxRoundStage === self::ROUND_ROLLBACK_CALLBACKS ) {
601 $initStage = ILoadBalancer::STAGE_POSTROLLBACK_CALLBACKS;
602 } else {
603 $initStage = null;
604 }
605
606 return [
607 'localDomain' => $this->localDomain,
608 'readOnlyReason' => $this->readOnlyReason,
609 'srvCache' => $this->srvCache,
610 'wanCache' => $this->wanCache,
611 'profiler' => $this->profiler,
612 'trxProfiler' => $this->trxProfiler,
613 'queryLogger' => $this->queryLogger,
614 'connLogger' => $this->connLogger,
615 'replLogger' => $this->replLogger,
616 'errorLogger' => $this->errorLogger,
617 'deprecationLogger' => $this->deprecationLogger,
618 'hostname' => $this->hostname,
619 'cliMode' => $this->cliMode,
620 'agent' => $this->agent,
621 'maxLag' => $this->maxLag,
622 'defaultGroup' => $this->defaultGroup,
623 'chronologyCallback' => function ( ILoadBalancer $lb ) {
624 // Defer ChronologyProtector construction in case setRequestInfo() ends up
625 // being called later (but before the first connection attempt) (T192611)
626 $this->getChronologyProtector()->applySessionReplicationPosition( $lb );
627 },
628 'roundStage' => $initStage,
629 'ownerId' => $this->id
630 ];
631 }
632
633 /**
634 * @param ILoadBalancer $lb
635 */
636 protected function initLoadBalancer( ILoadBalancer $lb ) {
637 if ( $this->trxRoundId !== false ) {
638 $lb->beginMasterChanges( $this->trxRoundId, $this->id ); // set DBO_TRX
639 }
640
641 $lb->setTableAliases( $this->tableAliases );
642 $lb->setIndexAliases( $this->indexAliases );
643 }
644
645 public function setTableAliases( array $aliases ) {
646 $this->tableAliases = $aliases;
647 }
648
649 public function setIndexAliases( array $aliases ) {
650 $this->indexAliases = $aliases;
651 }
652
653 public function setLocalDomainPrefix( $prefix ) {
654 $this->localDomain = new DatabaseDomain(
655 $this->localDomain->getDatabase(),
656 $this->localDomain->getSchema(),
657 $prefix
658 );
659
660 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
661 $lb->setLocalDomainPrefix( $prefix );
662 } );
663 }
664
665 public function redefineLocalDomain( $domain ) {
666 $this->closeAll();
667
668 $this->localDomain = DatabaseDomain::newFromId( $domain );
669
670 $this->forEachLB( function ( ILoadBalancer $lb ) {
671 $lb->redefineLocalDomain( $this->localDomain );
672 } );
673 }
674
675 public function closeAll() {
676 $this->forEachLBCallMethod( 'closeAll' );
677 }
678
679 public function setAgentName( $agent ) {
680 $this->agent = $agent;
681 }
682
683 public function appendShutdownCPIndexAsQuery( $url, $index ) {
684 $usedCluster = 0;
685 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
686 $usedCluster |= $lb->hasStreamingReplicaServers();
687 } );
688
689 if ( !$usedCluster ) {
690 return $url; // no master/replica clusters touched
691 }
692
693 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
694 }
695
696 public function getChronologyProtectorClientId() {
697 return $this->getChronologyProtector()->getClientId();
698 }
699
700 /**
701 * @param int $index Write index
702 * @param int $time UNIX timestamp; can be used to detect stale cookies (T190082)
703 * @param string $clientId Agent ID hash from ILBFactory::shutdown()
704 * @return string Timestamp-qualified write index of the form "<index>@<timestamp>#<hash>"
705 * @since 1.32
706 */
707 public static function makeCookieValueFromCPIndex( $index, $time, $clientId ) {
708 return "$index@$time#$clientId";
709 }
710
711 /**
712 * @param string $value Possible result of LBFactory::makeCookieValueFromCPIndex()
713 * @param int $minTimestamp Lowest UNIX timestamp that a non-expired value can have
714 * @return array (index: int or null, clientId: string or null)
715 * @since 1.32
716 */
717 public static function getCPInfoFromCookieValue( $value, $minTimestamp ) {
718 static $placeholder = [ 'index' => null, 'clientId' => null ];
719
720 if ( !preg_match( '/^(\d+)@(\d+)#([0-9a-f]{32})$/', $value, $m ) ) {
721 return $placeholder; // invalid
722 }
723
724 $index = (int)$m[1];
725 if ( $index <= 0 ) {
726 return $placeholder; // invalid
727 } elseif ( isset( $m[2] ) && $m[2] !== '' && (int)$m[2] < $minTimestamp ) {
728 return $placeholder; // expired
729 }
730
731 $clientId = ( isset( $m[3] ) && $m[3] !== '' ) ? $m[3] : null;
732
733 return [ 'index' => $index, 'clientId' => $clientId ];
734 }
735
736 public function setRequestInfo( array $info ) {
737 if ( $this->chronProt ) {
738 throw new LogicException( 'ChronologyProtector already initialized' );
739 }
740
741 $this->requestInfo = $info + $this->requestInfo;
742 }
743
744 /**
745 * @param string $stage
746 */
747 private function assertTransactionRoundStage( $stage ) {
748 if ( $this->trxRoundStage !== $stage ) {
749 throw new DBTransactionError(
750 null,
751 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
752 );
753 }
754 }
755
756 function __destruct() {
757 $this->destroy();
758 }
759 }