Merge "Create IResultWrapper interface for type-hints"
[lhc/web/wiklou.git] / includes / libs / rdbms / loadbalancer / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing manager
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 use Psr\Log\LoggerInterface;
24 use Psr\Log\NullLogger;
25 use Wikimedia\ScopedCallback;
26 use Wikimedia\Rdbms\TransactionProfiler;
27 use Wikimedia\Rdbms\ILoadMonitor;
28 use Wikimedia\Rdbms\DatabaseDomain;
29 use Wikimedia\Rdbms\ILoadBalancer;
30 use Wikimedia\Rdbms\DBMasterPos;
31
32 /**
33 * Database connection, tracking, load balancing, and transaction manager for a cluster
34 *
35 * @ingroup Database
36 */
37 class LoadBalancer implements ILoadBalancer {
38 /** @var array[] Map of (server index => server config array) */
39 private $mServers;
40 /** @var IDatabase[][][] Map of local/foreignUsed/foreignFree => server index => IDatabase array */
41 private $mConns;
42 /** @var float[] Map of (server index => weight) */
43 private $mLoads;
44 /** @var array[] Map of (group => server index => weight) */
45 private $mGroupLoads;
46 /** @var bool Whether to disregard replica DB lag as a factor in replica DB selection */
47 private $mAllowLagged;
48 /** @var integer Seconds to spend waiting on replica DB lag to resolve */
49 private $mWaitTimeout;
50 /** @var array The LoadMonitor configuration */
51 private $loadMonitorConfig;
52 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
53 private $tableAliases = [];
54
55 /** @var ILoadMonitor */
56 private $loadMonitor;
57 /** @var BagOStuff */
58 private $srvCache;
59 /** @var BagOStuff */
60 private $memCache;
61 /** @var WANObjectCache */
62 private $wanCache;
63 /** @var object|string Class name or object With profileIn/profileOut methods */
64 protected $profiler;
65 /** @var TransactionProfiler */
66 protected $trxProfiler;
67 /** @var LoggerInterface */
68 protected $replLogger;
69 /** @var LoggerInterface */
70 protected $connLogger;
71 /** @var LoggerInterface */
72 protected $queryLogger;
73 /** @var LoggerInterface */
74 protected $perfLogger;
75
76 /** @var bool|IDatabase Database connection that caused a problem */
77 private $mErrorConnection;
78 /** @var integer The generic (not query grouped) replica DB index (of $mServers) */
79 private $mReadIndex;
80 /** @var bool|DBMasterPos False if not set */
81 private $mWaitForPos;
82 /** @var bool Whether the generic reader fell back to a lagged replica DB */
83 private $laggedReplicaMode = false;
84 /** @var bool Whether the generic reader fell back to a lagged replica DB */
85 private $allReplicasDownMode = false;
86 /** @var string The last DB selection or connection error */
87 private $mLastError = 'Unknown error';
88 /** @var string|bool Reason the LB is read-only or false if not */
89 private $readOnlyReason = false;
90 /** @var integer Total connections opened */
91 private $connsOpened = 0;
92 /** @var string|bool String if a requested DBO_TRX transaction round is active */
93 private $trxRoundId = false;
94 /** @var array[] Map of (name => callable) */
95 private $trxRecurringCallbacks = [];
96 /** @var DatabaseDomain Local Domain ID and default for selectDB() calls */
97 private $localDomain;
98 /** @var string Alternate ID string for the domain instead of DatabaseDomain::getId() */
99 private $localDomainIdAlias;
100 /** @var string Current server name */
101 private $host;
102 /** @var bool Whether this PHP instance is for a CLI script */
103 protected $cliMode;
104 /** @var string Agent name for query profiling */
105 protected $agent;
106
107 /** @var callable Exception logger */
108 private $errorLogger;
109
110 /** @var boolean */
111 private $disabled = false;
112
113 /** @var integer Warn when this many connection are held */
114 const CONN_HELD_WARN_THRESHOLD = 10;
115
116 /** @var integer Default 'max lag' when unspecified */
117 const MAX_LAG_DEFAULT = 10;
118 /** @var integer Seconds to cache master server read-only status */
119 const TTL_CACHE_READONLY = 5;
120
121 public function __construct( array $params ) {
122 if ( !isset( $params['servers'] ) ) {
123 throw new InvalidArgumentException( __CLASS__ . ': missing servers parameter' );
124 }
125 $this->mServers = $params['servers'];
126
127 $this->localDomain = isset( $params['localDomain'] )
128 ? DatabaseDomain::newFromId( $params['localDomain'] )
129 : DatabaseDomain::newUnspecified();
130 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
131 // always true, gracefully handle the case when they fail to account for escaping.
132 if ( $this->localDomain->getTablePrefix() != '' ) {
133 $this->localDomainIdAlias =
134 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
135 } else {
136 $this->localDomainIdAlias = $this->localDomain->getDatabase();
137 }
138
139 $this->mWaitTimeout = isset( $params['waitTimeout'] ) ? $params['waitTimeout'] : 10;
140
141 $this->mReadIndex = -1;
142 $this->mConns = [
143 'local' => [],
144 'foreignUsed' => [],
145 'foreignFree' => []
146 ];
147 $this->mLoads = [];
148 $this->mWaitForPos = false;
149 $this->mErrorConnection = false;
150 $this->mAllowLagged = false;
151
152 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
153 $this->readOnlyReason = $params['readOnlyReason'];
154 }
155
156 if ( isset( $params['loadMonitor'] ) ) {
157 $this->loadMonitorConfig = $params['loadMonitor'];
158 } else {
159 $this->loadMonitorConfig = [ 'class' => 'LoadMonitorNull' ];
160 }
161
162 foreach ( $params['servers'] as $i => $server ) {
163 $this->mLoads[$i] = $server['load'];
164 if ( isset( $server['groupLoads'] ) ) {
165 foreach ( $server['groupLoads'] as $group => $ratio ) {
166 if ( !isset( $this->mGroupLoads[$group] ) ) {
167 $this->mGroupLoads[$group] = [];
168 }
169 $this->mGroupLoads[$group][$i] = $ratio;
170 }
171 }
172 }
173
174 if ( isset( $params['srvCache'] ) ) {
175 $this->srvCache = $params['srvCache'];
176 } else {
177 $this->srvCache = new EmptyBagOStuff();
178 }
179 if ( isset( $params['memCache'] ) ) {
180 $this->memCache = $params['memCache'];
181 } else {
182 $this->memCache = new EmptyBagOStuff();
183 }
184 if ( isset( $params['wanCache'] ) ) {
185 $this->wanCache = $params['wanCache'];
186 } else {
187 $this->wanCache = WANObjectCache::newEmpty();
188 }
189 $this->profiler = isset( $params['profiler'] ) ? $params['profiler'] : null;
190 if ( isset( $params['trxProfiler'] ) ) {
191 $this->trxProfiler = $params['trxProfiler'];
192 } else {
193 $this->trxProfiler = new TransactionProfiler();
194 }
195
196 $this->errorLogger = isset( $params['errorLogger'] )
197 ? $params['errorLogger']
198 : function ( Exception $e ) {
199 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
200 };
201
202 foreach ( [ 'replLogger', 'connLogger', 'queryLogger', 'perfLogger' ] as $key ) {
203 $this->$key = isset( $params[$key] ) ? $params[$key] : new NullLogger();
204 }
205
206 $this->host = isset( $params['hostname'] )
207 ? $params['hostname']
208 : ( gethostname() ?: 'unknown' );
209 $this->cliMode = isset( $params['cliMode'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
210 $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
211 }
212
213 /**
214 * Get a LoadMonitor instance
215 *
216 * @return ILoadMonitor
217 */
218 private function getLoadMonitor() {
219 if ( !isset( $this->loadMonitor ) ) {
220 $compat = [
221 'LoadMonitor' => Wikimedia\Rdbms\LoadMonitor::class,
222 'LoadMonitorNull' => Wikimedia\Rdbms\LoadMonitorNull::class,
223 'LoadMonitorMySQL' => Wikimedia\Rdbms\LoadMonitorMySQL::class,
224 ];
225
226 $class = $this->loadMonitorConfig['class'];
227 if ( isset( $compat[$class] ) ) {
228 $class = $compat[$class];
229 }
230
231 $this->loadMonitor = new $class(
232 $this, $this->srvCache, $this->memCache, $this->loadMonitorConfig );
233 $this->loadMonitor->setLogger( $this->replLogger );
234 }
235
236 return $this->loadMonitor;
237 }
238
239 /**
240 * @param array $loads
241 * @param bool|string $domain Domain to get non-lagged for
242 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
243 * @return bool|int|string
244 */
245 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
246 $lags = $this->getLagTimes( $domain );
247
248 # Unset excessively lagged servers
249 foreach ( $lags as $i => $lag ) {
250 if ( $i != 0 ) {
251 # How much lag this server nominally is allowed to have
252 $maxServerLag = isset( $this->mServers[$i]['max lag'] )
253 ? $this->mServers[$i]['max lag']
254 : self::MAX_LAG_DEFAULT; // default
255 # Constrain that futher by $maxLag argument
256 $maxServerLag = min( $maxServerLag, $maxLag );
257
258 $host = $this->getServerName( $i );
259 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
260 $this->replLogger->error(
261 "Server {host} (#$i) is not replicating?", [ 'host' => $host ] );
262 unset( $loads[$i] );
263 } elseif ( $lag > $maxServerLag ) {
264 $this->replLogger->warning(
265 "Server {host} (#$i) has {lag} seconds of lag (>= {maxlag})",
266 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
267 );
268 unset( $loads[$i] );
269 }
270 }
271 }
272
273 # Find out if all the replica DBs with non-zero load are lagged
274 $sum = 0;
275 foreach ( $loads as $load ) {
276 $sum += $load;
277 }
278 if ( $sum == 0 ) {
279 # No appropriate DB servers except maybe the master and some replica DBs with zero load
280 # Do NOT use the master
281 # Instead, this function will return false, triggering read-only mode,
282 # and a lagged replica DB will be used instead.
283 return false;
284 }
285
286 if ( count( $loads ) == 0 ) {
287 return false;
288 }
289
290 # Return a random representative of the remainder
291 return ArrayUtils::pickRandom( $loads );
292 }
293
294 public function getReaderIndex( $group = false, $domain = false ) {
295 if ( count( $this->mServers ) == 1 ) {
296 # Skip the load balancing if there's only one server
297 return $this->getWriterIndex();
298 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
299 # Shortcut if generic reader exists already
300 return $this->mReadIndex;
301 }
302
303 # Find the relevant load array
304 if ( $group !== false ) {
305 if ( isset( $this->mGroupLoads[$group] ) ) {
306 $nonErrorLoads = $this->mGroupLoads[$group];
307 } else {
308 # No loads for this group, return false and the caller can use some other group
309 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
310
311 return false;
312 }
313 } else {
314 $nonErrorLoads = $this->mLoads;
315 }
316
317 if ( !count( $nonErrorLoads ) ) {
318 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
319 }
320
321 # Scale the configured load ratios according to the dynamic load if supported
322 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $domain );
323
324 $laggedReplicaMode = false;
325
326 # No server found yet
327 $i = false;
328 # First try quickly looking through the available servers for a server that
329 # meets our criteria
330 $currentLoads = $nonErrorLoads;
331 while ( count( $currentLoads ) ) {
332 if ( $this->mAllowLagged || $laggedReplicaMode ) {
333 $i = ArrayUtils::pickRandom( $currentLoads );
334 } else {
335 $i = false;
336 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
337 # ChronologyProtecter causes mWaitForPos to be set via sessions.
338 # This triggers doWait() after connect, so it's especially good to
339 # avoid lagged servers so as to avoid just blocking in that method.
340 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
341 # Aim for <= 1 second of waiting (being too picky can backfire)
342 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
343 }
344 if ( $i === false ) {
345 # Any server with less lag than it's 'max lag' param is preferable
346 $i = $this->getRandomNonLagged( $currentLoads, $domain );
347 }
348 if ( $i === false && count( $currentLoads ) != 0 ) {
349 # All replica DBs lagged. Switch to read-only mode
350 $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
351 $i = ArrayUtils::pickRandom( $currentLoads );
352 $laggedReplicaMode = true;
353 }
354 }
355
356 if ( $i === false ) {
357 # pickRandom() returned false
358 # This is permanent and means the configuration or the load monitor
359 # wants us to return false.
360 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
361
362 return false;
363 }
364
365 $serverName = $this->getServerName( $i );
366 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
367
368 $conn = $this->openConnection( $i, $domain );
369 if ( !$conn ) {
370 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
371 unset( $nonErrorLoads[$i] );
372 unset( $currentLoads[$i] );
373 $i = false;
374 continue;
375 }
376
377 // Decrement reference counter, we are finished with this connection.
378 // It will be incremented for the caller later.
379 if ( $domain !== false ) {
380 $this->reuseConnection( $conn );
381 }
382
383 # Return this server
384 break;
385 }
386
387 # If all servers were down, quit now
388 if ( !count( $nonErrorLoads ) ) {
389 $this->connLogger->error( "All servers down" );
390 }
391
392 if ( $i !== false ) {
393 # Replica DB connection successful.
394 # Wait for the session master pos for a short time.
395 if ( $this->mWaitForPos && $i > 0 ) {
396 $this->doWait( $i );
397 }
398 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
399 $this->mReadIndex = $i;
400 # Record if the generic reader index is in "lagged replica DB" mode
401 if ( $laggedReplicaMode ) {
402 $this->laggedReplicaMode = true;
403 }
404 }
405 $serverName = $this->getServerName( $i );
406 $this->connLogger->debug(
407 __METHOD__ . ": using server $serverName for group '$group'" );
408 }
409
410 return $i;
411 }
412
413 /**
414 * @param DBMasterPos|false $pos
415 */
416 public function waitFor( $pos ) {
417 $this->mWaitForPos = $pos;
418 $i = $this->mReadIndex;
419
420 if ( $i > 0 ) {
421 if ( !$this->doWait( $i ) ) {
422 $this->laggedReplicaMode = true;
423 }
424 }
425 }
426
427 public function waitForOne( $pos, $timeout = null ) {
428 $this->mWaitForPos = $pos;
429
430 $i = $this->mReadIndex;
431 if ( $i <= 0 ) {
432 // Pick a generic replica DB if there isn't one yet
433 $readLoads = $this->mLoads;
434 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
435 $readLoads = array_filter( $readLoads ); // with non-zero load
436 $i = ArrayUtils::pickRandom( $readLoads );
437 }
438
439 if ( $i > 0 ) {
440 $ok = $this->doWait( $i, true, $timeout );
441 } else {
442 $ok = true; // no applicable loads
443 }
444
445 return $ok;
446 }
447
448 public function waitForAll( $pos, $timeout = null ) {
449 $this->mWaitForPos = $pos;
450 $serverCount = count( $this->mServers );
451
452 $ok = true;
453 for ( $i = 1; $i < $serverCount; $i++ ) {
454 if ( $this->mLoads[$i] > 0 ) {
455 $ok = $this->doWait( $i, true, $timeout ) && $ok;
456 }
457 }
458
459 return $ok;
460 }
461
462 /**
463 * @param int $i
464 * @return IDatabase|bool
465 */
466 public function getAnyOpenConnection( $i ) {
467 foreach ( $this->mConns as $connsByServer ) {
468 if ( !empty( $connsByServer[$i] ) ) {
469 /** @var $serverConns IDatabase[] */
470 $serverConns = $connsByServer[$i];
471
472 return reset( $serverConns );
473 }
474 }
475
476 return false;
477 }
478
479 /**
480 * Wait for a given replica DB to catch up to the master pos stored in $this
481 * @param int $index Server index
482 * @param bool $open Check the server even if a new connection has to be made
483 * @param int $timeout Max seconds to wait; default is mWaitTimeout
484 * @return bool
485 */
486 protected function doWait( $index, $open = false, $timeout = null ) {
487 $close = false; // close the connection afterwards
488
489 // Check if we already know that the DB has reached this point
490 $server = $this->getServerName( $index );
491 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
492 /** @var DBMasterPos $knownReachedPos */
493 $knownReachedPos = $this->srvCache->get( $key );
494 if (
495 $knownReachedPos instanceof DBMasterPos &&
496 $knownReachedPos->hasReached( $this->mWaitForPos )
497 ) {
498 $this->replLogger->debug( __METHOD__ .
499 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
500 return true;
501 }
502
503 // Find a connection to wait on, creating one if needed and allowed
504 $conn = $this->getAnyOpenConnection( $index );
505 if ( !$conn ) {
506 if ( !$open ) {
507 $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
508
509 return false;
510 } else {
511 $conn = $this->openConnection( $index, self::DOMAIN_ANY );
512 if ( !$conn ) {
513 $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
514
515 return false;
516 }
517 // Avoid connection spam in waitForAll() when connections
518 // are made just for the sake of doing this lag check.
519 $close = true;
520 }
521 }
522
523 $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
524 $timeout = $timeout ?: $this->mWaitTimeout;
525 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
526
527 if ( $result == -1 || is_null( $result ) ) {
528 // Timed out waiting for replica DB, use master instead
529 $this->replLogger->warning(
530 __METHOD__ . ": Timed out waiting on {host} pos {$this->mWaitForPos}",
531 [ 'host' => $server ]
532 );
533 $ok = false;
534 } else {
535 $this->replLogger->info( __METHOD__ . ": Done" );
536 $ok = true;
537 // Remember that the DB reached this point
538 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
539 }
540
541 if ( $close ) {
542 $this->closeConnection( $conn );
543 }
544
545 return $ok;
546 }
547
548 /**
549 * @see ILoadBalancer::getConnection()
550 *
551 * @param int $i
552 * @param array $groups
553 * @param bool $domain
554 * @return Database
555 * @throws DBConnectionError
556 */
557 public function getConnection( $i, $groups = [], $domain = false ) {
558 if ( $i === null || $i === false ) {
559 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
560 ' with invalid server index' );
561 }
562
563 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
564 $domain = false; // local connection requested
565 }
566
567 $groups = ( $groups === false || $groups === [] )
568 ? [ false ] // check one "group": the generic pool
569 : (array)$groups;
570
571 $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
572 $oldConnsOpened = $this->connsOpened; // connections open now
573
574 if ( $i == self::DB_MASTER ) {
575 $i = $this->getWriterIndex();
576 } else {
577 # Try to find an available server in any the query groups (in order)
578 foreach ( $groups as $group ) {
579 $groupIndex = $this->getReaderIndex( $group, $domain );
580 if ( $groupIndex !== false ) {
581 $i = $groupIndex;
582 break;
583 }
584 }
585 }
586
587 # Operation-based index
588 if ( $i == self::DB_REPLICA ) {
589 $this->mLastError = 'Unknown error'; // reset error string
590 # Try the general server pool if $groups are unavailable.
591 $i = ( $groups === [ false ] )
592 ? false // don't bother with this if that is what was tried above
593 : $this->getReaderIndex( false, $domain );
594 # Couldn't find a working server in getReaderIndex()?
595 if ( $i === false ) {
596 $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
597 // Throw an exception
598 $this->reportConnectionError();
599 return null; // not reached
600 }
601 }
602
603 # Now we have an explicit index into the servers array
604 $conn = $this->openConnection( $i, $domain );
605 if ( !$conn ) {
606 // Throw an exception
607 $this->reportConnectionError();
608 return null; // not reached
609 }
610
611 # Profile any new connections that happen
612 if ( $this->connsOpened > $oldConnsOpened ) {
613 $host = $conn->getServer();
614 $dbname = $conn->getDBname();
615 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
616 }
617
618 if ( $masterOnly ) {
619 # Make master-requested DB handles inherit any read-only mode setting
620 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
621 }
622
623 return $conn;
624 }
625
626 public function reuseConnection( $conn ) {
627 $serverIndex = $conn->getLBInfo( 'serverIndex' );
628 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
629 if ( $serverIndex === null || $refCount === null ) {
630 /**
631 * This can happen in code like:
632 * foreach ( $dbs as $db ) {
633 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
634 * ...
635 * $lb->reuseConnection( $conn );
636 * }
637 * When a connection to the local DB is opened in this way, reuseConnection()
638 * should be ignored
639 */
640 return;
641 } elseif ( $conn instanceof DBConnRef ) {
642 // DBConnRef already handles calling reuseConnection() and only passes the live
643 // Database instance to this method. Any caller passing in a DBConnRef is broken.
644 $this->connLogger->error( __METHOD__ . ": got DBConnRef instance.\n" .
645 ( new RuntimeException() )->getTraceAsString() );
646
647 return;
648 }
649
650 if ( $this->disabled ) {
651 return; // DBConnRef handle probably survived longer than the LoadBalancer
652 }
653
654 $domain = $conn->getDomainID();
655 if ( !isset( $this->mConns['foreignUsed'][$serverIndex][$domain] ) ) {
656 throw new InvalidArgumentException( __METHOD__ .
657 ": connection $serverIndex/$domain not found; it may have already been freed." );
658 } elseif ( $this->mConns['foreignUsed'][$serverIndex][$domain] !== $conn ) {
659 throw new InvalidArgumentException( __METHOD__ .
660 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
661 }
662 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
663 if ( $refCount <= 0 ) {
664 $this->mConns['foreignFree'][$serverIndex][$domain] = $conn;
665 unset( $this->mConns['foreignUsed'][$serverIndex][$domain] );
666 if ( !$this->mConns['foreignUsed'][$serverIndex] ) {
667 unset( $this->mConns[ 'foreignUsed' ][$serverIndex] ); // clean up
668 }
669 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
670 } else {
671 $this->connLogger->debug( __METHOD__ .
672 ": reference count for $serverIndex/$domain reduced to $refCount" );
673 }
674 }
675
676 public function getConnectionRef( $db, $groups = [], $domain = false ) {
677 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
678
679 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
680 }
681
682 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
683 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
684
685 return new DBConnRef( $this, [ $db, $groups, $domain ] );
686 }
687
688 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
689 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
690
691 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
692 }
693
694 /**
695 * @see ILoadBalancer::openConnection()
696 *
697 * @param int $i
698 * @param bool $domain
699 * @return bool|Database
700 * @throws DBAccessError
701 */
702 public function openConnection( $i, $domain = false ) {
703 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
704 $domain = false; // local connection requested
705 }
706
707 if ( $domain !== false ) {
708 $conn = $this->openForeignConnection( $i, $domain );
709 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
710 $conn = $this->mConns['local'][$i][0];
711 } else {
712 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
713 throw new InvalidArgumentException( "No server with index '$i'." );
714 }
715 // Open a new connection
716 $server = $this->mServers[$i];
717 $server['serverIndex'] = $i;
718 $conn = $this->reallyOpenConnection( $server, false );
719 $serverName = $this->getServerName( $i );
720 if ( $conn->isOpen() ) {
721 $this->connLogger->debug( "Connected to database $i at '$serverName'." );
722 $this->mConns['local'][$i][0] = $conn;
723 } else {
724 $this->connLogger->warning( "Failed to connect to database $i at '$serverName'." );
725 $this->mErrorConnection = $conn;
726 $conn = false;
727 }
728 }
729
730 if ( $conn && !$conn->isOpen() ) {
731 // Connection was made but later unrecoverably lost for some reason.
732 // Do not return a handle that will just throw exceptions on use,
733 // but let the calling code (e.g. getReaderIndex) try another server.
734 // See DatabaseMyslBase::ping() for how this can happen.
735 $this->mErrorConnection = $conn;
736 $conn = false;
737 }
738
739 return $conn;
740 }
741
742 /**
743 * Open a connection to a foreign DB, or return one if it is already open.
744 *
745 * Increments a reference count on the returned connection which locks the
746 * connection to the requested domain. This reference count can be
747 * decremented by calling reuseConnection().
748 *
749 * If a connection is open to the appropriate server already, but with the wrong
750 * database, it will be switched to the right database and returned, as long as
751 * it has been freed first with reuseConnection().
752 *
753 * On error, returns false, and the connection which caused the
754 * error will be available via $this->mErrorConnection.
755 *
756 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
757 *
758 * @param int $i Server index
759 * @param string $domain Domain ID to open
760 * @return Database
761 */
762 private function openForeignConnection( $i, $domain ) {
763 $domainInstance = DatabaseDomain::newFromId( $domain );
764 $dbName = $domainInstance->getDatabase();
765 $prefix = $domainInstance->getTablePrefix();
766
767 if ( isset( $this->mConns['foreignUsed'][$i][$domain] ) ) {
768 // Reuse an already-used connection
769 $conn = $this->mConns['foreignUsed'][$i][$domain];
770 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
771 } elseif ( isset( $this->mConns['foreignFree'][$i][$domain] ) ) {
772 // Reuse a free connection for the same domain
773 $conn = $this->mConns['foreignFree'][$i][$domain];
774 unset( $this->mConns['foreignFree'][$i][$domain] );
775 $this->mConns['foreignUsed'][$i][$domain] = $conn;
776 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
777 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
778 // Reuse a connection from another domain
779 $conn = reset( $this->mConns['foreignFree'][$i] );
780 $oldDomain = key( $this->mConns['foreignFree'][$i] );
781 // The empty string as a DB name means "don't care".
782 // DatabaseMysqlBase::open() already handle this on connection.
783 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
784 $this->mLastError = "Error selecting database '$dbName' on server " .
785 $conn->getServer() . " from client host {$this->host}";
786 $this->mErrorConnection = $conn;
787 $conn = false;
788 } else {
789 $conn->tablePrefix( $prefix );
790 unset( $this->mConns['foreignFree'][$i][$oldDomain] );
791 $this->mConns['foreignUsed'][$i][$domain] = $conn;
792 $this->connLogger->debug( __METHOD__ .
793 ": reusing free connection from $oldDomain for $domain" );
794 }
795 } else {
796 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
797 throw new InvalidArgumentException( "No server with index '$i'." );
798 }
799 // Open a new connection
800 $server = $this->mServers[$i];
801 $server['serverIndex'] = $i;
802 $server['foreignPoolRefCount'] = 0;
803 $server['foreign'] = true;
804 $conn = $this->reallyOpenConnection( $server, $dbName );
805 if ( !$conn->isOpen() ) {
806 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
807 $this->mErrorConnection = $conn;
808 $conn = false;
809 } else {
810 $conn->tablePrefix( $prefix );
811 $this->mConns['foreignUsed'][$i][$domain] = $conn;
812 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
813 }
814 }
815
816 // Increment reference count
817 if ( $conn ) {
818 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
819 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
820 }
821
822 return $conn;
823 }
824
825 /**
826 * Test if the specified index represents an open connection
827 *
828 * @param int $index Server index
829 * @access private
830 * @return bool
831 */
832 private function isOpen( $index ) {
833 if ( !is_integer( $index ) ) {
834 return false;
835 }
836
837 return (bool)$this->getAnyOpenConnection( $index );
838 }
839
840 /**
841 * Really opens a connection. Uncached.
842 * Returns a Database object whether or not the connection was successful.
843 * @access private
844 *
845 * @param array $server
846 * @param string|bool $dbNameOverride Use "" to not select any database
847 * @return Database
848 * @throws DBAccessError
849 * @throws InvalidArgumentException
850 */
851 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
852 if ( $this->disabled ) {
853 throw new DBAccessError();
854 }
855
856 if ( $dbNameOverride !== false ) {
857 $server['dbname'] = $dbNameOverride;
858 }
859
860 // Let the handle know what the cluster master is (e.g. "db1052")
861 $masterName = $this->getServerName( $this->getWriterIndex() );
862 $server['clusterMasterHost'] = $masterName;
863
864 // Log when many connection are made on requests
865 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
866 $this->perfLogger->warning( __METHOD__ . ": " .
867 "{$this->connsOpened}+ connections made (master=$masterName)" );
868 }
869
870 $server['srvCache'] = $this->srvCache;
871 // Set loggers and profilers
872 $server['connLogger'] = $this->connLogger;
873 $server['queryLogger'] = $this->queryLogger;
874 $server['errorLogger'] = $this->errorLogger;
875 $server['profiler'] = $this->profiler;
876 $server['trxProfiler'] = $this->trxProfiler;
877 // Use the same agent and PHP mode for all DB handles
878 $server['cliMode'] = $this->cliMode;
879 $server['agent'] = $this->agent;
880 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
881 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
882 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
883
884 // Create a live connection object
885 try {
886 $db = Database::factory( $server['type'], $server );
887 } catch ( DBConnectionError $e ) {
888 // FIXME: This is probably the ugliest thing I have ever done to
889 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
890 $db = $e->db;
891 }
892
893 $db->setLBInfo( $server );
894 $db->setLazyMasterHandle(
895 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
896 );
897 $db->setTableAliases( $this->tableAliases );
898
899 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
900 if ( $this->trxRoundId !== false ) {
901 $this->applyTransactionRoundFlags( $db );
902 }
903 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
904 $db->setTransactionListener( $name, $callback );
905 }
906 }
907
908 return $db;
909 }
910
911 /**
912 * @throws DBConnectionError
913 */
914 private function reportConnectionError() {
915 $conn = $this->mErrorConnection; // the connection which caused the error
916 $context = [
917 'method' => __METHOD__,
918 'last_error' => $this->mLastError,
919 ];
920
921 if ( !is_object( $conn ) ) {
922 // No last connection, probably due to all servers being too busy
923 $this->connLogger->error(
924 "LB failure with no last connection. Connection error: {last_error}",
925 $context
926 );
927
928 // If all servers were busy, mLastError will contain something sensible
929 throw new DBConnectionError( null, $this->mLastError );
930 } else {
931 $context['db_server'] = $conn->getServer();
932 $this->connLogger->warning(
933 "Connection error: {last_error} ({db_server})",
934 $context
935 );
936
937 // throws DBConnectionError
938 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
939 }
940 }
941
942 public function getWriterIndex() {
943 return 0;
944 }
945
946 public function haveIndex( $i ) {
947 return array_key_exists( $i, $this->mServers );
948 }
949
950 public function isNonZeroLoad( $i ) {
951 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
952 }
953
954 public function getServerCount() {
955 return count( $this->mServers );
956 }
957
958 public function getServerName( $i ) {
959 if ( isset( $this->mServers[$i]['hostName'] ) ) {
960 $name = $this->mServers[$i]['hostName'];
961 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
962 $name = $this->mServers[$i]['host'];
963 } else {
964 $name = '';
965 }
966
967 return ( $name != '' ) ? $name : 'localhost';
968 }
969
970 public function getServerInfo( $i ) {
971 if ( isset( $this->mServers[$i] ) ) {
972 return $this->mServers[$i];
973 } else {
974 return false;
975 }
976 }
977
978 public function setServerInfo( $i, array $serverInfo ) {
979 $this->mServers[$i] = $serverInfo;
980 }
981
982 public function getMasterPos() {
983 # If this entire request was served from a replica DB without opening a connection to the
984 # master (however unlikely that may be), then we can fetch the position from the replica DB.
985 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
986 if ( !$masterConn ) {
987 $serverCount = count( $this->mServers );
988 for ( $i = 1; $i < $serverCount; $i++ ) {
989 $conn = $this->getAnyOpenConnection( $i );
990 if ( $conn ) {
991 return $conn->getReplicaPos();
992 }
993 }
994 } else {
995 return $masterConn->getMasterPos();
996 }
997
998 return false;
999 }
1000
1001 public function disable() {
1002 $this->closeAll();
1003 $this->disabled = true;
1004 }
1005
1006 public function closeAll() {
1007 $this->forEachOpenConnection( function ( IDatabase $conn ) {
1008 $host = $conn->getServer();
1009 $this->connLogger->debug( "Closing connection to database '$host'." );
1010 $conn->close();
1011 } );
1012
1013 $this->mConns = [
1014 'local' => [],
1015 'foreignFree' => [],
1016 'foreignUsed' => [],
1017 ];
1018 $this->connsOpened = 0;
1019 }
1020
1021 public function closeConnection( IDatabase $conn ) {
1022 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1023 foreach ( $this->mConns as $type => $connsByServer ) {
1024 if ( !isset( $connsByServer[$serverIndex] ) ) {
1025 continue;
1026 }
1027
1028 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1029 if ( $conn === $trackedConn ) {
1030 $host = $this->getServerName( $i );
1031 $this->connLogger->debug( "Closing connection to database $i at '$host'." );
1032 unset( $this->mConns[$type][$serverIndex][$i] );
1033 --$this->connsOpened;
1034 break 2;
1035 }
1036 }
1037 }
1038
1039 $conn->close();
1040 }
1041
1042 public function commitAll( $fname = __METHOD__ ) {
1043 $failures = [];
1044
1045 $restore = ( $this->trxRoundId !== false );
1046 $this->trxRoundId = false;
1047 $this->forEachOpenConnection(
1048 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1049 try {
1050 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1051 } catch ( DBError $e ) {
1052 call_user_func( $this->errorLogger, $e );
1053 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1054 }
1055 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1056 $this->undoTransactionRoundFlags( $conn );
1057 }
1058 }
1059 );
1060
1061 if ( $failures ) {
1062 throw new DBExpectedError(
1063 null,
1064 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1065 );
1066 }
1067 }
1068
1069 public function finalizeMasterChanges() {
1070 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1071 // Any error should cause all DB transactions to be rolled back together
1072 $conn->setTrxEndCallbackSuppression( false );
1073 $conn->runOnTransactionPreCommitCallbacks();
1074 // Defer post-commit callbacks until COMMIT finishes for all DBs
1075 $conn->setTrxEndCallbackSuppression( true );
1076 } );
1077 }
1078
1079 public function approveMasterChanges( array $options ) {
1080 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1081 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1082 // If atomic sections or explicit transactions are still open, some caller must have
1083 // caught an exception but failed to properly rollback any changes. Detect that and
1084 // throw and error (causing rollback).
1085 if ( $conn->explicitTrxActive() ) {
1086 throw new DBTransactionError(
1087 $conn,
1088 "Explicit transaction still active. A caller may have caught an error."
1089 );
1090 }
1091 // Assert that the time to replicate the transaction will be sane.
1092 // If this fails, then all DB transactions will be rollback back together.
1093 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1094 if ( $limit > 0 && $time > $limit ) {
1095 throw new DBTransactionSizeError(
1096 $conn,
1097 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1098 [ $time, $limit ]
1099 );
1100 }
1101 // If a connection sits idle while slow queries execute on another, that connection
1102 // may end up dropped before the commit round is reached. Ping servers to detect this.
1103 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1104 throw new DBTransactionError(
1105 $conn,
1106 "A connection to the {$conn->getDBname()} database was lost before commit."
1107 );
1108 }
1109 } );
1110 }
1111
1112 public function beginMasterChanges( $fname = __METHOD__ ) {
1113 if ( $this->trxRoundId !== false ) {
1114 throw new DBTransactionError(
1115 null,
1116 "$fname: Transaction round '{$this->trxRoundId}' already started."
1117 );
1118 }
1119 $this->trxRoundId = $fname;
1120
1121 $failures = [];
1122 $this->forEachOpenMasterConnection(
1123 function ( Database $conn ) use ( $fname, &$failures ) {
1124 $conn->setTrxEndCallbackSuppression( true );
1125 try {
1126 $conn->flushSnapshot( $fname );
1127 } catch ( DBError $e ) {
1128 call_user_func( $this->errorLogger, $e );
1129 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1130 }
1131 $conn->setTrxEndCallbackSuppression( false );
1132 $this->applyTransactionRoundFlags( $conn );
1133 }
1134 );
1135
1136 if ( $failures ) {
1137 throw new DBExpectedError(
1138 null,
1139 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1140 );
1141 }
1142 }
1143
1144 public function commitMasterChanges( $fname = __METHOD__ ) {
1145 $failures = [];
1146
1147 /** @noinspection PhpUnusedLocalVariableInspection */
1148 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1149
1150 $restore = ( $this->trxRoundId !== false );
1151 $this->trxRoundId = false;
1152 $this->forEachOpenMasterConnection(
1153 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1154 try {
1155 if ( $conn->writesOrCallbacksPending() ) {
1156 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1157 } elseif ( $restore ) {
1158 $conn->flushSnapshot( $fname );
1159 }
1160 } catch ( DBError $e ) {
1161 call_user_func( $this->errorLogger, $e );
1162 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1163 }
1164 if ( $restore ) {
1165 $this->undoTransactionRoundFlags( $conn );
1166 }
1167 }
1168 );
1169
1170 if ( $failures ) {
1171 throw new DBExpectedError(
1172 null,
1173 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1174 );
1175 }
1176 }
1177
1178 public function runMasterPostTrxCallbacks( $type ) {
1179 $e = null; // first exception
1180 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1181 $conn->setTrxEndCallbackSuppression( false );
1182 if ( $conn->writesOrCallbacksPending() ) {
1183 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1184 // (which finished its callbacks already). Warn and recover in this case. Let the
1185 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1186 $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
1187 return;
1188 } elseif ( $conn->trxLevel() ) {
1189 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1190 // thus leaving an implicit read-only transaction open at this point. It
1191 // also happens if onTransactionIdle() callbacks leave implicit transactions
1192 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1193 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1194 return;
1195 }
1196 try {
1197 $conn->runOnTransactionIdleCallbacks( $type );
1198 } catch ( Exception $ex ) {
1199 $e = $e ?: $ex;
1200 }
1201 try {
1202 $conn->runTransactionListenerCallbacks( $type );
1203 } catch ( Exception $ex ) {
1204 $e = $e ?: $ex;
1205 }
1206 } );
1207
1208 return $e;
1209 }
1210
1211 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1212 $restore = ( $this->trxRoundId !== false );
1213 $this->trxRoundId = false;
1214 $this->forEachOpenMasterConnection(
1215 function ( IDatabase $conn ) use ( $fname, $restore ) {
1216 if ( $conn->writesOrCallbacksPending() ) {
1217 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1218 }
1219 if ( $restore ) {
1220 $this->undoTransactionRoundFlags( $conn );
1221 }
1222 }
1223 );
1224 }
1225
1226 public function suppressTransactionEndCallbacks() {
1227 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1228 $conn->setTrxEndCallbackSuppression( true );
1229 } );
1230 }
1231
1232 /**
1233 * @param IDatabase $conn
1234 */
1235 private function applyTransactionRoundFlags( IDatabase $conn ) {
1236 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1237 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1238 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1239 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1240 // If config has explicitly requested DBO_TRX be either on or off by not
1241 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1242 // for things like blob stores (ExternalStore) which want auto-commit mode.
1243 }
1244 }
1245
1246 /**
1247 * @param IDatabase $conn
1248 */
1249 private function undoTransactionRoundFlags( IDatabase $conn ) {
1250 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1251 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1252 }
1253 }
1254
1255 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1256 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1257 $conn->flushSnapshot( __METHOD__ );
1258 } );
1259 }
1260
1261 public function hasMasterConnection() {
1262 return $this->isOpen( $this->getWriterIndex() );
1263 }
1264
1265 public function hasMasterChanges() {
1266 $pending = 0;
1267 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1268 $pending |= $conn->writesOrCallbacksPending();
1269 } );
1270
1271 return (bool)$pending;
1272 }
1273
1274 public function lastMasterChangeTimestamp() {
1275 $lastTime = false;
1276 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1277 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1278 } );
1279
1280 return $lastTime;
1281 }
1282
1283 public function hasOrMadeRecentMasterChanges( $age = null ) {
1284 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1285
1286 return ( $this->hasMasterChanges()
1287 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1288 }
1289
1290 public function pendingMasterChangeCallers() {
1291 $fnames = [];
1292 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1293 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1294 } );
1295
1296 return $fnames;
1297 }
1298
1299 public function getLaggedReplicaMode( $domain = false ) {
1300 // No-op if there is only one DB (also avoids recursion)
1301 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1302 try {
1303 // See if laggedReplicaMode gets set
1304 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1305 $this->reuseConnection( $conn );
1306 } catch ( DBConnectionError $e ) {
1307 // Avoid expensive re-connect attempts and failures
1308 $this->allReplicasDownMode = true;
1309 $this->laggedReplicaMode = true;
1310 }
1311 }
1312
1313 return $this->laggedReplicaMode;
1314 }
1315
1316 /**
1317 * @param bool $domain
1318 * @return bool
1319 * @deprecated 1.28; use getLaggedReplicaMode()
1320 */
1321 public function getLaggedSlaveMode( $domain = false ) {
1322 return $this->getLaggedReplicaMode( $domain );
1323 }
1324
1325 public function laggedReplicaUsed() {
1326 return $this->laggedReplicaMode;
1327 }
1328
1329 /**
1330 * @return bool
1331 * @since 1.27
1332 * @deprecated Since 1.28; use laggedReplicaUsed()
1333 */
1334 public function laggedSlaveUsed() {
1335 return $this->laggedReplicaUsed();
1336 }
1337
1338 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1339 if ( $this->readOnlyReason !== false ) {
1340 return $this->readOnlyReason;
1341 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1342 if ( $this->allReplicasDownMode ) {
1343 return 'The database has been automatically locked ' .
1344 'until the replica database servers become available';
1345 } else {
1346 return 'The database has been automatically locked ' .
1347 'while the replica database servers catch up to the master.';
1348 }
1349 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1350 return 'The database master is running in read-only mode.';
1351 }
1352
1353 return false;
1354 }
1355
1356 /**
1357 * @param string $domain Domain ID, or false for the current domain
1358 * @param IDatabase|null DB master connectionl used to avoid loops [optional]
1359 * @return bool
1360 */
1361 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1362 $cache = $this->wanCache;
1363 $masterServer = $this->getServerName( $this->getWriterIndex() );
1364
1365 return (bool)$cache->getWithSetCallback(
1366 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1367 self::TTL_CACHE_READONLY,
1368 function () use ( $domain, $conn ) {
1369 $old = $this->trxProfiler->setSilenced( true );
1370 try {
1371 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1372 $readOnly = (int)$dbw->serverIsReadOnly();
1373 if ( !$conn ) {
1374 $this->reuseConnection( $dbw );
1375 }
1376 } catch ( DBError $e ) {
1377 $readOnly = 0;
1378 }
1379 $this->trxProfiler->setSilenced( $old );
1380 return $readOnly;
1381 },
1382 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1383 );
1384 }
1385
1386 public function allowLagged( $mode = null ) {
1387 if ( $mode === null ) {
1388 return $this->mAllowLagged;
1389 }
1390 $this->mAllowLagged = $mode;
1391
1392 return $this->mAllowLagged;
1393 }
1394
1395 public function pingAll() {
1396 $success = true;
1397 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1398 if ( !$conn->ping() ) {
1399 $success = false;
1400 }
1401 } );
1402
1403 return $success;
1404 }
1405
1406 public function forEachOpenConnection( $callback, array $params = [] ) {
1407 foreach ( $this->mConns as $connsByServer ) {
1408 foreach ( $connsByServer as $serverConns ) {
1409 foreach ( $serverConns as $conn ) {
1410 $mergedParams = array_merge( [ $conn ], $params );
1411 call_user_func_array( $callback, $mergedParams );
1412 }
1413 }
1414 }
1415 }
1416
1417 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1418 $masterIndex = $this->getWriterIndex();
1419 foreach ( $this->mConns as $connsByServer ) {
1420 if ( isset( $connsByServer[$masterIndex] ) ) {
1421 /** @var IDatabase $conn */
1422 foreach ( $connsByServer[$masterIndex] as $conn ) {
1423 $mergedParams = array_merge( [ $conn ], $params );
1424 call_user_func_array( $callback, $mergedParams );
1425 }
1426 }
1427 }
1428 }
1429
1430 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1431 foreach ( $this->mConns as $connsByServer ) {
1432 foreach ( $connsByServer as $i => $serverConns ) {
1433 if ( $i === $this->getWriterIndex() ) {
1434 continue; // skip master
1435 }
1436 foreach ( $serverConns as $conn ) {
1437 $mergedParams = array_merge( [ $conn ], $params );
1438 call_user_func_array( $callback, $mergedParams );
1439 }
1440 }
1441 }
1442 }
1443
1444 public function getMaxLag( $domain = false ) {
1445 $maxLag = -1;
1446 $host = '';
1447 $maxIndex = 0;
1448
1449 if ( $this->getServerCount() <= 1 ) {
1450 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1451 }
1452
1453 $lagTimes = $this->getLagTimes( $domain );
1454 foreach ( $lagTimes as $i => $lag ) {
1455 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1456 $maxLag = $lag;
1457 $host = $this->mServers[$i]['host'];
1458 $maxIndex = $i;
1459 }
1460 }
1461
1462 return [ $host, $maxLag, $maxIndex ];
1463 }
1464
1465 public function getLagTimes( $domain = false ) {
1466 if ( $this->getServerCount() <= 1 ) {
1467 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1468 }
1469
1470 $knownLagTimes = []; // map of (server index => 0 seconds)
1471 $indexesWithLag = [];
1472 foreach ( $this->mServers as $i => $server ) {
1473 if ( empty( $server['is static'] ) ) {
1474 $indexesWithLag[] = $i; // DB server might have replication lag
1475 } else {
1476 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1477 }
1478 }
1479
1480 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1481 }
1482
1483 public function safeGetLag( IDatabase $conn ) {
1484 if ( $this->getServerCount() <= 1 ) {
1485 return 0;
1486 } else {
1487 return $conn->getLag();
1488 }
1489 }
1490
1491 /**
1492 * @param IDatabase $conn
1493 * @param DBMasterPos|bool $pos
1494 * @param int $timeout
1495 * @return bool
1496 */
1497 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1498 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1499 return true; // server is not a replica DB
1500 }
1501
1502 if ( !$pos ) {
1503 // Get the current master position, opening a connection if needed
1504 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1505 if ( $masterConn ) {
1506 $pos = $masterConn->getMasterPos();
1507 } else {
1508 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1509 $pos = $masterConn->getMasterPos();
1510 $this->closeConnection( $masterConn );
1511 }
1512 }
1513
1514 if ( $pos instanceof DBMasterPos ) {
1515 $result = $conn->masterPosWait( $pos, $timeout );
1516 if ( $result == -1 || is_null( $result ) ) {
1517 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1518 $this->replLogger->warning( "$msg" );
1519 $ok = false;
1520 } else {
1521 $this->replLogger->info( __METHOD__ . ": Done" );
1522 $ok = true;
1523 }
1524 } else {
1525 $ok = false; // something is misconfigured
1526 $this->replLogger->error( "Could not get master pos for {$conn->getServer()}." );
1527 }
1528
1529 return $ok;
1530 }
1531
1532 public function setTransactionListener( $name, callable $callback = null ) {
1533 if ( $callback ) {
1534 $this->trxRecurringCallbacks[$name] = $callback;
1535 } else {
1536 unset( $this->trxRecurringCallbacks[$name] );
1537 }
1538 $this->forEachOpenMasterConnection(
1539 function ( IDatabase $conn ) use ( $name, $callback ) {
1540 $conn->setTransactionListener( $name, $callback );
1541 }
1542 );
1543 }
1544
1545 public function setTableAliases( array $aliases ) {
1546 $this->tableAliases = $aliases;
1547 }
1548
1549 public function setDomainPrefix( $prefix ) {
1550 if ( $this->mConns['foreignUsed'] ) {
1551 // Do not switch connections to explicit foreign domains unless marked as free
1552 $domains = [];
1553 foreach ( $this->mConns['foreignUsed'] as $i => $connsByDomain ) {
1554 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1555 }
1556 $domains = implode( ', ', $domains );
1557 throw new DBUnexpectedError( null,
1558 "Foreign domain connections are still in use ($domains)." );
1559 }
1560
1561 $this->localDomain = new DatabaseDomain(
1562 $this->localDomain->getDatabase(),
1563 null,
1564 $prefix
1565 );
1566
1567 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1568 $db->tablePrefix( $prefix );
1569 } );
1570 }
1571
1572 /**
1573 * Make PHP ignore user aborts/disconnects until the returned
1574 * value leaves scope. This returns null and does nothing in CLI mode.
1575 *
1576 * @return ScopedCallback|null
1577 */
1578 final protected function getScopedPHPBehaviorForCommit() {
1579 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1580 $old = ignore_user_abort( true ); // avoid half-finished operations
1581 return new ScopedCallback( function () use ( $old ) {
1582 ignore_user_abort( $old );
1583 } );
1584 }
1585
1586 return null;
1587 }
1588
1589 function __destruct() {
1590 // Avoid connection leaks for sanity
1591 $this->disable();
1592 }
1593 }