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