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