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