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