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