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