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