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