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