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