Merge "Move LoadBalancerSingle to /libs/rdbms"
[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 use Psr\Log\LoggerInterface;
25
26 /**
27 * An interface for generating database load balancers
28 * @ingroup Database
29 */
30 abstract class LBFactory {
31 /** @var ChronologyProtector */
32 protected $chronProt;
33 /** @var object|string Class name or object With profileIn/profileOut methods */
34 protected $profiler;
35 /** @var TransactionProfiler */
36 protected $trxProfiler;
37 /** @var LoggerInterface */
38 protected $replLogger;
39 /** @var LoggerInterface */
40 protected $connLogger;
41 /** @var LoggerInterface */
42 protected $queryLogger;
43 /** @var LoggerInterface */
44 protected $perfLogger;
45 /** @var callable Error logger */
46 protected $errorLogger;
47 /** @var BagOStuff */
48 protected $srvCache;
49 /** @var BagOStuff */
50 protected $memCache;
51 /** @var WANObjectCache */
52 protected $wanCache;
53
54 /** @var DatabaseDomain Local domain */
55 protected $localDomain;
56 /** @var string Local hostname of the app server */
57 protected $hostname;
58 /** @var array Web request information about the client */
59 protected $requestInfo;
60
61 /** @var mixed */
62 protected $ticket;
63 /** @var string|bool String if a requested DBO_TRX transaction round is active */
64 protected $trxRoundId = false;
65 /** @var string|bool Reason all LBs are read-only or false if not */
66 protected $readOnlyReason = false;
67 /** @var callable[] */
68 protected $replicationWaitCallbacks = [];
69
70 /** @var bool Whether this PHP instance is for a CLI script */
71 protected $cliMode;
72 /** @var string Agent name for query profiling */
73 protected $agent;
74
75 const SHUTDOWN_NO_CHRONPROT = 0; // don't save DB positions at all
76 const SHUTDOWN_CHRONPROT_ASYNC = 1; // save DB positions, but don't wait on remote DCs
77 const SHUTDOWN_CHRONPROT_SYNC = 2; // save DB positions, waiting on all DCs
78
79 private static $loggerFields =
80 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
81
82 /**
83 * @TODO: document base params here
84 * @param array $conf
85 */
86 public function __construct( array $conf ) {
87 $this->localDomain = isset( $conf['localDomain'] )
88 ? DatabaseDomain::newFromId( $conf['localDomain'] )
89 : DatabaseDomain::newUnspecified();
90
91 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
92 $this->readOnlyReason = $conf['readOnlyReason'];
93 }
94
95 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
96 $this->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : new EmptyBagOStuff();
97 $this->wanCache = isset( $conf['wanCache'] )
98 ? $conf['wanCache']
99 : WANObjectCache::newEmpty();
100
101 foreach ( self::$loggerFields as $key ) {
102 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
103 }
104 $this->errorLogger = isset( $conf['errorLogger'] )
105 ? $conf['errorLogger']
106 : function ( Exception $e ) {
107 trigger_error( E_WARNING, get_class( $e ) . ': ' . $e->getMessage() );
108 };
109
110 $this->chronProt = isset( $conf['chronProt'] ) ? $conf['chronProt'] : null;
111
112 $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null;
113 $this->trxProfiler = isset( $conf['trxProfiler'] )
114 ? $conf['trxProfiler']
115 : new TransactionProfiler();
116
117 $this->requestInfo = [
118 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
119 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
120 'ChronologyProtection' => 'true'
121 ];
122
123 $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
124 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
125 $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
126
127 $this->ticket = mt_rand();
128 }
129
130 /**
131 * Disables all load balancers. All connections are closed, and any attempt to
132 * open a new connection will result in a DBAccessError.
133 * @see LoadBalancer::disable()
134 */
135 public function destroy() {
136 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
137 $this->forEachLBCallMethod( 'disable' );
138 }
139
140 /**
141 * Create a new load balancer object. The resulting object will be untracked,
142 * not chronology-protected, and the caller is responsible for cleaning it up.
143 *
144 * @param bool|string $domain Domain ID, or false for the current domain
145 * @return ILoadBalancer
146 */
147 abstract public function newMainLB( $domain = false );
148
149 /**
150 * Get a cached (tracked) load balancer object.
151 *
152 * @param bool|string $domain Domain ID, or false for the current domain
153 * @return ILoadBalancer
154 */
155 abstract public function getMainLB( $domain = false );
156
157 /**
158 * Create a new load balancer for external storage. The resulting object will be
159 * untracked, not chronology-protected, and the caller is responsible for
160 * cleaning it up.
161 *
162 * @param string $cluster External storage cluster, or false for core
163 * @param bool|string $domain Domain ID, or false for the current domain
164 * @return ILoadBalancer
165 */
166 abstract protected function newExternalLB( $cluster, $domain = false );
167
168 /**
169 * Get a cached (tracked) load balancer for external storage
170 *
171 * @param string $cluster External storage cluster, or false for core
172 * @param bool|string $domain Domain ID, or false for the current domain
173 * @return ILoadBalancer
174 */
175 abstract public function getExternalLB( $cluster, $domain = false );
176
177 /**
178 * Execute a function for each tracked load balancer
179 * The callback is called with the load balancer as the first parameter,
180 * and $params passed as the subsequent parameters.
181 *
182 * @param callable $callback
183 * @param array $params
184 */
185 abstract public function forEachLB( $callback, array $params = [] );
186
187 /**
188 * Prepare all tracked load balancers for shutdown
189 * @param integer $mode One of the class SHUTDOWN_* constants
190 * @param callable|null $workCallback Work to mask ChronologyProtector writes
191 */
192 public function shutdown(
193 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
194 ) {
195 $chronProt = $this->getChronologyProtector();
196 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
197 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
198 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
199 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
200 }
201
202 $this->commitMasterChanges( __METHOD__ ); // sanity
203 }
204
205 /**
206 * Call a method of each tracked load balancer
207 *
208 * @param string $methodName
209 * @param array $args
210 */
211 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
212 $this->forEachLB(
213 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
214 call_user_func_array( [ $loadBalancer, $methodName ], $args );
215 },
216 [ $methodName, $args ]
217 );
218 }
219
220 /**
221 * Commit all replica DB transactions so as to flush any REPEATABLE-READ or SSI snapshot
222 *
223 * @param string $fname Caller name
224 * @since 1.28
225 */
226 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
227 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
228 }
229
230 /**
231 * Commit on all connections. Done for two reasons:
232 * 1. To commit changes to the masters.
233 * 2. To release the snapshot on all connections, master and replica DB.
234 * @param string $fname Caller name
235 * @param array $options Options map:
236 * - maxWriteDuration: abort if more than this much time was spent in write queries
237 */
238 public function commitAll( $fname = __METHOD__, array $options = [] ) {
239 $this->commitMasterChanges( $fname, $options );
240 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
241 }
242
243 /**
244 * Flush any master transaction snapshots and set DBO_TRX (if DBO_DEFAULT is set)
245 *
246 * The DBO_TRX setting will be reverted to the default in each of these methods:
247 * - commitMasterChanges()
248 * - rollbackMasterChanges()
249 * - commitAll()
250 *
251 * This allows for custom transaction rounds from any outer transaction scope.
252 *
253 * @param string $fname
254 * @throws DBTransactionError
255 * @since 1.28
256 */
257 public function beginMasterChanges( $fname = __METHOD__ ) {
258 if ( $this->trxRoundId !== false ) {
259 throw new DBTransactionError(
260 null,
261 "$fname: transaction round '{$this->trxRoundId}' already started."
262 );
263 }
264 $this->trxRoundId = $fname;
265 // Set DBO_TRX flags on all appropriate DBs
266 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
267 }
268
269 /**
270 * Commit changes on all master connections
271 * @param string $fname Caller name
272 * @param array $options Options map:
273 * - maxWriteDuration: abort if more than this much time was spent in write queries
274 * @throws Exception
275 */
276 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
277 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
278 throw new DBTransactionError(
279 null,
280 "$fname: transaction round '{$this->trxRoundId}' still running."
281 );
282 }
283 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
284 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
285 $this->trxRoundId = false;
286 // Perform pre-commit checks, aborting on failure
287 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
288 // Log the DBs and methods involved in multi-DB transactions
289 $this->logIfMultiDbTransaction();
290 // Actually perform the commit on all master DB connections and revert DBO_TRX
291 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
292 // Run all post-commit callbacks
293 /** @var Exception $e */
294 $e = null; // first callback exception
295 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
296 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
297 $e = $e ?: $ex;
298 } );
299 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
300 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
301 // Throw any last post-commit callback error
302 if ( $e instanceof Exception ) {
303 throw $e;
304 }
305 }
306
307 /**
308 * Rollback changes on all master connections
309 * @param string $fname Caller name
310 * @since 1.23
311 */
312 public function rollbackMasterChanges( $fname = __METHOD__ ) {
313 $this->trxRoundId = false;
314 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
315 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
316 // Run all post-rollback callbacks
317 $this->forEachLB( function ( ILoadBalancer $lb ) {
318 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
319 } );
320 }
321
322 /**
323 * Log query info if multi DB transactions are going to be committed now
324 */
325 private function logIfMultiDbTransaction() {
326 $callersByDB = [];
327 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
328 $masterName = $lb->getServerName( $lb->getWriterIndex() );
329 $callers = $lb->pendingMasterChangeCallers();
330 if ( $callers ) {
331 $callersByDB[$masterName] = $callers;
332 }
333 } );
334
335 if ( count( $callersByDB ) >= 2 ) {
336 $dbs = implode( ', ', array_keys( $callersByDB ) );
337 $msg = "Multi-DB transaction [{$dbs}]:\n";
338 foreach ( $callersByDB as $db => $callers ) {
339 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
340 }
341 $this->queryLogger->info( $msg );
342 }
343 }
344
345 /**
346 * Determine if any master connection has pending changes
347 * @return bool
348 * @since 1.23
349 */
350 public function hasMasterChanges() {
351 $ret = false;
352 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
353 $ret = $ret || $lb->hasMasterChanges();
354 } );
355
356 return $ret;
357 }
358
359 /**
360 * Detemine if any lagged replica DB connection was used
361 * @return bool
362 * @since 1.28
363 */
364 public function laggedReplicaUsed() {
365 $ret = false;
366 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
367 $ret = $ret || $lb->laggedReplicaUsed();
368 } );
369
370 return $ret;
371 }
372
373 /**
374 * Determine if any master connection has pending/written changes from this request
375 * @param float $age How many seconds ago is "recent" [defaults to LB lag wait timeout]
376 * @return bool
377 * @since 1.27
378 */
379 public function hasOrMadeRecentMasterChanges( $age = null ) {
380 $ret = false;
381 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
382 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
383 } );
384 return $ret;
385 }
386
387 /**
388 * Waits for the replica DBs to catch up to the current master position
389 *
390 * Use this when updating very large numbers of rows, as in maintenance scripts,
391 * to avoid causing too much lag. Of course, this is a no-op if there are no replica DBs.
392 *
393 * By default this waits on all DB clusters actually used in this request.
394 * This makes sense when lag being waiting on is caused by the code that does this check.
395 * In that case, setting "ifWritesSince" can avoid the overhead of waiting for clusters
396 * that were not changed since the last wait check. To forcefully wait on a specific cluster
397 * for a given wiki, use the 'wiki' parameter. To forcefully wait on an "external" cluster,
398 * use the "cluster" parameter.
399 *
400 * Never call this function after a large DB write that is *still* in a transaction.
401 * It only makes sense to call this after the possible lag inducing changes were committed.
402 *
403 * @param array $opts Optional fields that include:
404 * - wiki : wait on the load balancer DBs that handles the given wiki
405 * - cluster : wait on the given external load balancer DBs
406 * - timeout : Max wait time. Default: ~60 seconds
407 * - ifWritesSince: Only wait if writes were done since this UNIX timestamp
408 * @throws DBReplicationWaitError If a timeout or error occured waiting on a DB cluster
409 * @since 1.27
410 */
411 public function waitForReplication( array $opts = [] ) {
412 $opts += [
413 'wiki' => false,
414 'cluster' => false,
415 'timeout' => 60,
416 'ifWritesSince' => null
417 ];
418
419 // Figure out which clusters need to be checked
420 /** @var ILoadBalancer[] $lbs */
421 $lbs = [];
422 if ( $opts['cluster'] !== false ) {
423 $lbs[] = $this->getExternalLB( $opts['cluster'] );
424 } elseif ( $opts['wiki'] !== false ) {
425 $lbs[] = $this->getMainLB( $opts['wiki'] );
426 } else {
427 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
428 $lbs[] = $lb;
429 } );
430 if ( !$lbs ) {
431 return; // nothing actually used
432 }
433 }
434
435 // Get all the master positions of applicable DBs right now.
436 // This can be faster since waiting on one cluster reduces the
437 // time needed to wait on the next clusters.
438 $masterPositions = array_fill( 0, count( $lbs ), false );
439 foreach ( $lbs as $i => $lb ) {
440 if ( $lb->getServerCount() <= 1 ) {
441 // Bug 27975 - Don't try to wait for replica DBs if there are none
442 // Prevents permission error when getting master position
443 continue;
444 } elseif ( $opts['ifWritesSince']
445 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
446 ) {
447 continue; // no writes since the last wait
448 }
449 $masterPositions[$i] = $lb->getMasterPos();
450 }
451
452 // Run any listener callbacks *after* getting the DB positions. The more
453 // time spent in the callbacks, the less time is spent in waitForAll().
454 foreach ( $this->replicationWaitCallbacks as $callback ) {
455 $callback();
456 }
457
458 $failed = [];
459 foreach ( $lbs as $i => $lb ) {
460 if ( $masterPositions[$i] ) {
461 // The DBMS may not support getMasterPos()
462 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
463 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
464 }
465 }
466 }
467
468 if ( $failed ) {
469 throw new DBReplicationWaitError(
470 "Could not wait for replica DBs to catch up to " .
471 implode( ', ', $failed )
472 );
473 }
474 }
475
476 /**
477 * Add a callback to be run in every call to waitForReplication() before waiting
478 *
479 * Callbacks must clear any transactions that they start
480 *
481 * @param string $name Callback name
482 * @param callable|null $callback Use null to unset a callback
483 * @since 1.28
484 */
485 public function setWaitForReplicationListener( $name, callable $callback = null ) {
486 if ( $callback ) {
487 $this->replicationWaitCallbacks[$name] = $callback;
488 } else {
489 unset( $this->replicationWaitCallbacks[$name] );
490 }
491 }
492
493 /**
494 * Get a token asserting that no transaction writes are active
495 *
496 * @param string $fname Caller name (e.g. __METHOD__)
497 * @return mixed A value to pass to commitAndWaitForReplication()
498 * @since 1.28
499 */
500 public function getEmptyTransactionTicket( $fname ) {
501 if ( $this->hasMasterChanges() ) {
502 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope." );
503 return null;
504 }
505
506 return $this->ticket;
507 }
508
509 /**
510 * Convenience method for safely running commitMasterChanges()/waitForReplication()
511 *
512 * This will commit and wait unless $ticket indicates it is unsafe to do so
513 *
514 * @param string $fname Caller name (e.g. __METHOD__)
515 * @param mixed $ticket Result of getEmptyTransactionTicket()
516 * @param array $opts Options to waitForReplication()
517 * @throws DBReplicationWaitError
518 * @since 1.28
519 */
520 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
521 if ( $ticket !== $this->ticket ) {
522 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope." );
523 return;
524 }
525
526 // The transaction owner and any caller with the empty transaction ticket can commit
527 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
528 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
529 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
530 $fnameEffective = $this->trxRoundId;
531 } else {
532 $fnameEffective = $fname;
533 }
534
535 $this->commitMasterChanges( $fnameEffective );
536 $this->waitForReplication( $opts );
537 // If a nested caller committed on behalf of $fname, start another empty $fname
538 // transaction, leaving the caller with the same empty transaction state as before.
539 if ( $fnameEffective !== $fname ) {
540 $this->beginMasterChanges( $fnameEffective );
541 }
542 }
543
544 /**
545 * @param string $dbName DB master name (e.g. "db1052")
546 * @return float|bool UNIX timestamp when client last touched the DB or false if not recent
547 * @since 1.28
548 */
549 public function getChronologyProtectorTouched( $dbName ) {
550 return $this->getChronologyProtector()->getTouched( $dbName );
551 }
552
553 /**
554 * Disable the ChronologyProtector for all load balancers
555 *
556 * This can be called at the start of special API entry points
557 *
558 * @since 1.27
559 */
560 public function disableChronologyProtection() {
561 $this->getChronologyProtector()->setEnabled( false );
562 }
563
564 /**
565 * @return ChronologyProtector
566 */
567 protected function getChronologyProtector() {
568 if ( $this->chronProt ) {
569 return $this->chronProt;
570 }
571
572 $this->chronProt = new ChronologyProtector(
573 $this->memCache,
574 [
575 'ip' => $this->requestInfo['IPAddress'],
576 'agent' => $this->requestInfo['UserAgent'],
577 ],
578 isset( $_GET['cpPosTime'] ) ? $_GET['cpPosTime'] : null
579 );
580 $this->chronProt->setLogger( $this->replLogger );
581
582 if ( $this->cliMode ) {
583 $this->chronProt->setEnabled( false );
584 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
585 // Request opted out of using position wait logic. This is useful for requests
586 // done by the job queue or background ETL that do not have a meaningful session.
587 $this->chronProt->setWaitEnabled( false );
588 }
589
590 $this->replLogger->debug( __METHOD__ . ': using request info ' .
591 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
592
593 return $this->chronProt;
594 }
595
596 /**
597 * Get and record all of the staged DB positions into persistent memory storage
598 *
599 * @param ChronologyProtector $cp
600 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
601 * @param string $mode One of (sync, async); whether to wait on remote datacenters
602 */
603 protected function shutdownChronologyProtector(
604 ChronologyProtector $cp, $workCallback, $mode
605 ) {
606 // Record all the master positions needed
607 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
608 $cp->shutdownLB( $lb );
609 } );
610 // Write them to the persistent stash. Try to do something useful by running $work
611 // while ChronologyProtector waits for the stash write to replicate to all DCs.
612 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
613 if ( $unsavedPositions && $workCallback ) {
614 // Invoke callback in case it did not cache the result yet
615 $workCallback(); // work now to block for less time in waitForAll()
616 }
617 // If the positions failed to write to the stash, at least wait on local datacenter
618 // replica DBs to catch up before responding. Even if there are several DCs, this increases
619 // the chance that the user will see their own changes immediately afterwards. As long
620 // as the sticky DC cookie applies (same domain), this is not even an issue.
621 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
622 $masterName = $lb->getServerName( $lb->getWriterIndex() );
623 if ( isset( $unsavedPositions[$masterName] ) ) {
624 $lb->waitForAll( $unsavedPositions[$masterName] );
625 }
626 } );
627 }
628
629 /**
630 * Base parameters to LoadBalancer::__construct()
631 * @return array
632 */
633 final protected function baseLoadBalancerParams() {
634 return [
635 'localDomain' => $this->localDomain,
636 'readOnlyReason' => $this->readOnlyReason,
637 'srvCache' => $this->srvCache,
638 'wanCache' => $this->wanCache,
639 'profiler' => $this->profiler,
640 'trxProfiler' => $this->trxProfiler,
641 'queryLogger' => $this->queryLogger,
642 'connLogger' => $this->connLogger,
643 'replLogger' => $this->replLogger,
644 'errorLogger' => $this->errorLogger,
645 'hostname' => $this->hostname,
646 'cliMode' => $this->cliMode,
647 'agent' => $this->agent
648 ];
649 }
650
651 /**
652 * @param ILoadBalancer $lb
653 */
654 protected function initLoadBalancer( ILoadBalancer $lb ) {
655 if ( $this->trxRoundId !== false ) {
656 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
657 }
658 }
659
660 /**
661 * Set a new table prefix for the existing local domain ID for testing
662 *
663 * @param string $prefix
664 * @since 1.28
665 */
666 public function setDomainPrefix( $prefix ) {
667 $this->localDomain = new DatabaseDomain(
668 $this->localDomain->getDatabase(),
669 null,
670 $prefix
671 );
672
673 $this->forEachLB( function( LoadBalancer $lb ) use ( $prefix ) {
674 $lb->setDomainPrefix( $prefix );
675 } );
676 }
677
678 /**
679 * Close all open database connections on all open load balancers.
680 * @since 1.28
681 */
682 public function closeAll() {
683 $this->forEachLBCallMethod( 'closeAll', [] );
684 }
685
686 /**
687 * @param string $agent Agent name for query profiling
688 * @since 1.28
689 */
690 public function setAgentName( $agent ) {
691 $this->agent = $agent;
692 }
693
694 /**
695 * Append ?cpPosTime parameter to a URL for ChronologyProtector purposes if needed
696 *
697 * Note that unlike cookies, this works accross domains
698 *
699 * @param string $url
700 * @param float $time UNIX timestamp just before shutdown() was called
701 * @return string
702 * @since 1.28
703 */
704 public function appendPreShutdownTimeAsQuery( $url, $time ) {
705 $usedCluster = 0;
706 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
707 $usedCluster |= ( $lb->getServerCount() > 1 );
708 } );
709
710 if ( !$usedCluster ) {
711 return $url; // no master/replica clusters touched
712 }
713
714 return strpos( $url, '?' ) === false ? "$url?cpPosTime=$time" : "$url&cpPosTime=$time";
715 }
716
717 /**
718 * @param array $info Map of fields, including:
719 * - IPAddress : IP address
720 * - UserAgent : User-Agent HTTP header
721 * - ChronologyProtection : cookie/header value specifying ChronologyProtector usage
722 * @since 1.28
723 */
724 public function setRequestInfo( array $info ) {
725 $this->requestInfo = $info + $this->requestInfo;
726 }
727
728 function __destruct() {
729 $this->destroy();
730 }
731 }