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