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