Merge "Create a custom log formatter that allows log entries to contain wikitext"
[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 $groups = ( $groups === false || $groups === [] )
684 ? [ false ] // check one "group": the generic pool
685 : (array)$groups;
686
687 $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
688 $oldConnsOpened = $this->connsOpened; // connections open now
689
690 if ( $i == self::DB_MASTER ) {
691 $i = $this->getWriterIndex();
692 } else {
693 # Try to find an available server in any the query groups (in order)
694 foreach ( $groups as $group ) {
695 $groupIndex = $this->getReaderIndex( $group, $domain );
696 if ( $groupIndex !== false ) {
697 $i = $groupIndex;
698 break;
699 }
700 }
701 }
702
703 # Operation-based index
704 if ( $i == self::DB_REPLICA ) {
705 $this->lastError = 'Unknown error'; // reset error string
706 # Try the general server pool if $groups are unavailable.
707 $i = ( $groups === [ false ] )
708 ? false // don't bother with this if that is what was tried above
709 : $this->getReaderIndex( false, $domain );
710 # Couldn't find a working server in getReaderIndex()?
711 if ( $i === false ) {
712 $this->lastError = 'No working replica DB server: ' . $this->lastError;
713 // Throw an exception
714 $this->reportConnectionError();
715 return null; // not reached
716 }
717 }
718
719 # Now we have an explicit index into the servers array
720 $conn = $this->openConnection( $i, $domain, $flags );
721 if ( !$conn ) {
722 // Throw an exception
723 $this->reportConnectionError();
724 return null; // not reached
725 }
726
727 # Profile any new connections that happen
728 if ( $this->connsOpened > $oldConnsOpened ) {
729 $host = $conn->getServer();
730 $dbname = $conn->getDBname();
731 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
732 }
733
734 if ( $masterOnly ) {
735 # Make master-requested DB handles inherit any read-only mode setting
736 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
737 }
738
739 return $conn;
740 }
741
742 public function reuseConnection( IDatabase $conn ) {
743 $serverIndex = $conn->getLBInfo( 'serverIndex' );
744 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
745 if ( $serverIndex === null || $refCount === null ) {
746 /**
747 * This can happen in code like:
748 * foreach ( $dbs as $db ) {
749 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
750 * ...
751 * $lb->reuseConnection( $conn );
752 * }
753 * When a connection to the local DB is opened in this way, reuseConnection()
754 * should be ignored
755 */
756 return;
757 } elseif ( $conn instanceof DBConnRef ) {
758 // DBConnRef already handles calling reuseConnection() and only passes the live
759 // Database instance to this method. Any caller passing in a DBConnRef is broken.
760 $this->connLogger->error(
761 __METHOD__ . ": got DBConnRef instance.\n" .
762 ( new RuntimeException() )->getTraceAsString() );
763
764 return;
765 }
766
767 if ( $this->disabled ) {
768 return; // DBConnRef handle probably survived longer than the LoadBalancer
769 }
770
771 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
772 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
773 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
774 } else {
775 $connFreeKey = self::KEY_FOREIGN_FREE;
776 $connInUseKey = self::KEY_FOREIGN_INUSE;
777 }
778
779 $domain = $conn->getDomainID();
780 if ( !isset( $this->conns[$connInUseKey][$serverIndex][$domain] ) ) {
781 throw new InvalidArgumentException( __METHOD__ .
782 ": connection $serverIndex/$domain not found; it may have already been freed." );
783 } elseif ( $this->conns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
784 throw new InvalidArgumentException( __METHOD__ .
785 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
786 }
787
788 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
789 if ( $refCount <= 0 ) {
790 $this->conns[$connFreeKey][$serverIndex][$domain] = $conn;
791 unset( $this->conns[$connInUseKey][$serverIndex][$domain] );
792 if ( !$this->conns[$connInUseKey][$serverIndex] ) {
793 unset( $this->conns[$connInUseKey][$serverIndex] ); // clean up
794 }
795 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
796 } else {
797 $this->connLogger->debug( __METHOD__ .
798 ": reference count for $serverIndex/$domain reduced to $refCount" );
799 }
800 }
801
802 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
803 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
804
805 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
806 }
807
808 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
809 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
810
811 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
812 }
813
814 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
815 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
816
817 return new MaintainableDBConnRef(
818 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
819 }
820
821 public function openConnection( $i, $domain = false, $flags = 0 ) {
822 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
823 $domain = false; // local connection requested
824 }
825
826 if ( !$this->chronProtInitialized && $this->chronProt ) {
827 $this->connLogger->debug( __METHOD__ . ': calling initLB() before first connection.' );
828 // Load CP positions before connecting so that doWait() triggers later if needed
829 $this->chronProtInitialized = true;
830 $this->chronProt->initLB( $this );
831 }
832
833 // Check if an auto-commit connection is being requested. If so, it will not reuse the
834 // main set of DB connections but rather its own pool since:
835 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
836 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
837 $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
838
839 if ( $domain !== false ) {
840 // Connection is to a foreign domain
841 $conn = $this->openForeignConnection( $i, $domain, $flags );
842 } else {
843 // Connection is to the local domain
844 $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
845 if ( isset( $this->conns[$connKey][$i][0] ) ) {
846 $conn = $this->conns[$connKey][$i][0];
847 } else {
848 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
849 throw new InvalidArgumentException( "No server with index '$i'." );
850 }
851 // Open a new connection
852 $server = $this->servers[$i];
853 $server['serverIndex'] = $i;
854 $server['autoCommitOnly'] = $autoCommit;
855 if ( $this->localDomain->getDatabase() !== null ) {
856 // Use the local domain table prefix if the local domain is specified
857 $server['tablePrefix'] = $this->localDomain->getTablePrefix();
858 }
859 $conn = $this->reallyOpenConnection( $server, $this->localDomain );
860 $host = $this->getServerName( $i );
861 if ( $conn->isOpen() ) {
862 $this->connLogger->debug(
863 __METHOD__ . ": connected to database $i at '$host'." );
864 $this->conns[$connKey][$i][0] = $conn;
865 } else {
866 $this->connLogger->warning(
867 __METHOD__ . ": failed to connect to database $i at '$host'." );
868 $this->errorConnection = $conn;
869 $conn = false;
870 }
871 }
872 }
873
874 if ( $conn instanceof IDatabase && !$conn->isOpen() ) {
875 // Connection was made but later unrecoverably lost for some reason.
876 // Do not return a handle that will just throw exceptions on use,
877 // but let the calling code (e.g. getReaderIndex) try another server.
878 // See DatabaseMyslBase::ping() for how this can happen.
879 $this->errorConnection = $conn;
880 $conn = false;
881 }
882
883 if ( $autoCommit && $conn instanceof IDatabase ) {
884 $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
885 }
886
887 return $conn;
888 }
889
890 /**
891 * Open a connection to a foreign DB, or return one if it is already open.
892 *
893 * Increments a reference count on the returned connection which locks the
894 * connection to the requested domain. This reference count can be
895 * decremented by calling reuseConnection().
896 *
897 * If a connection is open to the appropriate server already, but with the wrong
898 * database, it will be switched to the right database and returned, as long as
899 * it has been freed first with reuseConnection().
900 *
901 * On error, returns false, and the connection which caused the
902 * error will be available via $this->errorConnection.
903 *
904 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
905 *
906 * @param int $i Server index
907 * @param string $domain Domain ID to open
908 * @param int $flags Class CONN_* constant bitfield
909 * @return Database
910 */
911 private function openForeignConnection( $i, $domain, $flags = 0 ) {
912 $domainInstance = DatabaseDomain::newFromId( $domain );
913 $dbName = $domainInstance->getDatabase();
914 $prefix = $domainInstance->getTablePrefix();
915 $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
916
917 if ( $autoCommit ) {
918 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
919 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
920 } else {
921 $connFreeKey = self::KEY_FOREIGN_FREE;
922 $connInUseKey = self::KEY_FOREIGN_INUSE;
923 }
924
925 if ( isset( $this->conns[$connInUseKey][$i][$domain] ) ) {
926 // Reuse an in-use connection for the same domain
927 $conn = $this->conns[$connInUseKey][$i][$domain];
928 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
929 } elseif ( isset( $this->conns[$connFreeKey][$i][$domain] ) ) {
930 // Reuse a free connection for the same domain
931 $conn = $this->conns[$connFreeKey][$i][$domain];
932 unset( $this->conns[$connFreeKey][$i][$domain] );
933 $this->conns[$connInUseKey][$i][$domain] = $conn;
934 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
935 } elseif ( !empty( $this->conns[$connFreeKey][$i] ) ) {
936 // Reuse a free connection from another domain
937 $conn = reset( $this->conns[$connFreeKey][$i] );
938 $oldDomain = key( $this->conns[$connFreeKey][$i] );
939 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
940 $this->lastError = "Error selecting database '$dbName' on server " .
941 $conn->getServer() . " from client host {$this->host}";
942 $this->errorConnection = $conn;
943 $conn = false;
944 } else {
945 $conn->tablePrefix( $prefix );
946 unset( $this->conns[$connFreeKey][$i][$oldDomain] );
947 // Note that if $domain is an empty string, getDomainID() might not match it
948 $this->conns[$connInUseKey][$i][$conn->getDomainId()] = $conn;
949 $this->connLogger->debug( __METHOD__ .
950 ": reusing free connection from $oldDomain for $domain" );
951 }
952 } else {
953 if ( !isset( $this->servers[$i] ) || !is_array( $this->servers[$i] ) ) {
954 throw new InvalidArgumentException( "No server with index '$i'." );
955 }
956 // Open a new connection
957 $server = $this->servers[$i];
958 $server['serverIndex'] = $i;
959 $server['foreignPoolRefCount'] = 0;
960 $server['foreign'] = true;
961 $server['autoCommitOnly'] = $autoCommit;
962 $conn = $this->reallyOpenConnection( $server, $domainInstance );
963 if ( !$conn->isOpen() ) {
964 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
965 $this->errorConnection = $conn;
966 $conn = false;
967 } else {
968 $conn->tablePrefix( $prefix ); // as specified
969 // Note that if $domain is an empty string, getDomainID() might not match it
970 $this->conns[$connInUseKey][$i][$conn->getDomainID()] = $conn;
971 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
972 }
973 }
974
975 // Increment reference count
976 if ( $conn instanceof IDatabase ) {
977 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
978 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
979 }
980
981 return $conn;
982 }
983
984 /**
985 * Test if the specified index represents an open connection
986 *
987 * @param int $index Server index
988 * @access private
989 * @return bool
990 */
991 private function isOpen( $index ) {
992 if ( !is_int( $index ) ) {
993 return false;
994 }
995
996 return (bool)$this->getAnyOpenConnection( $index );
997 }
998
999 /**
1000 * Open a new network connection to a server (uncached)
1001 *
1002 * Returns a Database object whether or not the connection was successful.
1003 *
1004 * @param array $server
1005 * @param DatabaseDomain $domainOverride Use an unspecified domain to not select any database
1006 * @return Database
1007 * @throws DBAccessError
1008 * @throws InvalidArgumentException
1009 */
1010 protected function reallyOpenConnection( array $server, DatabaseDomain $domainOverride ) {
1011 if ( $this->disabled ) {
1012 throw new DBAccessError();
1013 }
1014
1015 // Handle $domainOverride being a specified or an unspecified domain
1016 if ( $domainOverride->getDatabase() === null ) {
1017 // Normally, an RDBMS requires a DB name specified on connection and the $server
1018 // configuration array is assumed to already specify an appropriate DB name.
1019 if ( $server['type'] === 'mysql' ) {
1020 // For MySQL, DATABASE and SCHEMA are synonyms, connections need not specify a DB,
1021 // and the DB name in $server might not exist due to legacy reasons (the default
1022 // domain used to ignore the local LB domain, even when mismatched).
1023 $server['dbname'] = null;
1024 }
1025 } else {
1026 $server['dbname'] = $domainOverride->getDatabase();
1027 $server['schema'] = $domainOverride->getSchema();
1028 }
1029
1030 // Let the handle know what the cluster master is (e.g. "db1052")
1031 $masterName = $this->getServerName( $this->getWriterIndex() );
1032 $server['clusterMasterHost'] = $masterName;
1033
1034 // Log when many connection are made on requests
1035 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
1036 $this->perfLogger->warning( __METHOD__ . ": " .
1037 "{$this->connsOpened}+ connections made (master=$masterName)" );
1038 }
1039
1040 $server['srvCache'] = $this->srvCache;
1041 // Set loggers and profilers
1042 $server['connLogger'] = $this->connLogger;
1043 $server['queryLogger'] = $this->queryLogger;
1044 $server['errorLogger'] = $this->errorLogger;
1045 $server['profiler'] = $this->profiler;
1046 $server['trxProfiler'] = $this->trxProfiler;
1047 // Use the same agent and PHP mode for all DB handles
1048 $server['cliMode'] = $this->cliMode;
1049 $server['agent'] = $this->agent;
1050 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
1051 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
1052 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
1053
1054 // Create a live connection object
1055 try {
1056 $db = Database::factory( $server['type'], $server );
1057 } catch ( DBConnectionError $e ) {
1058 // FIXME: This is probably the ugliest thing I have ever done to
1059 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
1060 $db = $e->db;
1061 }
1062
1063 $db->setLBInfo( $server );
1064 $db->setLazyMasterHandle(
1065 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
1066 );
1067 $db->setTableAliases( $this->tableAliases );
1068
1069 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1070 if ( $this->trxRoundId !== false ) {
1071 $this->applyTransactionRoundFlags( $db );
1072 }
1073 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1074 $db->setTransactionListener( $name, $callback );
1075 }
1076 }
1077
1078 return $db;
1079 }
1080
1081 /**
1082 * @throws DBConnectionError
1083 */
1084 private function reportConnectionError() {
1085 $conn = $this->errorConnection; // the connection which caused the error
1086 $context = [
1087 'method' => __METHOD__,
1088 'last_error' => $this->lastError,
1089 ];
1090
1091 if ( $conn instanceof IDatabase ) {
1092 $context['db_server'] = $conn->getServer();
1093 $this->connLogger->warning(
1094 __METHOD__ . ": connection error: {last_error} ({db_server})",
1095 $context
1096 );
1097
1098 // throws DBConnectionError
1099 $conn->reportConnectionError( "{$this->lastError} ({$context['db_server']})" );
1100 } else {
1101 // No last connection, probably due to all servers being too busy
1102 $this->connLogger->error(
1103 __METHOD__ .
1104 ": LB failure with no last connection. Connection error: {last_error}",
1105 $context
1106 );
1107
1108 // If all servers were busy, mLastError will contain something sensible
1109 throw new DBConnectionError( null, $this->lastError );
1110 }
1111 }
1112
1113 public function getWriterIndex() {
1114 return 0;
1115 }
1116
1117 public function haveIndex( $i ) {
1118 return array_key_exists( $i, $this->servers );
1119 }
1120
1121 public function isNonZeroLoad( $i ) {
1122 return array_key_exists( $i, $this->servers ) && $this->loads[$i] != 0;
1123 }
1124
1125 public function getServerCount() {
1126 return count( $this->servers );
1127 }
1128
1129 public function getServerName( $i ) {
1130 if ( isset( $this->servers[$i]['hostName'] ) ) {
1131 $name = $this->servers[$i]['hostName'];
1132 } elseif ( isset( $this->servers[$i]['host'] ) ) {
1133 $name = $this->servers[$i]['host'];
1134 } else {
1135 $name = '';
1136 }
1137
1138 return ( $name != '' ) ? $name : 'localhost';
1139 }
1140
1141 public function getServerType( $i ) {
1142 return isset( $this->servers[$i]['type'] ) ? $this->servers[$i]['type'] : 'unknown';
1143 }
1144
1145 public function getMasterPos() {
1146 # If this entire request was served from a replica DB without opening a connection to the
1147 # master (however unlikely that may be), then we can fetch the position from the replica DB.
1148 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1149 if ( !$masterConn ) {
1150 $serverCount = count( $this->servers );
1151 for ( $i = 1; $i < $serverCount; $i++ ) {
1152 $conn = $this->getAnyOpenConnection( $i );
1153 if ( $conn ) {
1154 return $conn->getReplicaPos();
1155 }
1156 }
1157 } else {
1158 return $masterConn->getMasterPos();
1159 }
1160
1161 return false;
1162 }
1163
1164 public function disable() {
1165 $this->closeAll();
1166 $this->disabled = true;
1167 }
1168
1169 public function closeAll() {
1170 $this->forEachOpenConnection( function ( IDatabase $conn ) {
1171 $host = $conn->getServer();
1172 $this->connLogger->debug(
1173 __METHOD__ . ": closing connection to database '$host'." );
1174 $conn->close();
1175 } );
1176
1177 $this->conns = [
1178 self::KEY_LOCAL => [],
1179 self::KEY_FOREIGN_INUSE => [],
1180 self::KEY_FOREIGN_FREE => [],
1181 self::KEY_LOCAL_NOROUND => [],
1182 self::KEY_FOREIGN_INUSE_NOROUND => [],
1183 self::KEY_FOREIGN_FREE_NOROUND => []
1184 ];
1185 $this->connsOpened = 0;
1186 }
1187
1188 public function closeConnection( IDatabase $conn ) {
1189 $serverIndex = $conn->getLBInfo( 'serverIndex' ); // second index level of mConns
1190 foreach ( $this->conns as $type => $connsByServer ) {
1191 if ( !isset( $connsByServer[$serverIndex] ) ) {
1192 continue;
1193 }
1194
1195 foreach ( $connsByServer[$serverIndex] as $i => $trackedConn ) {
1196 if ( $conn === $trackedConn ) {
1197 $host = $this->getServerName( $i );
1198 $this->connLogger->debug(
1199 __METHOD__ . ": closing connection to database $i at '$host'." );
1200 unset( $this->conns[$type][$serverIndex][$i] );
1201 --$this->connsOpened;
1202 break 2;
1203 }
1204 }
1205 }
1206
1207 $conn->close();
1208 }
1209
1210 public function commitAll( $fname = __METHOD__ ) {
1211 $failures = [];
1212
1213 $restore = ( $this->trxRoundId !== false );
1214 $this->trxRoundId = false;
1215 $this->forEachOpenConnection(
1216 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1217 try {
1218 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1219 } catch ( DBError $e ) {
1220 call_user_func( $this->errorLogger, $e );
1221 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1222 }
1223 if ( $restore && $conn->getLBInfo( 'master' ) ) {
1224 $this->undoTransactionRoundFlags( $conn );
1225 }
1226 }
1227 );
1228
1229 if ( $failures ) {
1230 throw new DBExpectedError(
1231 null,
1232 "Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1233 );
1234 }
1235 }
1236
1237 public function finalizeMasterChanges() {
1238 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1239 // Any error should cause all DB transactions to be rolled back together
1240 $conn->setTrxEndCallbackSuppression( false );
1241 $conn->runOnTransactionPreCommitCallbacks();
1242 // Defer post-commit callbacks until COMMIT finishes for all DBs
1243 $conn->setTrxEndCallbackSuppression( true );
1244 } );
1245 }
1246
1247 public function approveMasterChanges( array $options ) {
1248 $limit = isset( $options['maxWriteDuration'] ) ? $options['maxWriteDuration'] : 0;
1249 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( $limit ) {
1250 // If atomic sections or explicit transactions are still open, some caller must have
1251 // caught an exception but failed to properly rollback any changes. Detect that and
1252 // throw and error (causing rollback).
1253 if ( $conn->explicitTrxActive() ) {
1254 throw new DBTransactionError(
1255 $conn,
1256 "Explicit transaction still active. A caller may have caught an error."
1257 );
1258 }
1259 // Assert that the time to replicate the transaction will be sane.
1260 // If this fails, then all DB transactions will be rollback back together.
1261 $time = $conn->pendingWriteQueryDuration( $conn::ESTIMATE_DB_APPLY );
1262 if ( $limit > 0 && $time > $limit ) {
1263 throw new DBTransactionSizeError(
1264 $conn,
1265 "Transaction spent $time second(s) in writes, exceeding the limit of $limit.",
1266 [ $time, $limit ]
1267 );
1268 }
1269 // If a connection sits idle while slow queries execute on another, that connection
1270 // may end up dropped before the commit round is reached. Ping servers to detect this.
1271 if ( $conn->writesOrCallbacksPending() && !$conn->ping() ) {
1272 throw new DBTransactionError(
1273 $conn,
1274 "A connection to the {$conn->getDBname()} database was lost before commit."
1275 );
1276 }
1277 } );
1278 }
1279
1280 public function beginMasterChanges( $fname = __METHOD__ ) {
1281 if ( $this->trxRoundId !== false ) {
1282 throw new DBTransactionError(
1283 null,
1284 "$fname: Transaction round '{$this->trxRoundId}' already started."
1285 );
1286 }
1287 $this->trxRoundId = $fname;
1288
1289 $failures = [];
1290 $this->forEachOpenMasterConnection(
1291 function ( Database $conn ) use ( $fname, &$failures ) {
1292 $conn->setTrxEndCallbackSuppression( true );
1293 try {
1294 $conn->flushSnapshot( $fname );
1295 } catch ( DBError $e ) {
1296 call_user_func( $this->errorLogger, $e );
1297 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1298 }
1299 $conn->setTrxEndCallbackSuppression( false );
1300 $this->applyTransactionRoundFlags( $conn );
1301 }
1302 );
1303
1304 if ( $failures ) {
1305 throw new DBExpectedError(
1306 null,
1307 "$fname: Flush failed on server(s) " . implode( "\n", array_unique( $failures ) )
1308 );
1309 }
1310 }
1311
1312 public function commitMasterChanges( $fname = __METHOD__ ) {
1313 $failures = [];
1314
1315 /** @noinspection PhpUnusedLocalVariableInspection */
1316 $scope = $this->getScopedPHPBehaviorForCommit(); // try to ignore client aborts
1317
1318 $restore = ( $this->trxRoundId !== false );
1319 $this->trxRoundId = false;
1320 $this->forEachOpenMasterConnection(
1321 function ( IDatabase $conn ) use ( $fname, $restore, &$failures ) {
1322 try {
1323 if ( $conn->writesOrCallbacksPending() ) {
1324 $conn->commit( $fname, $conn::FLUSHING_ALL_PEERS );
1325 } elseif ( $restore ) {
1326 $conn->flushSnapshot( $fname );
1327 }
1328 } catch ( DBError $e ) {
1329 call_user_func( $this->errorLogger, $e );
1330 $failures[] = "{$conn->getServer()}: {$e->getMessage()}";
1331 }
1332 if ( $restore ) {
1333 $this->undoTransactionRoundFlags( $conn );
1334 }
1335 }
1336 );
1337
1338 if ( $failures ) {
1339 throw new DBExpectedError(
1340 null,
1341 "$fname: Commit failed on server(s) " . implode( "\n", array_unique( $failures ) )
1342 );
1343 }
1344 }
1345
1346 public function runMasterPostTrxCallbacks( $type ) {
1347 $e = null; // first exception
1348 $this->forEachOpenMasterConnection( function ( Database $conn ) use ( $type, &$e ) {
1349 $conn->setTrxEndCallbackSuppression( false );
1350 if ( $conn->writesOrCallbacksPending() ) {
1351 // This happens if onTransactionIdle() callbacks leave callbacks on *another* DB
1352 // (which finished its callbacks already). Warn and recover in this case. Let the
1353 // callbacks run in the final commitMasterChanges() in LBFactory::shutdown().
1354 $this->queryLogger->info( __METHOD__ . ": found writes/callbacks pending." );
1355 return;
1356 } elseif ( $conn->trxLevel() ) {
1357 // This happens for single-DB setups where DB_REPLICA uses the master DB,
1358 // thus leaving an implicit read-only transaction open at this point. It
1359 // also happens if onTransactionIdle() callbacks leave implicit transactions
1360 // open on *other* DBs (which is slightly improper). Let these COMMIT on the
1361 // next call to commitMasterChanges(), possibly in LBFactory::shutdown().
1362 return;
1363 }
1364 try {
1365 $conn->runOnTransactionIdleCallbacks( $type );
1366 } catch ( Exception $ex ) {
1367 $e = $e ?: $ex;
1368 }
1369 try {
1370 $conn->runTransactionListenerCallbacks( $type );
1371 } catch ( Exception $ex ) {
1372 $e = $e ?: $ex;
1373 }
1374 } );
1375
1376 return $e;
1377 }
1378
1379 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1380 $restore = ( $this->trxRoundId !== false );
1381 $this->trxRoundId = false;
1382 $this->forEachOpenMasterConnection(
1383 function ( IDatabase $conn ) use ( $fname, $restore ) {
1384 if ( $conn->writesOrCallbacksPending() || $conn->explicitTrxActive() ) {
1385 $conn->rollback( $fname, $conn::FLUSHING_ALL_PEERS );
1386 }
1387 if ( $restore ) {
1388 $this->undoTransactionRoundFlags( $conn );
1389 }
1390 }
1391 );
1392 }
1393
1394 public function suppressTransactionEndCallbacks() {
1395 $this->forEachOpenMasterConnection( function ( Database $conn ) {
1396 $conn->setTrxEndCallbackSuppression( true );
1397 } );
1398 }
1399
1400 /**
1401 * @param IDatabase $conn
1402 */
1403 private function applyTransactionRoundFlags( IDatabase $conn ) {
1404 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1405 return; // transaction rounds do not apply to these connections
1406 }
1407
1408 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1409 // DBO_TRX is controlled entirely by CLI mode presence with DBO_DEFAULT.
1410 // Force DBO_TRX even in CLI mode since a commit round is expected soon.
1411 $conn->setFlag( $conn::DBO_TRX, $conn::REMEMBER_PRIOR );
1412 // If config has explicitly requested DBO_TRX be either on or off by not
1413 // setting DBO_DEFAULT, then respect that. Forcing no transactions is useful
1414 // for things like blob stores (ExternalStore) which want auto-commit mode.
1415 }
1416 }
1417
1418 /**
1419 * @param IDatabase $conn
1420 */
1421 private function undoTransactionRoundFlags( IDatabase $conn ) {
1422 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
1423 return; // transaction rounds do not apply to these connections
1424 }
1425
1426 if ( $conn->getFlag( $conn::DBO_DEFAULT ) ) {
1427 $conn->restoreFlags( $conn::RESTORE_PRIOR );
1428 }
1429 }
1430
1431 public function flushReplicaSnapshots( $fname = __METHOD__ ) {
1432 $this->forEachOpenReplicaConnection( function ( IDatabase $conn ) {
1433 $conn->flushSnapshot( __METHOD__ );
1434 } );
1435 }
1436
1437 public function hasMasterConnection() {
1438 return $this->isOpen( $this->getWriterIndex() );
1439 }
1440
1441 public function hasMasterChanges() {
1442 $pending = 0;
1443 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$pending ) {
1444 $pending |= $conn->writesOrCallbacksPending();
1445 } );
1446
1447 return (bool)$pending;
1448 }
1449
1450 public function lastMasterChangeTimestamp() {
1451 $lastTime = false;
1452 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$lastTime ) {
1453 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1454 } );
1455
1456 return $lastTime;
1457 }
1458
1459 public function hasOrMadeRecentMasterChanges( $age = null ) {
1460 $age = ( $age === null ) ? $this->waitTimeout : $age;
1461
1462 return ( $this->hasMasterChanges()
1463 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1464 }
1465
1466 public function pendingMasterChangeCallers() {
1467 $fnames = [];
1468 $this->forEachOpenMasterConnection( function ( IDatabase $conn ) use ( &$fnames ) {
1469 $fnames = array_merge( $fnames, $conn->pendingWriteCallers() );
1470 } );
1471
1472 return $fnames;
1473 }
1474
1475 public function getLaggedReplicaMode( $domain = false ) {
1476 // No-op if there is only one DB (also avoids recursion)
1477 if ( !$this->laggedReplicaMode && $this->getServerCount() > 1 ) {
1478 try {
1479 // See if laggedReplicaMode gets set
1480 $conn = $this->getConnection( self::DB_REPLICA, false, $domain );
1481 $this->reuseConnection( $conn );
1482 } catch ( DBConnectionError $e ) {
1483 // Avoid expensive re-connect attempts and failures
1484 $this->allReplicasDownMode = true;
1485 $this->laggedReplicaMode = true;
1486 }
1487 }
1488
1489 return $this->laggedReplicaMode;
1490 }
1491
1492 /**
1493 * @param bool $domain
1494 * @return bool
1495 * @deprecated 1.28; use getLaggedReplicaMode()
1496 */
1497 public function getLaggedSlaveMode( $domain = false ) {
1498 return $this->getLaggedReplicaMode( $domain );
1499 }
1500
1501 public function laggedReplicaUsed() {
1502 return $this->laggedReplicaMode;
1503 }
1504
1505 /**
1506 * @return bool
1507 * @since 1.27
1508 * @deprecated Since 1.28; use laggedReplicaUsed()
1509 */
1510 public function laggedSlaveUsed() {
1511 return $this->laggedReplicaUsed();
1512 }
1513
1514 public function getReadOnlyReason( $domain = false, IDatabase $conn = null ) {
1515 if ( $this->readOnlyReason !== false ) {
1516 return $this->readOnlyReason;
1517 } elseif ( $this->getLaggedReplicaMode( $domain ) ) {
1518 if ( $this->allReplicasDownMode ) {
1519 return 'The database has been automatically locked ' .
1520 'until the replica database servers become available';
1521 } else {
1522 return 'The database has been automatically locked ' .
1523 'while the replica database servers catch up to the master.';
1524 }
1525 } elseif ( $this->masterRunningReadOnly( $domain, $conn ) ) {
1526 return 'The database master is running in read-only mode.';
1527 }
1528
1529 return false;
1530 }
1531
1532 /**
1533 * @param string $domain Domain ID, or false for the current domain
1534 * @param IDatabase|null $conn DB master connectionl used to avoid loops [optional]
1535 * @return bool
1536 */
1537 private function masterRunningReadOnly( $domain, IDatabase $conn = null ) {
1538 $cache = $this->wanCache;
1539 $masterServer = $this->getServerName( $this->getWriterIndex() );
1540
1541 return (bool)$cache->getWithSetCallback(
1542 $cache->makeGlobalKey( __CLASS__, 'server-read-only', $masterServer ),
1543 self::TTL_CACHE_READONLY,
1544 function () use ( $domain, $conn ) {
1545 $old = $this->trxProfiler->setSilenced( true );
1546 try {
1547 $dbw = $conn ?: $this->getConnection( self::DB_MASTER, [], $domain );
1548 $readOnly = (int)$dbw->serverIsReadOnly();
1549 if ( !$conn ) {
1550 $this->reuseConnection( $dbw );
1551 }
1552 } catch ( DBError $e ) {
1553 $readOnly = 0;
1554 }
1555 $this->trxProfiler->setSilenced( $old );
1556 return $readOnly;
1557 },
1558 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'busyValue' => 0 ]
1559 );
1560 }
1561
1562 public function allowLagged( $mode = null ) {
1563 if ( $mode === null ) {
1564 return $this->allowLagged;
1565 }
1566 $this->allowLagged = $mode;
1567
1568 return $this->allowLagged;
1569 }
1570
1571 public function pingAll() {
1572 $success = true;
1573 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$success ) {
1574 if ( !$conn->ping() ) {
1575 $success = false;
1576 }
1577 } );
1578
1579 return $success;
1580 }
1581
1582 public function forEachOpenConnection( $callback, array $params = [] ) {
1583 foreach ( $this->conns as $connsByServer ) {
1584 foreach ( $connsByServer as $serverConns ) {
1585 foreach ( $serverConns as $conn ) {
1586 $mergedParams = array_merge( [ $conn ], $params );
1587 call_user_func_array( $callback, $mergedParams );
1588 }
1589 }
1590 }
1591 }
1592
1593 public function forEachOpenMasterConnection( $callback, array $params = [] ) {
1594 $masterIndex = $this->getWriterIndex();
1595 foreach ( $this->conns as $connsByServer ) {
1596 if ( isset( $connsByServer[$masterIndex] ) ) {
1597 /** @var IDatabase $conn */
1598 foreach ( $connsByServer[$masterIndex] as $conn ) {
1599 $mergedParams = array_merge( [ $conn ], $params );
1600 call_user_func_array( $callback, $mergedParams );
1601 }
1602 }
1603 }
1604 }
1605
1606 public function forEachOpenReplicaConnection( $callback, array $params = [] ) {
1607 foreach ( $this->conns as $connsByServer ) {
1608 foreach ( $connsByServer as $i => $serverConns ) {
1609 if ( $i === $this->getWriterIndex() ) {
1610 continue; // skip master
1611 }
1612 foreach ( $serverConns as $conn ) {
1613 $mergedParams = array_merge( [ $conn ], $params );
1614 call_user_func_array( $callback, $mergedParams );
1615 }
1616 }
1617 }
1618 }
1619
1620 public function getMaxLag( $domain = false ) {
1621 $maxLag = -1;
1622 $host = '';
1623 $maxIndex = 0;
1624
1625 if ( $this->getServerCount() <= 1 ) {
1626 return [ $host, $maxLag, $maxIndex ]; // no replication = no lag
1627 }
1628
1629 $lagTimes = $this->getLagTimes( $domain );
1630 foreach ( $lagTimes as $i => $lag ) {
1631 if ( $this->loads[$i] > 0 && $lag > $maxLag ) {
1632 $maxLag = $lag;
1633 $host = $this->servers[$i]['host'];
1634 $maxIndex = $i;
1635 }
1636 }
1637
1638 return [ $host, $maxLag, $maxIndex ];
1639 }
1640
1641 public function getLagTimes( $domain = false ) {
1642 if ( $this->getServerCount() <= 1 ) {
1643 return [ $this->getWriterIndex() => 0 ]; // no replication = no lag
1644 }
1645
1646 $knownLagTimes = []; // map of (server index => 0 seconds)
1647 $indexesWithLag = [];
1648 foreach ( $this->servers as $i => $server ) {
1649 if ( empty( $server['is static'] ) ) {
1650 $indexesWithLag[] = $i; // DB server might have replication lag
1651 } else {
1652 $knownLagTimes[$i] = 0; // DB server is a non-replicating and read-only archive
1653 }
1654 }
1655
1656 return $this->getLoadMonitor()->getLagTimes( $indexesWithLag, $domain ) + $knownLagTimes;
1657 }
1658
1659 public function safeGetLag( IDatabase $conn ) {
1660 if ( $this->getServerCount() <= 1 ) {
1661 return 0;
1662 } else {
1663 return $conn->getLag();
1664 }
1665 }
1666
1667 /**
1668 * @param IDatabase $conn
1669 * @param DBMasterPos|bool $pos
1670 * @param int|null $timeout
1671 * @return bool
1672 */
1673 public function safeWaitForMasterPos( IDatabase $conn, $pos = false, $timeout = null ) {
1674 $timeout = max( 1, $timeout ?: $this->waitTimeout );
1675
1676 if ( $this->getServerCount() <= 1 || !$conn->getLBInfo( 'replica' ) ) {
1677 return true; // server is not a replica DB
1678 }
1679
1680 if ( !$pos ) {
1681 // Get the current master position, opening a connection if needed
1682 $masterConn = $this->getAnyOpenConnection( $this->getWriterIndex() );
1683 if ( $masterConn ) {
1684 $pos = $masterConn->getMasterPos();
1685 } else {
1686 $masterConn = $this->openConnection( $this->getWriterIndex(), self::DOMAIN_ANY );
1687 $pos = $masterConn->getMasterPos();
1688 $this->closeConnection( $masterConn );
1689 }
1690 }
1691
1692 if ( $pos instanceof DBMasterPos ) {
1693 $result = $conn->masterPosWait( $pos, $timeout );
1694 if ( $result == -1 || is_null( $result ) ) {
1695 $msg = __METHOD__ . ': timed out waiting on {host} pos {pos}';
1696 $this->replLogger->warning( $msg, [
1697 'host' => $conn->getServer(),
1698 'pos' => $pos,
1699 'trace' => ( new RuntimeException() )->getTraceAsString()
1700 ] );
1701 $ok = false;
1702 } else {
1703 $this->replLogger->debug( __METHOD__ . ': done waiting' );
1704 $ok = true;
1705 }
1706 } else {
1707 $ok = false; // something is misconfigured
1708 $this->replLogger->error(
1709 __METHOD__ . ': could not get master pos for {host}',
1710 [
1711 'host' => $conn->getServer(),
1712 'trace' => ( new RuntimeException() )->getTraceAsString()
1713 ]
1714 );
1715 }
1716
1717 return $ok;
1718 }
1719
1720 public function setTransactionListener( $name, callable $callback = null ) {
1721 if ( $callback ) {
1722 $this->trxRecurringCallbacks[$name] = $callback;
1723 } else {
1724 unset( $this->trxRecurringCallbacks[$name] );
1725 }
1726 $this->forEachOpenMasterConnection(
1727 function ( IDatabase $conn ) use ( $name, $callback ) {
1728 $conn->setTransactionListener( $name, $callback );
1729 }
1730 );
1731 }
1732
1733 public function setTableAliases( array $aliases ) {
1734 $this->tableAliases = $aliases;
1735 }
1736
1737 public function setDomainPrefix( $prefix ) {
1738 // Find connections to explicit foreign domains still marked as in-use...
1739 $domainsInUse = [];
1740 $this->forEachOpenConnection( function ( IDatabase $conn ) use ( &$domainsInUse ) {
1741 // Once reuseConnection() is called on a handle, its reference count goes from 1 to 0.
1742 // Until then, it is still in use by the caller (explicitly or via DBConnRef scope).
1743 if ( $conn->getLBInfo( 'foreignPoolRefCount' ) > 0 ) {
1744 $domainsInUse[] = $conn->getDomainID();
1745 }
1746 } );
1747
1748 // Do not switch connections to explicit foreign domains unless marked as safe
1749 if ( $domainsInUse ) {
1750 $domains = implode( ', ', $domainsInUse );
1751 throw new DBUnexpectedError( null,
1752 "Foreign domain connections are still in use ($domains)." );
1753 }
1754
1755 $oldDomain = $this->localDomain->getId();
1756 $this->setLocalDomain( new DatabaseDomain(
1757 $this->localDomain->getDatabase(),
1758 $this->localDomain->getSchema(),
1759 $prefix
1760 ) );
1761
1762 $this->forEachOpenConnection( function ( IDatabase $db ) use ( $prefix, $oldDomain ) {
1763 if ( !$db->getLBInfo( 'foreign' ) ) {
1764 $db->tablePrefix( $prefix );
1765 }
1766 } );
1767 }
1768
1769 /**
1770 * @param DatabaseDomain $domain
1771 */
1772 private function setLocalDomain( DatabaseDomain $domain ) {
1773 $this->localDomain = $domain;
1774 // In case a caller assumes that the domain ID is simply <db>-<prefix>, which is almost
1775 // always true, gracefully handle the case when they fail to account for escaping.
1776 if ( $this->localDomain->getTablePrefix() != '' ) {
1777 $this->localDomainIdAlias =
1778 $this->localDomain->getDatabase() . '-' . $this->localDomain->getTablePrefix();
1779 } else {
1780 $this->localDomainIdAlias = $this->localDomain->getDatabase();
1781 }
1782 }
1783
1784 /**
1785 * Make PHP ignore user aborts/disconnects until the returned
1786 * value leaves scope. This returns null and does nothing in CLI mode.
1787 *
1788 * @return ScopedCallback|null
1789 */
1790 final protected function getScopedPHPBehaviorForCommit() {
1791 if ( PHP_SAPI != 'cli' ) { // https://bugs.php.net/bug.php?id=47540
1792 $old = ignore_user_abort( true ); // avoid half-finished operations
1793 return new ScopedCallback( function () use ( $old ) {
1794 ignore_user_abort( $old );
1795 } );
1796 }
1797
1798 return null;
1799 }
1800
1801 function __destruct() {
1802 // Avoid connection leaks for sanity
1803 $this->disable();
1804 }
1805 }
1806
1807 class_alias( LoadBalancer::class, 'LoadBalancer' );