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