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