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