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