rdbms: use ILoadBalancer in more LBFactory comments
[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
99 private static $loggerFields =
100 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
101
102 public function __construct( array $conf ) {
103 $this->localDomain = isset( $conf['localDomain'] )
104 ? DatabaseDomain::newFromId( $conf['localDomain'] )
105 : DatabaseDomain::newUnspecified();
106
107 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
108 $this->readOnlyReason = $conf['readOnlyReason'];
109 }
110
111 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
112 $this->memStash = isset( $conf['memStash'] ) ? $conf['memStash'] : new EmptyBagOStuff();
113 $this->wanCache = isset( $conf['wanCache'] )
114 ? $conf['wanCache']
115 : WANObjectCache::newEmpty();
116
117 foreach ( self::$loggerFields as $key ) {
118 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
119 }
120 $this->errorLogger = isset( $conf['errorLogger'] )
121 ? $conf['errorLogger']
122 : function ( Exception $e ) {
123 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
124 };
125 $this->deprecationLogger = isset( $conf['deprecationLogger'] )
126 ? $conf['deprecationLogger']
127 : function ( $msg ) {
128 trigger_error( $msg, E_USER_DEPRECATED );
129 };
130
131 $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null;
132 $this->trxProfiler = isset( $conf['trxProfiler'] )
133 ? $conf['trxProfiler']
134 : new TransactionProfiler();
135
136 $this->requestInfo = [
137 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
138 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
139 'ChronologyProtection' => 'true',
140 'ChronologyPositionIndex' => isset( $_GET['cpPosIndex'] ) ? $_GET['cpPosIndex'] : null
141 ];
142
143 $this->cliMode = isset( $conf['cliMode'] )
144 ? $conf['cliMode']
145 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
146 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
147 $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : '';
148
149 $this->ticket = mt_rand();
150 }
151
152 public function destroy() {
153 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
154 $this->forEachLBCallMethod( 'disable' );
155 }
156
157 public function shutdown(
158 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null, &$cpIndex = null
159 ) {
160 $chronProt = $this->getChronologyProtector();
161 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
162 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync', $cpIndex );
163 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
164 $this->shutdownChronologyProtector( $chronProt, null, 'async', $cpIndex );
165 }
166
167 $this->commitMasterChanges( __METHOD__ ); // sanity
168 }
169
170 /**
171 * @see ILBFactory::newMainLB()
172 * @param bool $domain
173 * @return ILoadBalancer
174 */
175 abstract public function newMainLB( $domain = false );
176
177 /**
178 * @see ILBFactory::getMainLB()
179 * @param bool $domain
180 * @return ILoadBalancer
181 */
182 abstract public function getMainLB( $domain = false );
183
184 /**
185 * @see ILBFactory::newExternalLB()
186 * @param string $cluster
187 * @return ILoadBalancer
188 */
189 abstract public function newExternalLB( $cluster );
190
191 /**
192 * @see ILBFactory::getExternalLB()
193 * @param string $cluster
194 * @return ILoadBalancer
195 */
196 abstract public function getExternalLB( $cluster );
197
198 /**
199 * Call a method of each tracked load balancer
200 *
201 * @param string $methodName
202 * @param array $args
203 */
204 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
205 $this->forEachLB(
206 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
207 call_user_func_array( [ $loadBalancer, $methodName ], $args );
208 },
209 [ $methodName, $args ]
210 );
211 }
212
213 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
214 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
215 }
216
217 final public function commitAll( $fname = __METHOD__, array $options = [] ) {
218 $this->commitMasterChanges( $fname, $options );
219 $this->forEachLBCallMethod( 'flushMasterSnapshots', [ $fname ] );
220 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
221 }
222
223 final public function beginMasterChanges( $fname = __METHOD__ ) {
224 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
225 $this->trxRoundStage = self::ROUND_BEGINNING;
226 if ( $this->trxRoundId !== false ) {
227 throw new DBTransactionError(
228 null,
229 "$fname: transaction round '{$this->trxRoundId}' already started."
230 );
231 }
232 $this->trxRoundId = $fname;
233 // Set DBO_TRX flags on all appropriate DBs
234 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
235 $this->trxRoundStage = self::ROUND_CURSORY;
236 }
237
238 final public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
239 $this->assertTransactionRoundStage( self::ROUND_CURSORY );
240 $this->trxRoundStage = self::ROUND_COMMITTING;
241 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
242 throw new DBTransactionError(
243 null,
244 "$fname: transaction round '{$this->trxRoundId}' still running."
245 );
246 }
247 /** @noinspection PhpUnusedLocalVariableInspection */
248 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
249 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
250 do {
251 $count = 0; // number of callbacks executed this iteration
252 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$count ) {
253 $count += $lb->finalizeMasterChanges();
254 } );
255 } while ( $count > 0 );
256 $this->trxRoundId = false;
257 // Perform pre-commit checks, aborting on failure
258 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
259 // Log the DBs and methods involved in multi-DB transactions
260 $this->logIfMultiDbTransaction();
261 // Actually perform the commit on all master DB connections and revert DBO_TRX
262 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
263 // Run all post-commit callbacks in a separate step
264 $e = $this->executePostTransactionCallbacks();
265 $this->trxRoundStage = self::ROUND_CURSORY;
266 // Throw any last post-commit callback error
267 if ( $e instanceof Exception ) {
268 throw $e;
269 }
270 }
271
272 final public function rollbackMasterChanges( $fname = __METHOD__ ) {
273 $this->trxRoundStage = self::ROUND_ROLLING_BACK;
274 $this->trxRoundId = false;
275 // Actually perform the rollback on all master DB connections and revert DBO_TRX
276 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
277 // Run all post-commit callbacks in a separate step
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 ],
497 $this->requestInfo['ChronologyPositionIndex']
498 );
499 $this->chronProt->setLogger( $this->replLogger );
500
501 if ( $this->cliMode ) {
502 $this->chronProt->setEnabled( false );
503 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
504 // Request opted out of using position wait logic. This is useful for requests
505 // done by the job queue or background ETL that do not have a meaningful session.
506 $this->chronProt->setWaitEnabled( false );
507 }
508
509 $this->replLogger->debug( __METHOD__ . ': using request info ' .
510 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
511
512 return $this->chronProt;
513 }
514
515 /**
516 * Get and record all of the staged DB positions into persistent memory storage
517 *
518 * @param ChronologyProtector $cp
519 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
520 * @param string $mode One of (sync, async); whether to wait on remote datacenters
521 * @param int|null &$cpIndex DB position key write counter; incremented on update
522 */
523 protected function shutdownChronologyProtector(
524 ChronologyProtector $cp, $workCallback, $mode, &$cpIndex = null
525 ) {
526 // Record all the master positions needed
527 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
528 $cp->shutdownLB( $lb );
529 } );
530 // Write them to the persistent stash. Try to do something useful by running $work
531 // while ChronologyProtector waits for the stash write to replicate to all DCs.
532 $unsavedPositions = $cp->shutdown( $workCallback, $mode, $cpIndex );
533 if ( $unsavedPositions && $workCallback ) {
534 // Invoke callback in case it did not cache the result yet
535 $workCallback(); // work now to block for less time in waitForAll()
536 }
537 // If the positions failed to write to the stash, at least wait on local datacenter
538 // replica DBs to catch up before responding. Even if there are several DCs, this increases
539 // the chance that the user will see their own changes immediately afterwards. As long
540 // as the sticky DC cookie applies (same domain), this is not even an issue.
541 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
542 $masterName = $lb->getServerName( $lb->getWriterIndex() );
543 if ( isset( $unsavedPositions[$masterName] ) ) {
544 $lb->waitForAll( $unsavedPositions[$masterName] );
545 }
546 } );
547 }
548
549 /**
550 * Base parameters to ILoadBalancer::__construct()
551 * @return array
552 */
553 final protected function baseLoadBalancerParams() {
554 return [
555 'localDomain' => $this->localDomain,
556 'readOnlyReason' => $this->readOnlyReason,
557 'srvCache' => $this->srvCache,
558 'wanCache' => $this->wanCache,
559 'profiler' => $this->profiler,
560 'trxProfiler' => $this->trxProfiler,
561 'queryLogger' => $this->queryLogger,
562 'connLogger' => $this->connLogger,
563 'replLogger' => $this->replLogger,
564 'errorLogger' => $this->errorLogger,
565 'deprecationLogger' => $this->deprecationLogger,
566 'hostname' => $this->hostname,
567 'cliMode' => $this->cliMode,
568 'agent' => $this->agent,
569 'chronologyCallback' => function ( ILoadBalancer $lb ) {
570 // Defer ChronologyProtector construction in case setRequestInfo() ends up
571 // being called later (but before the first connection attempt) (T192611)
572 $this->getChronologyProtector()->initLB( $lb );
573 }
574 ];
575 }
576
577 /**
578 * @param ILoadBalancer $lb
579 */
580 protected function initLoadBalancer( ILoadBalancer $lb ) {
581 if ( $this->trxRoundId !== false ) {
582 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
583 }
584
585 $lb->setTableAliases( $this->tableAliases );
586 $lb->setIndexAliases( $this->indexAliases );
587 }
588
589 public function setTableAliases( array $aliases ) {
590 $this->tableAliases = $aliases;
591 }
592
593 public function setIndexAliases( array $aliases ) {
594 $this->indexAliases = $aliases;
595 }
596
597 public function setDomainPrefix( $prefix ) {
598 $this->localDomain = new DatabaseDomain(
599 $this->localDomain->getDatabase(),
600 null,
601 $prefix
602 );
603
604 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $prefix ) {
605 $lb->setDomainPrefix( $prefix );
606 } );
607 }
608
609 public function closeAll() {
610 $this->forEachLBCallMethod( 'closeAll', [] );
611 }
612
613 public function setAgentName( $agent ) {
614 $this->agent = $agent;
615 }
616
617 public function appendShutdownCPIndexAsQuery( $url, $index ) {
618 $usedCluster = 0;
619 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
620 $usedCluster |= ( $lb->getServerCount() > 1 );
621 } );
622
623 if ( !$usedCluster ) {
624 return $url; // no master/replica clusters touched
625 }
626
627 return strpos( $url, '?' ) === false ? "$url?cpPosIndex=$index" : "$url&cpPosIndex=$index";
628 }
629
630 public function setRequestInfo( array $info ) {
631 if ( $this->chronProt ) {
632 throw new LogicException( 'ChronologyProtector already initialized.' );
633 }
634
635 $this->requestInfo = $info + $this->requestInfo;
636 }
637
638 /**
639 * @param string $stage
640 */
641 private function assertTransactionRoundStage( $stage ) {
642 if ( $this->trxRoundStage !== $stage ) {
643 throw new DBTransactionError(
644 null,
645 "Transaction round stage must be '$stage' (not '{$this->trxRoundStage}')"
646 );
647 }
648 }
649
650 /**
651 * Make PHP ignore user aborts/disconnects until the returned
652 * value leaves scope. This returns null and does nothing in CLI mode.
653 *
654 * @return ScopedCallback|null
655 */
656 final protected function getScopedPHPBehaviorForCommit() {
657 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
658 $old = ignore_user_abort( true ); // avoid half-finished operations
659 return new ScopedCallback( function () use ( $old ) {
660 ignore_user_abort( $old );
661 } );
662 }
663
664 return null;
665 }
666
667 function __destruct() {
668 $this->destroy();
669 }
670 }
671
672 class_alias( LBFactory::class, 'LBFactory' );