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