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