Move DatabaseDomain to Rdbms namespace
[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 ILoadBalancer;
34 use IDatabase;
35 use LoadBalancer;
36 use DBTransactionError;
37 use DBReplicationWaitError;
38
39 /**
40 * An interface for generating database load balancers
41 * @ingroup Database
42 */
43 abstract class LBFactory implements ILBFactory {
44 /** @var ChronologyProtector */
45 protected $chronProt;
46 /** @var object|string Class name or object With profileIn/profileOut methods */
47 protected $profiler;
48 /** @var TransactionProfiler */
49 protected $trxProfiler;
50 /** @var LoggerInterface */
51 protected $replLogger;
52 /** @var LoggerInterface */
53 protected $connLogger;
54 /** @var LoggerInterface */
55 protected $queryLogger;
56 /** @var LoggerInterface */
57 protected $perfLogger;
58 /** @var callable Error logger */
59 protected $errorLogger;
60 /** @var BagOStuff */
61 protected $srvCache;
62 /** @var BagOStuff */
63 protected $memCache;
64 /** @var WANObjectCache */
65 protected $wanCache;
66
67 /** @var DatabaseDomain Local domain */
68 protected $localDomain;
69 /** @var string Local hostname of the app server */
70 protected $hostname;
71 /** @var array Web request information about the client */
72 protected $requestInfo;
73
74 /** @var mixed */
75 protected $ticket;
76 /** @var string|bool String if a requested DBO_TRX transaction round is active */
77 protected $trxRoundId = false;
78 /** @var string|bool Reason all LBs are read-only or false if not */
79 protected $readOnlyReason = false;
80 /** @var callable[] */
81 protected $replicationWaitCallbacks = [];
82
83 /** @var bool Whether this PHP instance is for a CLI script */
84 protected $cliMode;
85 /** @var string Agent name for query profiling */
86 protected $agent;
87
88 private static $loggerFields =
89 [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ];
90
91 public function __construct( array $conf ) {
92 $this->localDomain = isset( $conf['localDomain'] )
93 ? DatabaseDomain::newFromId( $conf['localDomain'] )
94 : DatabaseDomain::newUnspecified();
95
96 if ( isset( $conf['readOnlyReason'] ) && is_string( $conf['readOnlyReason'] ) ) {
97 $this->readOnlyReason = $conf['readOnlyReason'];
98 }
99
100 $this->srvCache = isset( $conf['srvCache'] ) ? $conf['srvCache'] : new EmptyBagOStuff();
101 $this->memCache = isset( $conf['memCache'] ) ? $conf['memCache'] : new EmptyBagOStuff();
102 $this->wanCache = isset( $conf['wanCache'] )
103 ? $conf['wanCache']
104 : WANObjectCache::newEmpty();
105
106 foreach ( self::$loggerFields as $key ) {
107 $this->$key = isset( $conf[$key] ) ? $conf[$key] : new \Psr\Log\NullLogger();
108 }
109 $this->errorLogger = isset( $conf['errorLogger'] )
110 ? $conf['errorLogger']
111 : function ( Exception $e ) {
112 trigger_error( E_USER_WARNING, get_class( $e ) . ': ' . $e->getMessage() );
113 };
114
115 $this->profiler = isset( $conf['profiler'] ) ? $conf['profiler'] : null;
116 $this->trxProfiler = isset( $conf['trxProfiler'] )
117 ? $conf['trxProfiler']
118 : new TransactionProfiler();
119
120 $this->requestInfo = [
121 'IPAddress' => isset( $_SERVER[ 'REMOTE_ADDR' ] ) ? $_SERVER[ 'REMOTE_ADDR' ] : '',
122 'UserAgent' => isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '',
123 'ChronologyProtection' => 'true'
124 ];
125
126 $this->cliMode = isset( $conf['cliMode'] ) ? $conf['cliMode'] : PHP_SAPI === 'cli';
127 $this->hostname = isset( $conf['hostname'] ) ? $conf['hostname'] : gethostname();
128 $this->agent = isset( $conf['agent'] ) ? $conf['agent'] : '';
129
130 $this->ticket = mt_rand();
131 }
132
133 public function destroy() {
134 $this->shutdown( self::SHUTDOWN_NO_CHRONPROT );
135 $this->forEachLBCallMethod( 'disable' );
136 }
137
138 public function shutdown(
139 $mode = self::SHUTDOWN_CHRONPROT_SYNC, callable $workCallback = null
140 ) {
141 $chronProt = $this->getChronologyProtector();
142 if ( $mode === self::SHUTDOWN_CHRONPROT_SYNC ) {
143 $this->shutdownChronologyProtector( $chronProt, $workCallback, 'sync' );
144 } elseif ( $mode === self::SHUTDOWN_CHRONPROT_ASYNC ) {
145 $this->shutdownChronologyProtector( $chronProt, null, 'async' );
146 }
147
148 $this->commitMasterChanges( __METHOD__ ); // sanity
149 }
150
151 /**
152 * @see ILBFactory::newMainLB()
153 * @param bool $domain
154 * @return LoadBalancer
155 */
156 abstract public function newMainLB( $domain = false );
157
158 /**
159 * @see ILBFactory::getMainLB()
160 * @param bool $domain
161 * @return LoadBalancer
162 */
163 abstract public function getMainLB( $domain = false );
164
165 /**
166 * @see ILBFactory::newExternalLB()
167 * @param string $cluster
168 * @return LoadBalancer
169 */
170 abstract public function newExternalLB( $cluster );
171
172 /**
173 * @see ILBFactory::getExternalLB()
174 * @param string $cluster
175 * @return LoadBalancer
176 */
177 abstract public function getExternalLB( $cluster );
178
179 /**
180 * Call a method of each tracked load balancer
181 *
182 * @param string $methodName
183 * @param array $args
184 */
185 protected function forEachLBCallMethod( $methodName, array $args = [] ) {
186 $this->forEachLB(
187 function ( ILoadBalancer $loadBalancer, $methodName, array $args ) {
188 call_user_func_array( [ $loadBalancer, $methodName ], $args );
189 },
190 [ $methodName, $args ]
191 );
192 }
193
194 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
195 $this->forEachLBCallMethod( 'flushReplicaSnapshots', [ $fname ] );
196 }
197
198 public function commitAll( $fname = __METHOD__, array $options = [] ) {
199 $this->commitMasterChanges( $fname, $options );
200 $this->forEachLBCallMethod( 'commitAll', [ $fname ] );
201 }
202
203 public function beginMasterChanges( $fname = __METHOD__ ) {
204 if ( $this->trxRoundId !== false ) {
205 throw new DBTransactionError(
206 null,
207 "$fname: transaction round '{$this->trxRoundId}' already started."
208 );
209 }
210 $this->trxRoundId = $fname;
211 // Set DBO_TRX flags on all appropriate DBs
212 $this->forEachLBCallMethod( 'beginMasterChanges', [ $fname ] );
213 }
214
215 public function commitMasterChanges( $fname = __METHOD__, array $options = [] ) {
216 if ( $this->trxRoundId !== false && $this->trxRoundId !== $fname ) {
217 throw new DBTransactionError(
218 null,
219 "$fname: transaction round '{$this->trxRoundId}' still running."
220 );
221 }
222 /** @noinspection PhpUnusedLocalVariableInspection */
223 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
224 // Run pre-commit callbacks and suppress post-commit callbacks, aborting on failure
225 $this->forEachLBCallMethod( 'finalizeMasterChanges' );
226 $this->trxRoundId = false;
227 // Perform pre-commit checks, aborting on failure
228 $this->forEachLBCallMethod( 'approveMasterChanges', [ $options ] );
229 // Log the DBs and methods involved in multi-DB transactions
230 $this->logIfMultiDbTransaction();
231 // Actually perform the commit on all master DB connections and revert DBO_TRX
232 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
233 // Run all post-commit callbacks
234 /** @var Exception $e */
235 $e = null; // first callback exception
236 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$e ) {
237 $ex = $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_COMMIT );
238 $e = $e ?: $ex;
239 } );
240 // Commit any dangling DBO_TRX transactions from callbacks on one DB to another DB
241 $this->forEachLBCallMethod( 'commitMasterChanges', [ $fname ] );
242 // Throw any last post-commit callback error
243 if ( $e instanceof Exception ) {
244 throw $e;
245 }
246 }
247
248 public function rollbackMasterChanges( $fname = __METHOD__ ) {
249 $this->trxRoundId = false;
250 $this->forEachLBCallMethod( 'suppressTransactionEndCallbacks' );
251 $this->forEachLBCallMethod( 'rollbackMasterChanges', [ $fname ] );
252 // Run all post-rollback callbacks
253 $this->forEachLB( function ( ILoadBalancer $lb ) {
254 $lb->runMasterPostTrxCallbacks( IDatabase::TRIGGER_ROLLBACK );
255 } );
256 }
257
258 /**
259 * Log query info if multi DB transactions are going to be committed now
260 */
261 private function logIfMultiDbTransaction() {
262 $callersByDB = [];
263 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$callersByDB ) {
264 $masterName = $lb->getServerName( $lb->getWriterIndex() );
265 $callers = $lb->pendingMasterChangeCallers();
266 if ( $callers ) {
267 $callersByDB[$masterName] = $callers;
268 }
269 } );
270
271 if ( count( $callersByDB ) >= 2 ) {
272 $dbs = implode( ', ', array_keys( $callersByDB ) );
273 $msg = "Multi-DB transaction [{$dbs}]:\n";
274 foreach ( $callersByDB as $db => $callers ) {
275 $msg .= "$db: " . implode( '; ', $callers ) . "\n";
276 }
277 $this->queryLogger->info( $msg );
278 }
279 }
280
281 public function hasMasterChanges() {
282 $ret = false;
283 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
284 $ret = $ret || $lb->hasMasterChanges();
285 } );
286
287 return $ret;
288 }
289
290 public function laggedReplicaUsed() {
291 $ret = false;
292 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$ret ) {
293 $ret = $ret || $lb->laggedReplicaUsed();
294 } );
295
296 return $ret;
297 }
298
299 public function hasOrMadeRecentMasterChanges( $age = null ) {
300 $ret = false;
301 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $age, &$ret ) {
302 $ret = $ret || $lb->hasOrMadeRecentMasterChanges( $age );
303 } );
304 return $ret;
305 }
306
307 public function waitForReplication( array $opts = [] ) {
308 $opts += [
309 'domain' => false,
310 'cluster' => false,
311 'timeout' => 60,
312 'ifWritesSince' => null
313 ];
314
315 if ( $opts['domain'] === false && isset( $opts['wiki'] ) ) {
316 $opts['domain'] = $opts['wiki']; // b/c
317 }
318
319 // Figure out which clusters need to be checked
320 /** @var ILoadBalancer[] $lbs */
321 $lbs = [];
322 if ( $opts['cluster'] !== false ) {
323 $lbs[] = $this->getExternalLB( $opts['cluster'] );
324 } elseif ( $opts['domain'] !== false ) {
325 $lbs[] = $this->getMainLB( $opts['domain'] );
326 } else {
327 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$lbs ) {
328 $lbs[] = $lb;
329 } );
330 if ( !$lbs ) {
331 return; // nothing actually used
332 }
333 }
334
335 // Get all the master positions of applicable DBs right now.
336 // This can be faster since waiting on one cluster reduces the
337 // time needed to wait on the next clusters.
338 $masterPositions = array_fill( 0, count( $lbs ), false );
339 foreach ( $lbs as $i => $lb ) {
340 if ( $lb->getServerCount() <= 1 ) {
341 // Bug 27975 - Don't try to wait for replica DBs if there are none
342 // Prevents permission error when getting master position
343 continue;
344 } elseif ( $opts['ifWritesSince']
345 && $lb->lastMasterChangeTimestamp() < $opts['ifWritesSince']
346 ) {
347 continue; // no writes since the last wait
348 }
349 $masterPositions[$i] = $lb->getMasterPos();
350 }
351
352 // Run any listener callbacks *after* getting the DB positions. The more
353 // time spent in the callbacks, the less time is spent in waitForAll().
354 foreach ( $this->replicationWaitCallbacks as $callback ) {
355 $callback();
356 }
357
358 $failed = [];
359 foreach ( $lbs as $i => $lb ) {
360 if ( $masterPositions[$i] ) {
361 // The DBMS may not support getMasterPos()
362 if ( !$lb->waitForAll( $masterPositions[$i], $opts['timeout'] ) ) {
363 $failed[] = $lb->getServerName( $lb->getWriterIndex() );
364 }
365 }
366 }
367
368 if ( $failed ) {
369 throw new DBReplicationWaitError(
370 null,
371 "Could not wait for replica DBs to catch up to " .
372 implode( ', ', $failed )
373 );
374 }
375 }
376
377 public function setWaitForReplicationListener( $name, callable $callback = null ) {
378 if ( $callback ) {
379 $this->replicationWaitCallbacks[$name] = $callback;
380 } else {
381 unset( $this->replicationWaitCallbacks[$name] );
382 }
383 }
384
385 public function getEmptyTransactionTicket( $fname ) {
386 if ( $this->hasMasterChanges() ) {
387 $this->queryLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
388 ( new RuntimeException() )->getTraceAsString() );
389
390 return null;
391 }
392
393 return $this->ticket;
394 }
395
396 public function commitAndWaitForReplication( $fname, $ticket, array $opts = [] ) {
397 if ( $ticket !== $this->ticket ) {
398 $this->perfLogger->error( __METHOD__ . ": $fname does not have outer scope.\n" .
399 ( new RuntimeException() )->getTraceAsString() );
400
401 return;
402 }
403
404 // The transaction owner and any caller with the empty transaction ticket can commit
405 // so that getEmptyTransactionTicket() callers don't risk seeing DBTransactionError.
406 if ( $this->trxRoundId !== false && $fname !== $this->trxRoundId ) {
407 $this->queryLogger->info( "$fname: committing on behalf of {$this->trxRoundId}." );
408 $fnameEffective = $this->trxRoundId;
409 } else {
410 $fnameEffective = $fname;
411 }
412
413 $this->commitMasterChanges( $fnameEffective );
414 $this->waitForReplication( $opts );
415 // If a nested caller committed on behalf of $fname, start another empty $fname
416 // transaction, leaving the caller with the same empty transaction state as before.
417 if ( $fnameEffective !== $fname ) {
418 $this->beginMasterChanges( $fnameEffective );
419 }
420 }
421
422 public function getChronologyProtectorTouched( $dbName ) {
423 return $this->getChronologyProtector()->getTouched( $dbName );
424 }
425
426 public function disableChronologyProtection() {
427 $this->getChronologyProtector()->setEnabled( false );
428 }
429
430 /**
431 * @return ChronologyProtector
432 */
433 protected function getChronologyProtector() {
434 if ( $this->chronProt ) {
435 return $this->chronProt;
436 }
437
438 $this->chronProt = new ChronologyProtector(
439 $this->memCache,
440 [
441 'ip' => $this->requestInfo['IPAddress'],
442 'agent' => $this->requestInfo['UserAgent'],
443 ],
444 isset( $_GET['cpPosTime'] ) ? $_GET['cpPosTime'] : null
445 );
446 $this->chronProt->setLogger( $this->replLogger );
447
448 if ( $this->cliMode ) {
449 $this->chronProt->setEnabled( false );
450 } elseif ( $this->requestInfo['ChronologyProtection'] === 'false' ) {
451 // Request opted out of using position wait logic. This is useful for requests
452 // done by the job queue or background ETL that do not have a meaningful session.
453 $this->chronProt->setWaitEnabled( false );
454 }
455
456 $this->replLogger->debug( __METHOD__ . ': using request info ' .
457 json_encode( $this->requestInfo, JSON_PRETTY_PRINT ) );
458
459 return $this->chronProt;
460 }
461
462 /**
463 * Get and record all of the staged DB positions into persistent memory storage
464 *
465 * @param ChronologyProtector $cp
466 * @param callable|null $workCallback Work to do instead of waiting on syncing positions
467 * @param string $mode One of (sync, async); whether to wait on remote datacenters
468 */
469 protected function shutdownChronologyProtector(
470 ChronologyProtector $cp, $workCallback, $mode
471 ) {
472 // Record all the master positions needed
473 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $cp ) {
474 $cp->shutdownLB( $lb );
475 } );
476 // Write them to the persistent stash. Try to do something useful by running $work
477 // while ChronologyProtector waits for the stash write to replicate to all DCs.
478 $unsavedPositions = $cp->shutdown( $workCallback, $mode );
479 if ( $unsavedPositions && $workCallback ) {
480 // Invoke callback in case it did not cache the result yet
481 $workCallback(); // work now to block for less time in waitForAll()
482 }
483 // If the positions failed to write to the stash, at least wait on local datacenter
484 // replica DBs to catch up before responding. Even if there are several DCs, this increases
485 // the chance that the user will see their own changes immediately afterwards. As long
486 // as the sticky DC cookie applies (same domain), this is not even an issue.
487 $this->forEachLB( function ( ILoadBalancer $lb ) use ( $unsavedPositions ) {
488 $masterName = $lb->getServerName( $lb->getWriterIndex() );
489 if ( isset( $unsavedPositions[$masterName] ) ) {
490 $lb->waitForAll( $unsavedPositions[$masterName] );
491 }
492 } );
493 }
494
495 /**
496 * Base parameters to LoadBalancer::__construct()
497 * @return array
498 */
499 final protected function baseLoadBalancerParams() {
500 return [
501 'localDomain' => $this->localDomain,
502 'readOnlyReason' => $this->readOnlyReason,
503 'srvCache' => $this->srvCache,
504 'wanCache' => $this->wanCache,
505 'profiler' => $this->profiler,
506 'trxProfiler' => $this->trxProfiler,
507 'queryLogger' => $this->queryLogger,
508 'connLogger' => $this->connLogger,
509 'replLogger' => $this->replLogger,
510 'errorLogger' => $this->errorLogger,
511 'hostname' => $this->hostname,
512 'cliMode' => $this->cliMode,
513 'agent' => $this->agent
514 ];
515 }
516
517 /**
518 * @param ILoadBalancer $lb
519 */
520 protected function initLoadBalancer( ILoadBalancer $lb ) {
521 if ( $this->trxRoundId !== false ) {
522 $lb->beginMasterChanges( $this->trxRoundId ); // set DBO_TRX
523 }
524 }
525
526 public function setDomainPrefix( $prefix ) {
527 $this->localDomain = new DatabaseDomain(
528 $this->localDomain->getDatabase(),
529 null,
530 $prefix
531 );
532
533 $this->forEachLB( function( ILoadBalancer $lb ) use ( $prefix ) {
534 $lb->setDomainPrefix( $prefix );
535 } );
536 }
537
538 public function closeAll() {
539 $this->forEachLBCallMethod( 'closeAll', [] );
540 }
541
542 public function setAgentName( $agent ) {
543 $this->agent = $agent;
544 }
545
546 public function appendPreShutdownTimeAsQuery( $url, $time ) {
547 $usedCluster = 0;
548 $this->forEachLB( function ( ILoadBalancer $lb ) use ( &$usedCluster ) {
549 $usedCluster |= ( $lb->getServerCount() > 1 );
550 } );
551
552 if ( !$usedCluster ) {
553 return $url; // no master/replica clusters touched
554 }
555
556 return strpos( $url, '?' ) === false ? "$url?cpPosTime=$time" : "$url&cpPosTime=$time";
557 }
558
559 public function setRequestInfo( array $info ) {
560 $this->requestInfo = $info + $this->requestInfo;
561 }
562
563 /**
564 * Make PHP ignore user aborts/disconnects until the returned
565 * value leaves scope. This returns null and does nothing in CLI mode.
566 *
567 * @return ScopedCallback|null
568 */
569 final protected function getScopedPHPBehaviorForCommit() {
570 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
571 $old = ignore_user_abort( true ); // avoid half-finished operations
572 return new ScopedCallback( function () use ( $old ) {
573 ignore_user_abort( $old );
574 } );
575 }
576
577 return null;
578 }
579
580 function __destruct() {
581 $this->destroy();
582 }
583 }