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