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