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