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