ffa4f78a7695fbd7533a54a523e5c02d9acea1c8
[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 try {
434 $this->mWaitForPos = $pos;
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 } finally {
443 // Restore the older position if it was higher
444 $this->setWaitForPositionIfHigher( $oldPos );
445 }
446 }
447
448 public function waitForOne( $pos, $timeout = null ) {
449 $oldPos = $this->mWaitForPos;
450 try {
451 $this->mWaitForPos = $pos;
452
453 $i = $this->mReadIndex;
454 if ( $i <= 0 ) {
455 // Pick a generic replica DB if there isn't one yet
456 $readLoads = $this->mLoads;
457 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
458 $readLoads = array_filter( $readLoads ); // with non-zero load
459 $i = ArrayUtils::pickRandom( $readLoads );
460 }
461
462 if ( $i > 0 ) {
463 $ok = $this->doWait( $i, true, $timeout );
464 } else {
465 $ok = true; // no applicable loads
466 }
467 } finally {
468 // Restore the older position if it was higher
469 $this->setWaitForPositionIfHigher( $oldPos );
470 }
471
472 return $ok;
473 }
474
475 public function waitForAll( $pos, $timeout = null ) {
476 $oldPos = $this->mWaitForPos;
477 try {
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 } finally {
488 // Restore the older position if it was higher
489 $this->setWaitForPositionIfHigher( $oldPos );
490 }
491
492 return $ok;
493 }
494
495 /**
496 * @param DBMasterPos|bool $pos
497 */
498 private function setWaitForPositionIfHigher( $pos ) {
499 if ( !$pos ) {
500 return;
501 }
502
503 if ( !$this->mWaitForPos || $pos->hasReached( $this->mWaitForPos ) ) {
504 $this->mWaitForPos = $pos;
505 }
506 }
507
508 /**
509 * @param int $i
510 * @return IDatabase|bool
511 */
512 public function getAnyOpenConnection( $i ) {
513 foreach ( $this->mConns as $connsByServer ) {
514 if ( !empty( $connsByServer[$i] ) ) {
515 /** @var $serverConns IDatabase[] */
516 $serverConns = $connsByServer[$i];
517
518 return reset( $serverConns );
519 }
520 }
521
522 return false;
523 }
524
525 /**
526 * Wait for a given replica DB to catch up to the master pos stored in $this
527 * @param int $index Server index
528 * @param bool $open Check the server even if a new connection has to be made
529 * @param int $timeout Max seconds to wait; default is mWaitTimeout
530 * @return bool
531 */
532 protected function doWait( $index, $open = false, $timeout = null ) {
533 $close = false; // close the connection afterwards
534
535 // Check if we already know that the DB has reached this point
536 $server = $this->getServerName( $index );
537 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server, 'v1' );
538 /** @var DBMasterPos $knownReachedPos */
539 $knownReachedPos = $this->srvCache->get( $key );
540 if (
541 $knownReachedPos instanceof DBMasterPos &&
542 $knownReachedPos->hasReached( $this->mWaitForPos )
543 ) {
544 $this->replLogger->debug( __METHOD__ .
545 ": replica DB $server known to be caught up (pos >= $knownReachedPos)." );
546 return true;
547 }
548
549 // Find a connection to wait on, creating one if needed and allowed
550 $conn = $this->getAnyOpenConnection( $index );
551 if ( !$conn ) {
552 if ( !$open ) {
553 $this->replLogger->debug( __METHOD__ . ": no connection open for $server" );
554
555 return false;
556 } else {
557 $conn = $this->openConnection( $index, self::DOMAIN_ANY );
558 if ( !$conn ) {
559 $this->replLogger->warning( __METHOD__ . ": failed to connect to $server" );
560
561 return false;
562 }
563 // Avoid connection spam in waitForAll() when connections
564 // are made just for the sake of doing this lag check.
565 $close = true;
566 }
567 }
568
569 $this->replLogger->info( __METHOD__ . ": Waiting for replica DB $server to catch up..." );
570 $timeout = $timeout ?: $this->mWaitTimeout;
571 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
572
573 if ( $result == -1 || is_null( $result ) ) {
574 // Timed out waiting for replica DB, use master instead
575 $this->replLogger->warning(
576 __METHOD__ . ": Timed out waiting on {host} pos {$this->mWaitForPos}",
577 [ 'host' => $server ]
578 );
579 $ok = false;
580 } else {
581 $this->replLogger->info( __METHOD__ . ": Done" );
582 $ok = true;
583 // Remember that the DB reached this point
584 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
585 }
586
587 if ( $close ) {
588 $this->closeConnection( $conn );
589 }
590
591 return $ok;
592 }
593
594 /**
595 * @see ILoadBalancer::getConnection()
596 *
597 * @param int $i
598 * @param array $groups
599 * @param bool $domain
600 * @return Database
601 * @throws DBConnectionError
602 */
603 public function getConnection( $i, $groups = [], $domain = false ) {
604 if ( $i === null || $i === false ) {
605 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
606 ' with invalid server index' );
607 }
608
609 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
610 $domain = false; // local connection requested
611 }
612
613 $groups = ( $groups === false || $groups === [] )
614 ? [ false ] // check one "group": the generic pool
615 : (array)$groups;
616
617 $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
618 $oldConnsOpened = $this->connsOpened; // connections open now
619
620 if ( $i == self::DB_MASTER ) {
621 $i = $this->getWriterIndex();
622 } else {
623 # Try to find an available server in any the query groups (in order)
624 foreach ( $groups as $group ) {
625 $groupIndex = $this->getReaderIndex( $group, $domain );
626 if ( $groupIndex !== false ) {
627 $i = $groupIndex;
628 break;
629 }
630 }
631 }
632
633 # Operation-based index
634 if ( $i == self::DB_REPLICA ) {
635 $this->mLastError = 'Unknown error'; // reset error string
636 # Try the general server pool if $groups are unavailable.
637 $i = ( $groups === [ false ] )
638 ? false // don't bother with this if that is what was tried above
639 : $this->getReaderIndex( false, $domain );
640 # Couldn't find a working server in getReaderIndex()?
641 if ( $i === false ) {
642 $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
643 // Throw an exception
644 $this->reportConnectionError();
645 return null; // not reached
646 }
647 }
648
649 # Now we have an explicit index into the servers array
650 $conn = $this->openConnection( $i, $domain );
651 if ( !$conn ) {
652 // Throw an exception
653 $this->reportConnectionError();
654 return null; // not reached
655 }
656
657 # Profile any new connections that happen
658 if ( $this->connsOpened > $oldConnsOpened ) {
659 $host = $conn->getServer();
660 $dbname = $conn->getDBname();
661 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
662 }
663
664 if ( $masterOnly ) {
665 # Make master-requested DB handles inherit any read-only mode setting
666 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
667 }
668
669 return $conn;
670 }
671
672 public function reuseConnection( $conn ) {
673 $serverIndex = $conn->getLBInfo( 'serverIndex' );
674 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
675 if ( $serverIndex === null || $refCount === null ) {
676 /**
677 * This can happen in code like:
678 * foreach ( $dbs as $db ) {
679 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
680 * ...
681 * $lb->reuseConnection( $conn );
682 * }
683 * When a connection to the local DB is opened in this way, reuseConnection()
684 * should be ignored
685 */
686 return;
687 } elseif ( $conn instanceof DBConnRef ) {
688 // DBConnRef already handles calling reuseConnection() and only passes the live
689 // Database instance to this method. Any caller passing in a DBConnRef is broken.
690 $this->connLogger->error( __METHOD__ . ": got DBConnRef instance.\n" .
691 ( new RuntimeException() )->getTraceAsString() );
692
693 return;
694 }
695
696 if ( $this->disabled ) {
697 return; // DBConnRef handle probably survived longer than the LoadBalancer
698 }
699
700 $domain = $conn->getDomainID();
701 if ( !isset( $this->mConns['foreignUsed'][$serverIndex][$domain] ) ) {
702 throw new InvalidArgumentException( __METHOD__ .
703 ": connection $serverIndex/$domain not found; it may have already been freed." );
704 } elseif ( $this->mConns['foreignUsed'][$serverIndex][$domain] !== $conn ) {
705 throw new InvalidArgumentException( __METHOD__ .
706 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
707 }
708 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
709 if ( $refCount <= 0 ) {
710 $this->mConns['foreignFree'][$serverIndex][$domain] = $conn;
711 unset( $this->mConns['foreignUsed'][$serverIndex][$domain] );
712 if ( !$this->mConns['foreignUsed'][$serverIndex] ) {
713 unset( $this->mConns[ 'foreignUsed' ][$serverIndex] ); // clean up
714 }
715 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
716 } else {
717 $this->connLogger->debug( __METHOD__ .
718 ": reference count for $serverIndex/$domain reduced to $refCount" );
719 }
720 }
721
722 public function getConnectionRef( $db, $groups = [], $domain = false ) {
723 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
724
725 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
726 }
727
728 public function getLazyConnectionRef( $db, $groups = [], $domain = false ) {
729 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
730
731 return new DBConnRef( $this, [ $db, $groups, $domain ] );
732 }
733
734 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false ) {
735 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
736
737 return new MaintainableDBConnRef( $this, $this->getConnection( $db, $groups, $domain ) );
738 }
739
740 /**
741 * @see ILoadBalancer::openConnection()
742 *
743 * @param int $i
744 * @param bool $domain
745 * @return bool|Database
746 * @throws DBAccessError
747 */
748 public function openConnection( $i, $domain = false ) {
749 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
750 $domain = false; // local connection requested
751 }
752
753 if ( !$this->chronProtInitialized && $this->chronProt ) {
754 $this->connLogger->debug( __METHOD__ . ': calling initLB() before first connection.' );
755 // Load CP positions before connecting so that doWait() triggers later if needed
756 $this->chronProtInitialized = true;
757 $this->chronProt->initLB( $this );
758 }
759
760 if ( $domain !== false ) {
761 $conn = $this->openForeignConnection( $i, $domain );
762 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
763 $conn = $this->mConns['local'][$i][0];
764 } else {
765 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
766 throw new InvalidArgumentException( "No server with index '$i'." );
767 }
768 // Open a new connection
769 $server = $this->mServers[$i];
770 $server['serverIndex'] = $i;
771 $conn = $this->reallyOpenConnection( $server, false );
772 $serverName = $this->getServerName( $i );
773 if ( $conn->isOpen() ) {
774 $this->connLogger->debug( "Connected to database $i at '$serverName'." );
775 $this->mConns['local'][$i][0] = $conn;
776 } else {
777 $this->connLogger->warning( "Failed to connect to database $i at '$serverName'." );
778 $this->errorConnection = $conn;
779 $conn = false;
780 }
781 }
782
783 if ( $conn instanceof IDatabase && !$conn->isOpen() ) {
784 // Connection was made but later unrecoverably lost for some reason.
785 // Do not return a handle that will just throw exceptions on use,
786 // but let the calling code (e.g. getReaderIndex) try another server.
787 // See DatabaseMyslBase::ping() for how this can happen.
788 $this->errorConnection = $conn;
789 $conn = false;
790 }
791
792 return $conn;
793 }
794
795 /**
796 * Open a connection to a foreign DB, or return one if it is already open.
797 *
798 * Increments a reference count on the returned connection which locks the
799 * connection to the requested domain. This reference count can be
800 * decremented by calling reuseConnection().
801 *
802 * If a connection is open to the appropriate server already, but with the wrong
803 * database, it will be switched to the right database and returned, as long as
804 * it has been freed first with reuseConnection().
805 *
806 * On error, returns false, and the connection which caused the
807 * error will be available via $this->errorConnection.
808 *
809 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
810 *
811 * @param int $i Server index
812 * @param string $domain Domain ID to open
813 * @return Database
814 */
815 private function openForeignConnection( $i, $domain ) {
816 $domainInstance = DatabaseDomain::newFromId( $domain );
817 $dbName = $domainInstance->getDatabase();
818 $prefix = $domainInstance->getTablePrefix();
819
820 if ( isset( $this->mConns['foreignUsed'][$i][$domain] ) ) {
821 // Reuse an already-used connection
822 $conn = $this->mConns['foreignUsed'][$i][$domain];
823 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
824 } elseif ( isset( $this->mConns['foreignFree'][$i][$domain] ) ) {
825 // Reuse a free connection for the same domain
826 $conn = $this->mConns['foreignFree'][$i][$domain];
827 unset( $this->mConns['foreignFree'][$i][$domain] );
828 $this->mConns['foreignUsed'][$i][$domain] = $conn;
829 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
830 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
831 // Reuse a connection from another domain
832 $conn = reset( $this->mConns['foreignFree'][$i] );
833 $oldDomain = key( $this->mConns['foreignFree'][$i] );
834 // The empty string as a DB name means "don't care".
835 // DatabaseMysqlBase::open() already handle this on connection.
836 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
837 $this->mLastError = "Error selecting database '$dbName' on server " .
838 $conn->getServer() . " from client host {$this->host}";
839 $this->errorConnection = $conn;
840 $conn = false;
841 } else {
842 $conn->tablePrefix( $prefix );
843 unset( $this->mConns['foreignFree'][$i][$oldDomain] );
844 $this->mConns['foreignUsed'][$i][$domain] = $conn;
845 $this->connLogger->debug( __METHOD__ .
846 ": reusing free connection from $oldDomain for $domain" );
847 }
848 } else {
849 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
850 throw new InvalidArgumentException( "No server with index '$i'." );
851 }
852 // Open a new connection
853 $server = $this->mServers[$i];
854 $server['serverIndex'] = $i;
855 $server['foreignPoolRefCount'] = 0;
856 $server['foreign'] = true;
857 $conn = $this->reallyOpenConnection( $server, $dbName );
858 if ( !$conn->isOpen() ) {
859 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
860 $this->errorConnection = $conn;
861 $conn = false;
862 } else {
863 $conn->tablePrefix( $prefix );
864 $this->mConns['foreignUsed'][$i][$domain] = $conn;
865 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
866 }
867 }
868
869 // Increment reference count
870 if ( $conn instanceof IDatabase ) {
871 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
872 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
873 }
874
875 return $conn;
876 }
877
878 /**
879 * Test if the specified index represents an open connection
880 *
881 * @param int $index Server index
882 * @access private
883 * @return bool
884 */
885 private function isOpen( $index ) {
886 if ( !is_integer( $index ) ) {
887 return false;
888 }
889
890 return (bool)$this->getAnyOpenConnection( $index );
891 }
892
893 /**
894 * Really opens a connection. Uncached.
895 * Returns a Database object whether or not the connection was successful.
896 * @access private
897 *
898 * @param array $server
899 * @param string|bool $dbNameOverride Use "" to not select any database
900 * @return Database
901 * @throws DBAccessError
902 * @throws InvalidArgumentException
903 */
904 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
905 if ( $this->disabled ) {
906 throw new DBAccessError();
907 }
908
909 if ( $dbNameOverride !== false ) {
910 $server['dbname'] = $dbNameOverride;
911 }
912
913 // Let the handle know what the cluster master is (e.g. "db1052")
914 $masterName = $this->getServerName( $this->getWriterIndex() );
915 $server['clusterMasterHost'] = $masterName;
916
917 // Log when many connection are made on requests
918 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
919 $this->perfLogger->warning( __METHOD__ . ": " .
920 "{$this->connsOpened}+ connections made (master=$masterName)" );
921 }
922
923 $server['srvCache'] = $this->srvCache;
924 // Set loggers and profilers
925 $server['connLogger'] = $this->connLogger;
926 $server['queryLogger'] = $this->queryLogger;
927 $server['errorLogger'] = $this->errorLogger;
928 $server['profiler'] = $this->profiler;
929 $server['trxProfiler'] = $this->trxProfiler;
930 // Use the same agent and PHP mode for all DB handles
931 $server['cliMode'] = $this->cliMode;
932 $server['agent'] = $this->agent;
933 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
934 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
935 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
936
937 // Create a live connection object
938 try {
939 $db = Database::factory( $server['type'], $server );
940 } catch ( DBConnectionError $e ) {
941 // FIXME: This is probably the ugliest thing I have ever done to
942 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
943 $db = $e->db;
944 }
945
946 $db->setLBInfo( $server );
947 $db->setLazyMasterHandle(
948 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
949 );
950 $db->setTableAliases( $this->tableAliases );
951
952 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
953 if ( $this->trxRoundId !== false ) {
954 $this->applyTransactionRoundFlags( $db );
955 }
956 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
957 $db->setTransactionListener( $name, $callback );
958 }
959 }
960
961 return $db;
962 }
963
964 /**
965 * @throws DBConnectionError
966 */
967 private function reportConnectionError() {
968 $conn = $this->errorConnection; // the connection which caused the error
969 $context = [
970 'method' => __METHOD__,
971 'last_error' => $this->mLastError,
972 ];
973
974 if ( $conn instanceof IDatabase ) {
975 $context['db_server'] = $conn->getServer();
976 $this->connLogger->warning(
977 "Connection error: {last_error} ({db_server})",
978 $context
979 );
980
981 // throws DBConnectionError
982 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
983 } else {
984 // No last connection, probably due to all servers being too busy
985 $this->connLogger->error(
986 "LB failure with no last connection. Connection error: {last_error}",
987 $context
988 );
989
990 // If all servers were busy, mLastError will contain something sensible
991 throw new DBConnectionError( null, $this->mLastError );
992 }
993 }
994
995 public function getWriterIndex() {
996 return 0;
997 }
998
999 public function haveIndex( $i ) {
1000 return array_key_exists( $i, $this->mServers );
1001 }
1002
1003 public function isNonZeroLoad( $i ) {
1004 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
1005 }
1006
1007 public function getServerCount() {
1008 return count( $this->mServers );
1009 }
1010
1011 public function getServerName( $i ) {
1012 if ( isset( $this->mServers[$i]['hostName'] ) ) {
1013 $name = $this->mServers[$i]['hostName'];
1014 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
1015 $name = $this->mServers[$i]['host'];
1016 } else {
1017 $name = '';
1018 }
1019
1020 return ( $name != '' ) ? $name : 'localhost';
1021 }
1022
1023 public function getServerInfo( $i ) {
1024 if ( isset( $this->mServers[$i] ) ) {
1025 return $this->mServers[$i];
1026 } else {
1027 return false;
1028 }
1029 }
1030
1031 public function setServerInfo( $i, array $serverInfo ) {
1032 $this->mServers[$i] = $serverInfo;
1033 }
1034
1035 public function getMasterPos() {
1036 # If this entire request was served from a replica DB without opening a connection to the
1037 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1038 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1039 if ( !$masterConn ) {
1040 $serverCount = count( $this->mServers );
1041 for ( $i = 1; $i < $serverCount; $i++ ) {
1042 $conn = $this->getAnyOpenConnection( $i );
1043 if ( $conn ) {
1044 return $conn->getReplicaPos();
1045 }
1046 }
1047 } else {
1048 return $masterConn->getMasterPos();
1049 }
1050
1051 return false;
1052 }
1053
1054 public function disable() {
1055 $this->closeAll();
1056 $this->disabled = true;
1057 }
1058
1059 public function closeAll() {
1060 $this->forEachOpenConnection( function ( IDatabase $conn ) {
1061 $host = $conn->getServer();
1062 $this->connLogger->debug( "Closing connection to database '$host'." );
1063 $conn->close();
1064 } );
1065
1066 $this->mConns = [
1067 'local' => [],
1068 'foreignFree' => [],
1069 'foreignUsed' => [],
1070 ];
1071 $this->connsOpened = 0;
1072 }
1073
1074 public function closeConnection( IDatabase $conn ) {
1075 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1076 foreach ( $this->mConns as $type => $connsByServer ) {
1077 if ( !isset( $connsByServer[$serverIndex] ) ) {
1078 continue;
1079 }
1080
1081 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1082 if ( $conn === $trackedConn ) {
1083 $host = $this->getServerName( $i );
1084 $this->connLogger->debug( "Closing connection to database $i at '$host'." );
1085 unset( $this->mConns[$type][$serverIndex][$i] );
1086 --$this->connsOpened;
1087 break 2;
1088 }
1089 }
1090 }
1091
1092 $conn->close();
1093 }
1094
1095 public function commitAll( $fname = __METHOD__ ) {
1096 $failures = [];
1097
1098 $restore = ( $this->trxRoundId !== false );
1099 $this->trxRoundId = false;
1100 $this->forEachOpenConnection(
1101 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1102 try {
1103 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1104 } catch ( DBError $e ) {
1105 call_user_func( $this->errorLogger, $e );
1106 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1107 }
1108 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1109 $this->undoTransactionRoundFlags( $conn );
1110 }
1111 }
1112 );
1113
1114 if ( $failures ) {
1115 throw new DBExpectedError(
1116 null,
1117 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1118 );
1119 }
1120 }
1121
1122 public function finalizeMasterChanges() {
1123 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1124 // Any error should cause all DB transactions to be rolled back together
1125 $conn->setTrxEndCallbackSuppression( false );
1126 $conn->runOnTransactionPreCommitCallbacks();
1127 // Defer post-commit callbacks until COMMIT finishes for all DBs
1128 $conn->setTrxEndCallbackSuppression( true );
1129 } );
1130 }
1131
1132 public function approveMasterChanges( array $options ) {
1133 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1134 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1135 // If atomic sections or explicit transactions are still open, some caller must have
1136 // caught an exception but failed to properly rollback any changes. Detect that and
1137 // throw and error (causing rollback).
1138 if ( $conn->explicitTrxActive() ) {
1139 throw new DBTransactionError(
1140 $conn,
1141 "Explicit transaction still active. A caller may have caught an error."
1142 );
1143 }
1144 // Assert that the time to replicate the transaction will be sane.
1145 // If this fails, then all DB transactions will be rollback back together.
1146 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1147 if ( $limit > 0 && $time > $limit ) {
1148 throw new DBTransactionSizeError(
1149 $conn,
1150 "Transaction spent $time second(s) in writes, exceeding the $limit limit.",
1151 [ $time, $limit ]
1152 );
1153 }
1154 // If a connection sits idle while slow queries execute on another, that connection
1155 // may end up dropped before the commit round is reached. Ping servers to detect this.
1156 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1157 throw new DBTransactionError(
1158 $conn,
1159 "A connection to the {$conn->getDBname()} database was lost before commit."
1160 );
1161 }
1162 } );
1163 }
1164
1165 public function beginMasterChanges( $fname = __METHOD__ ) {
1166 if ( $this->trxRoundId !== false ) {
1167 throw new DBTransactionError(
1168 null,
1169 "$fname: Transaction round '{$this->trxRoundId}' already started."
1170 );
1171 }
1172 $this->trxRoundId = $fname;
1173
1174 $failures = [];
1175 $this->forEachOpenMasterConnection(
1176 function ( Database $conn ) use ( $fname, &$failures ) {
1177 $conn->setTrxEndCallbackSuppression( true );
1178 try {
1179 $conn->flushSnapshot( $fname );
1180 } catch ( DBError $e ) {
1181 call_user_func( $this->errorLogger, $e );
1182 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1183 }
1184 $conn->setTrxEndCallbackSuppression( false );
1185 $this->applyTransactionRoundFlags( $conn );
1186 }
1187 );
1188
1189 if ( $failures ) {
1190 throw new DBExpectedError(
1191 null,
1192 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1193 );
1194 }
1195 }
1196
1197 public function commitMasterChanges( $fname = __METHOD__ ) {
1198 $failures = [];
1199
1200 /** @noinspection PhpUnusedLocalVariableInspection */
1201 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1202
1203 $restore = ( $this->trxRoundId !== false );
1204 $this->trxRoundId = false;
1205 $this->forEachOpenMasterConnection(
1206 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1207 try {
1208 if ( $conn->writesOrCallbacksPending() ) {
1209 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1210 } elseif ( $restore ) {
1211 $conn->flushSnapshot( $fname );
1212 }
1213 } catch ( DBError $e ) {
1214 call_user_func( $this->errorLogger, $e );
1215 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1216 }
1217 if ( $restore ) {
1218 $this->undoTransactionRoundFlags( $conn );
1219 }
1220 }
1221 );
1222
1223 if ( $failures ) {
1224 throw new DBExpectedError(
1225 null,
1226 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1227 );
1228 }
1229 }
1230
1231 public function runMasterPostTrxCallbacks( $type ) {
1232 $e = null; // first exception
1233 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1234 $conn->setTrxEndCallbackSuppression( false );
1235 if ( $conn->writesOrCallbacksPending() ) {
1236 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1237 // (which finished its callbacks already). Warn and recover in this case. Let the
1238 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1239 $this->queryLogger->error( __METHOD__ . ": found writes/callbacks pending." );
1240 return;
1241 } elseif ( $conn->trxLevel() ) {
1242 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1243 // thus leaving an implicit read-only transaction open at this point. It
1244 // also happens if onTransactionIdle() callbacks leave implicit transactions
1245 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1246 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1247 return;
1248 }
1249 try {
1250 $conn->runOnTransactionIdleCallbacks( $type );
1251 } catch ( Exception $ex ) {
1252 $e = $e ?: $ex;
1253 }
1254 try {
1255 $conn->runTransactionListenerCallbacks( $type );
1256 } catch ( Exception $ex ) {
1257 $e = $e ?: $ex;
1258 }
1259 } );
1260
1261 return $e;
1262 }
1263
1264 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1265 $restore = ( $this->trxRoundId !== false );
1266 $this->trxRoundId = false;
1267 $this->forEachOpenMasterConnection(
1268 function ( IDatabase $conn ) use ( $fname, $restore ) {
1269 if ( $conn->writesOrCallbacksPending() ) {
1270 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1271 }
1272 if ( $restore ) {
1273 $this->undoTransactionRoundFlags( $conn );
1274 }
1275 }
1276 );
1277 }
1278
1279 public function suppressTransactionEndCallbacks() {
1280 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1281 $conn->setTrxEndCallbackSuppression( true );
1282 } );
1283 }
1284
1285 /**
1286 * @param IDatabase $conn
1287 */
1288 private function applyTransactionRoundFlags( IDatabase $conn ) {
1289 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1290 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1291 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1292 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1293 // If config has explicitly requested DBO_TRX be either on or off by not
1294 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1295 // for things like blob stores (ExternalStore) which want auto-commit mode.
1296 }
1297 }
1298
1299 /**
1300 * @param IDatabase $conn
1301 */
1302 private function undoTransactionRoundFlags( IDatabase $conn ) {
1303 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1304 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1305 }
1306 }
1307
1308 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1309 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1310 $conn->flushSnapshot( __METHOD__ );
1311 } );
1312 }
1313
1314 public function hasMasterConnection() {
1315 return $this->isOpen( $this->getWriterIndex() );
1316 }
1317
1318 public function hasMasterChanges() {
1319 $pending = 0;
1320 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1321 $pending |= $conn->writesOrCallbacksPending();
1322 } );
1323
1324 return (bool)$pending;
1325 }
1326
1327 public function lastMasterChangeTimestamp() {
1328 $lastTime = false;
1329 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1330 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1331 } );
1332
1333 return $lastTime;
1334 }
1335
1336 public function hasOrMadeRecentMasterChanges( $age = null ) {
1337 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1338
1339 return ( $this->hasMasterChanges()
1340 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1341 }
1342
1343 public function pendingMasterChangeCallers() {
1344 $fnames = [];
1345 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1346 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1347 } );
1348
1349 return $fnames;
1350 }
1351
1352 public function getLaggedReplicaMode( $domain = false ) {
1353 // No-op if there is only one DB (also avoids recursion)
1354 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1355 try {
1356 // See if laggedReplicaMode gets set
1357 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1358 $this->reuseConnection( $conn );
1359 } catch ( DBConnectionError $e ) {
1360 // Avoid expensive re-connect attempts and failures
1361 $this->allReplicasDownMode = true;
1362 $this->laggedReplicaMode = true;
1363 }
1364 }
1365
1366 return $this->laggedReplicaMode;
1367 }
1368
1369 /**
1370 * @param bool $domain
1371 * @return bool
1372 * @deprecated 1.28; use getLaggedReplicaMode()
1373 */
1374 public function getLaggedSlaveMode( $domain = false ) {
1375 return $this->getLaggedReplicaMode( $domain );
1376 }
1377
1378 public function laggedReplicaUsed() {
1379 return $this->laggedReplicaMode;
1380 }
1381
1382 /**
1383 * @return bool
1384 * @since 1.27
1385 * @deprecated Since 1.28; use laggedReplicaUsed()
1386 */
1387 public function laggedSlaveUsed() {
1388 return $this->laggedReplicaUsed();
1389 }
1390
1391 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1392 if ( $this->readOnlyReason !== false ) {
1393 return $this->readOnlyReason;
1394 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1395 if ( $this->allReplicasDownMode ) {
1396 return 'The database has been automatically locked ' .
1397 'until the replica database servers become available';
1398 } else {
1399 return 'The database has been automatically locked ' .
1400 'while the replica database servers catch up to the master.';
1401 }
1402 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1403 return 'The database master is running in read-only mode.';
1404 }
1405
1406 return false;
1407 }
1408
1409 /**
1410 * @param string $domain Domain ID, or false for the current domain
1411 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1412 * @return bool
1413 */
1414 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1415 $cache = $this->wanCache;
1416 $masterServer = $this->getServerName( $this->getWriterIndex() );
1417
1418 return (bool)$cache->getWithSetCallback(
1419 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1420 self::TTL_CACHE_READONLY,
1421 function () use ( $domain, $conn ) {
1422 $old = $this->trxProfiler->setSilenced( true );
1423 try {
1424 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1425 $readOnly = (int)$dbw->serverIsReadOnly();
1426 if ( !$conn ) {
1427 $this->reuseConnection( $dbw );
1428 }
1429 } catch ( DBError $e ) {
1430 $readOnly = 0;
1431 }
1432 $this->trxProfiler->setSilenced( $old );
1433 return $readOnly;
1434 },
1435 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1436 );
1437 }
1438
1439 public function allowLagged( $mode = null ) {
1440 if ( $mode === null ) {
1441 return $this->mAllowLagged;
1442 }
1443 $this->mAllowLagged = $mode;
1444
1445 return $this->mAllowLagged;
1446 }
1447
1448 public function pingAll() {
1449 $success = true;
1450 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1451 if ( !$conn->ping() ) {
1452 $success = false;
1453 }
1454 } );
1455
1456 return $success;
1457 }
1458
1459 public function forEachOpenConnection( $callback, array $params = [] ) {
1460 foreach ( $this->mConns as $connsByServer ) {
1461 foreach ( $connsByServer as $serverConns ) {
1462 foreach ( $serverConns as $conn ) {
1463 $mergedParams = array_merge( [ $conn ], $params );
1464 call_user_func_array( $callback, $mergedParams );
1465 }
1466 }
1467 }
1468 }
1469
1470 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1471 $masterIndex = $this->getWriterIndex();
1472 foreach ( $this->mConns as $connsByServer ) {
1473 if ( isset( $connsByServer[$masterIndex] ) ) {
1474 /** @var IDatabase $conn */
1475 foreach ( $connsByServer[$masterIndex] as $conn ) {
1476 $mergedParams = array_merge( [ $conn ], $params );
1477 call_user_func_array( $callback, $mergedParams );
1478 }
1479 }
1480 }
1481 }
1482
1483 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1484 foreach ( $this->mConns as $connsByServer ) {
1485 foreach ( $connsByServer as $i => $serverConns ) {
1486 if ( $i === $this->getWriterIndex() ) {
1487 continue; // skip master
1488 }
1489 foreach ( $serverConns as $conn ) {
1490 $mergedParams = array_merge( [ $conn ], $params );
1491 call_user_func_array( $callback, $mergedParams );
1492 }
1493 }
1494 }
1495 }
1496
1497 public function getMaxLag( $domain = false ) {
1498 $maxLag = -1;
1499 $host = '';
1500 $maxIndex = 0;
1501
1502 if ( $this->getServerCount() <= 1 ) {
1503 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1504 }
1505
1506 $lagTimes = $this->getLagTimes( $domain );
1507 foreach ( $lagTimes as $i => $lag ) {
1508 if ( $this->mLoads[$i] > 0 && $lag > $maxLag ) {
1509 $maxLag = $lag;
1510 $host = $this->mServers[$i]['host'];
1511 $maxIndex = $i;
1512 }
1513 }
1514
1515 return [ $host, $maxLag, $maxIndex ];
1516 }
1517
1518 public function getLagTimes( $domain = false ) {
1519 if ( $this->getServerCount() <= 1 ) {
1520 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1521 }
1522
1523 $knownLagTimes = []; // map of (server index => 0 seconds)
1524 $indexesWithLag = [];
1525 foreach ( $this->mServers as $i => $server ) {
1526 if ( empty( $server['is static'] ) ) {
1527 $indexesWithLag[] = $i; // DB server might have replication lag
1528 } else {
1529 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1530 }
1531 }
1532
1533 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1534 }
1535
1536 public function safeGetLag( IDatabase $conn ) {
1537 if ( $this->getServerCount() <= 1 ) {
1538 return 0;
1539 } else {
1540 return $conn->getLag();
1541 }
1542 }
1543
1544 /**
1545 * @param IDatabase $conn
1546 * @param DBMasterPos|bool $pos
1547 * @param int $timeout
1548 * @return bool
1549 */
1550 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = 10 ) {
1551 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1552 return true; // server is not a replica DB
1553 }
1554
1555 if ( !$pos ) {
1556 // Get the current master position, opening a connection if needed
1557 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1558 if ( $masterConn ) {
1559 $pos = $masterConn->getMasterPos();
1560 } else {
1561 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1562 $pos = $masterConn->getMasterPos();
1563 $this->closeConnection( $masterConn );
1564 }
1565 }
1566
1567 if ( $pos instanceof DBMasterPos ) {
1568 $result = $conn->masterPosWait( $pos, $timeout );
1569 if ( $result == -1 || is_null( $result ) ) {
1570 $msg = __METHOD__ . ": Timed out waiting on {$conn->getServer()} pos {$pos}";
1571 $this->replLogger->warning( "$msg" );
1572 $ok = false;
1573 } else {
1574 $this->replLogger->info( __METHOD__ . ": Done" );
1575 $ok = true;
1576 }
1577 } else {
1578 $ok = false; // something is misconfigured
1579 $this->replLogger->error( "Could not get master pos for {$conn->getServer()}." );
1580 }
1581
1582 return $ok;
1583 }
1584
1585 public function setTransactionListener( $name, callable $callback = null ) {
1586 if ( $callback ) {
1587 $this->trxRecurringCallbacks[$name] = $callback;
1588 } else {
1589 unset( $this->trxRecurringCallbacks[$name] );
1590 }
1591 $this->forEachOpenMasterConnection(
1592 function ( IDatabase $conn ) use ( $name, $callback ) {
1593 $conn->setTransactionListener( $name, $callback );
1594 }
1595 );
1596 }
1597
1598 public function setTableAliases( array $aliases ) {
1599 $this->tableAliases = $aliases;
1600 }
1601
1602 public function setDomainPrefix( $prefix ) {
1603 if ( $this->mConns['foreignUsed'] ) {
1604 // Do not switch connections to explicit foreign domains unless marked as free
1605 $domains = [];
1606 foreach ( $this->mConns['foreignUsed'] as $i => $connsByDomain ) {
1607 $domains = array_merge( $domains, array_keys( $connsByDomain ) );
1608 }
1609 $domains = implode( ', ', $domains );
1610 throw new DBUnexpectedError( null,
1611 "Foreign domain connections are still in use ($domains)." );
1612 }
1613
1614 $this->localDomain = new DatabaseDomain(
1615 $this->localDomain->getDatabase(),
1616 null,
1617 $prefix
1618 );
1619
1620 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix ) {
1621 $db->tablePrefix( $prefix );
1622 } );
1623 }
1624
1625 /**
1626 * Make PHP ignore user aborts/disconnects until the returned
1627 * value leaves scope. This returns null and does nothing in CLI mode.
1628 *
1629 * @return ScopedCallback|null
1630 */
1631 final protected function getScopedPHPBehaviorForCommit() {
1632 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1633 $old = ignore_user_abort( true ); // avoid half-finished operations
1634 return new ScopedCallback( function () use ( $old ) {
1635 ignore_user_abort( $old );
1636 } );
1637 }
1638
1639 return null;
1640 }
1641
1642 function __destruct() {
1643 // Avoid connection leaks for sanity
1644 $this->disable();
1645 }
1646 }
1647
1648 class_alias( LoadBalancer::class, 'LoadBalancer' );