Merge "ApiFeedWatchlist: Use guessSectionNameFromWikiText()"
[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'] ) ? $params['cliMode'] : PHP_SAPI === 'cli';
236 $this->agent = isset( $params['agent'] ) ? $params['agent'] : '';
237
238 if ( isset( $params['chronologyProtector'] ) ) {
239 $this->chronProt = $params['chronologyProtector'];
240 }
241 }
242
243 /**
244 * Get a LoadMonitor instance
245 *
246 * @return ILoadMonitor
247 */
248 private function getLoadMonitor() {
249 if ( !isset( $this->loadMonitor ) ) {
250 $compat = [
251 'LoadMonitor' => LoadMonitor::class,
252 'LoadMonitorNull' => LoadMonitorNull::class,
253 'LoadMonitorMySQL' => LoadMonitorMySQL::class,
254 ];
255
256 $class = $this->loadMonitorConfig['class'];
257 if ( isset( $compat[$class] ) ) {
258 $class = $compat[$class];
259 }
260
261 $this->loadMonitor = new $class(
262 $this, $this->srvCache, $this->wanCache, $this->loadMonitorConfig );
263 $this->loadMonitor->setLogger( $this->replLogger );
264 }
265
266 return $this->loadMonitor;
267 }
268
269 /**
270 * @param array $loads
271 * @param bool|string $domain Domain to get non-lagged for
272 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
273 * @return bool|int|string
274 */
275 private function getRandomNonLagged( array $loads, $domain = false, $maxLag = INF ) {
276 $lags = $this->getLagTimes( $domain );
277
278 # Unset excessively lagged servers
279 foreach ( $lags as $i => $lag ) {
280 if ( $i != 0 ) {
281 # How much lag this server nominally is allowed to have
282 $maxServerLag = isset( $this->mServers[$i]['max lag'] )
283 ? $this->mServers[$i]['max lag']
284 : $this->maxLag; // default
285 # Constrain that futher by $maxLag argument
286 $maxServerLag = min( $maxServerLag, $maxLag );
287
288 $host = $this->getServerName( $i );
289 if ( $lag === false && !is_infinite( $maxServerLag ) ) {
290 $this->replLogger->error(
291 "Server {host} is not replicating?", [ 'host' => $host ] );
292 unset( $loads[$i] );
293 } elseif ( $lag > $maxServerLag ) {
294 $this->replLogger->info(
295 "Server {host} has {lag} seconds of lag (>= {maxlag})",
296 [ 'host' => $host, 'lag' => $lag, 'maxlag' => $maxServerLag ]
297 );
298 unset( $loads[$i] );
299 }
300 }
301 }
302
303 # Find out if all the replica DBs with non-zero load are lagged
304 $sum = 0;
305 foreach ( $loads as $load ) {
306 $sum += $load;
307 }
308 if ( $sum == 0 ) {
309 # No appropriate DB servers except maybe the master and some replica DBs with zero load
310 # Do NOT use the master
311 # Instead, this function will return false, triggering read-only mode,
312 # and a lagged replica DB will be used instead.
313 return false;
314 }
315
316 if ( count( $loads ) == 0 ) {
317 return false;
318 }
319
320 # Return a random representative of the remainder
321 return ArrayUtils::pickRandom( $loads );
322 }
323
324 public function getReaderIndex( $group = false, $domain = false ) {
325 if ( count( $this->mServers ) == 1 ) {
326 // Skip the load balancing if there's only one server
327 return $this->getWriterIndex();
328 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
329 // Shortcut if the generic reader index was already cached
330 return $this->mReadIndex;
331 }
332
333 if ( $group !== false ) {
334 // Use the server weight array for this load group
335 if ( isset( $this->mGroupLoads[$group] ) ) {
336 $loads = $this->mGroupLoads[$group];
337 } else {
338 // No loads for this group, return false and the caller can use some other group
339 $this->connLogger->info( __METHOD__ . ": no loads for group $group" );
340
341 return false;
342 }
343 } else {
344 // Use the generic load group
345 $loads = $this->mLoads;
346 }
347
348 // Scale the configured load ratios according to each server's load and state
349 $this->getLoadMonitor()->scaleLoads( $loads, $domain );
350
351 // Pick a server to use, accounting for weights, load, lag, and mWaitForPos
352 list( $i, $laggedReplicaMode ) = $this->pickReaderIndex( $loads, $domain );
353 if ( $i === false ) {
354 // Replica DB connection unsuccessful
355 return false;
356 }
357
358 if ( $this->mWaitForPos && $i != $this->getWriterIndex() ) {
359 // Before any data queries are run, wait for the server to catch up to the
360 // specified position. This is used to improve session consistency. Note that
361 // when LoadBalancer::waitFor() sets mWaitForPos, the waiting triggers here,
362 // so update laggedReplicaMode as needed for consistency.
363 if ( !$this->doWait( $i ) ) {
364 $laggedReplicaMode = true;
365 }
366 }
367
368 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
369 // Cache the generic reader index for future ungrouped DB_REPLICA handles
370 $this->mReadIndex = $i;
371 // Record if the generic reader index is in "lagged replica DB" mode
372 if ( $laggedReplicaMode ) {
373 $this->laggedReplicaMode = true;
374 }
375 }
376
377 $serverName = $this->getServerName( $i );
378 $this->connLogger->debug( __METHOD__ . ": using server $serverName for group '$group'" );
379
380 return $i;
381 }
382
383 /**
384 * @param array $loads List of server weights
385 * @param string|bool $domain
386 * @return array (reader index, lagged replica mode) or false on failure
387 */
388 private function pickReaderIndex( array $loads, $domain = false ) {
389 if ( !count( $loads ) ) {
390 throw new InvalidArgumentException( "Empty server array given to LoadBalancer" );
391 }
392
393 /** @var int|bool $i Index of selected server */
394 $i = false;
395 /** @var bool $laggedReplicaMode Whether server is considered lagged */
396 $laggedReplicaMode = false;
397
398 // Quickly look through the available servers for a server that meets criteria...
399 $currentLoads = $loads;
400 while ( count( $currentLoads ) ) {
401 if ( $this->mAllowLagged || $laggedReplicaMode ) {
402 $i = ArrayUtils::pickRandom( $currentLoads );
403 } else {
404 $i = false;
405 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
406 // ChronologyProtecter sets mWaitForPos for session consistency.
407 // This triggers doWait() after connect, so it's especially good to
408 // avoid lagged servers so as to avoid excessive delay in that method.
409 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
410 // Aim for <= 1 second of waiting (being too picky can backfire)
411 $i = $this->getRandomNonLagged( $currentLoads, $domain, $ago + 1 );
412 }
413 if ( $i === false ) {
414 // Any server with less lag than it's 'max lag' param is preferable
415 $i = $this->getRandomNonLagged( $currentLoads, $domain );
416 }
417 if ( $i === false && count( $currentLoads ) != 0 ) {
418 // All replica DBs lagged. Switch to read-only mode
419 $this->replLogger->error( "All replica DBs lagged. Switch to read-only mode" );
420 $i = ArrayUtils::pickRandom( $currentLoads );
421 $laggedReplicaMode = true;
422 }
423 }
424
425 if ( $i === false ) {
426 // pickRandom() returned false.
427 // This is permanent and means the configuration or the load monitor
428 // wants us to return false.
429 $this->connLogger->debug( __METHOD__ . ": pickRandom() returned false" );
430
431 return [ false, false ];
432 }
433
434 $serverName = $this->getServerName( $i );
435 $this->connLogger->debug( __METHOD__ . ": Using reader #$i: $serverName..." );
436
437 $conn = $this->openConnection( $i, $domain );
438 if ( !$conn ) {
439 $this->connLogger->warning( __METHOD__ . ": Failed connecting to $i/$domain" );
440 unset( $currentLoads[$i] ); // avoid this server next iteration
441 $i = false;
442 continue;
443 }
444
445 // Decrement reference counter, we are finished with this connection.
446 // It will be incremented for the caller later.
447 if ( $domain !== false ) {
448 $this->reuseConnection( $conn );
449 }
450
451 // Return this server
452 break;
453 }
454
455 // If all servers were down, quit now
456 if ( !count( $currentLoads ) ) {
457 $this->connLogger->error( "All servers down" );
458 }
459
460 return [ $i, $laggedReplicaMode ];
461 }
462
463 public function waitFor( $pos ) {
464 $oldPos = $this->mWaitForPos;
465 try {
466 $this->mWaitForPos = $pos;
467 // If a generic reader connection was already established, then wait now
468 $i = $this->mReadIndex;
469 if ( $i > 0 ) {
470 if ( !$this->doWait( $i ) ) {
471 $this->laggedReplicaMode = true;
472 }
473 }
474 } finally {
475 // Restore the older position if it was higher since this is used for lag-protection
476 $this->setWaitForPositionIfHigher( $oldPos );
477 }
478 }
479
480 public function waitForOne( $pos, $timeout = null ) {
481 $oldPos = $this->mWaitForPos;
482 try {
483 $this->mWaitForPos = $pos;
484
485 $i = $this->mReadIndex;
486 if ( $i <= 0 ) {
487 // Pick a generic replica DB if there isn't one yet
488 $readLoads = $this->mLoads;
489 unset( $readLoads[$this->getWriterIndex()] ); // replica DBs only
490 $readLoads = array_filter( $readLoads ); // with non-zero load
491 $i = ArrayUtils::pickRandom( $readLoads );
492 }
493
494 if ( $i > 0 ) {
495 $ok = $this->doWait( $i, true, $timeout );
496 } else {
497 $ok = true; // no applicable loads
498 }
499 } finally {
500 # Restore the old position, as this is not used for lag-protection but for throttling
501 $this->mWaitForPos = $oldPos;
502 }
503
504 return $ok;
505 }
506
507 public function waitForAll( $pos, $timeout = null ) {
508 $oldPos = $this->mWaitForPos;
509 try {
510 $this->mWaitForPos = $pos;
511 $serverCount = count( $this->mServers );
512
513 $ok = true;
514 for ( $i = 1; $i < $serverCount; $i++ ) {
515 if ( $this->mLoads[$i] > 0 ) {
516 $ok = $this->doWait( $i, true, $timeout ) && $ok;
517 }
518 }
519 } finally {
520 # Restore the old position, as this is not used for lag-protection but for throttling
521 $this->mWaitForPos = $oldPos;
522 }
523
524 return $ok;
525 }
526
527 /**
528 * @param DBMasterPos|bool $pos
529 */
530 private function setWaitForPositionIfHigher( $pos ) {
531 if ( !$pos ) {
532 return;
533 }
534
535 if ( !$this->mWaitForPos || $pos->hasReached( $this->mWaitForPos ) ) {
536 $this->mWaitForPos = $pos;
537 }
538 }
539
540 /**
541 * @param int $i
542 * @return IDatabase|bool
543 */
544 public function getAnyOpenConnection( $i ) {
545 foreach ( $this->mConns as $connsByServer ) {
546 if ( !empty( $connsByServer[$i] ) ) {
547 /** @var IDatabase[] $serverConns */
548 $serverConns = $connsByServer[$i];
549
550 return reset( $serverConns );
551 }
552 }
553
554 return false;
555 }
556
557 /**
558 * Wait for a given replica DB to catch up to the master pos stored in $this
559 * @param int $index Server index
560 * @param bool $open Check the server even if a new connection has to be made
561 * @param int $timeout Max seconds to wait; default is mWaitTimeout
562 * @return bool
563 */
564 protected function doWait( $index, $open = false, $timeout = null ) {
565 $close = false; // close the connection afterwards
566
567 // Check if we already know that the DB has reached this point
568 $server = $this->getServerName( $index );
569 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server, 'v1' );
570 /** @var DBMasterPos $knownReachedPos */
571 $knownReachedPos = $this->srvCache->get( $key );
572 if (
573 $knownReachedPos instanceof DBMasterPos &&
574 $knownReachedPos->hasReached( $this->mWaitForPos )
575 ) {
576 $this->replLogger->debug( __METHOD__ .
577 ': replica DB {dbserver} known to be caught up (pos >= $knownReachedPos).',
578 [ 'dbserver' => $server ] );
579 return true;
580 }
581
582 // Find a connection to wait on, creating one if needed and allowed
583 $conn = $this->getAnyOpenConnection( $index );
584 if ( !$conn ) {
585 if ( !$open ) {
586 $this->replLogger->debug( __METHOD__ . ': no connection open for {dbserver}',
587 [ 'dbserver' => $server ] );
588
589 return false;
590 } else {
591 $conn = $this->openConnection( $index, self::DOMAIN_ANY );
592 if ( !$conn ) {
593 $this->replLogger->warning( __METHOD__ . ': failed to connect to {dbserver}',
594 [ 'dbserver' => $server ] );
595
596 return false;
597 }
598 // Avoid connection spam in waitForAll() when connections
599 // are made just for the sake of doing this lag check.
600 $close = true;
601 }
602 }
603
604 $this->replLogger->info( __METHOD__ . ': Waiting for replica DB {dbserver} to catch up...',
605 [ 'dbserver' => $server ] );
606 $timeout = $timeout ?: $this->mWaitTimeout;
607 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
608
609 if ( $result == -1 || is_null( $result ) ) {
610 // Timed out waiting for replica DB, use master instead
611 $this->replLogger->warning(
612 __METHOD__ . ': Timed out waiting on {host} pos {pos}',
613 [ 'host' => $server, 'pos' => $this->mWaitForPos ]
614 );
615 $ok = false;
616 } else {
617 $this->replLogger->info( __METHOD__ . ": Done" );
618 $ok = true;
619 // Remember that the DB reached this point
620 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
621 }
622
623 if ( $close ) {
624 $this->closeConnection( $conn );
625 }
626
627 return $ok;
628 }
629
630 public function getConnection( $i, $groups = [], $domain = false, $flags = 0 ) {
631 if ( $i === null || $i === false ) {
632 throw new InvalidArgumentException( 'Attempt to call ' . __METHOD__ .
633 ' with invalid server index' );
634 }
635
636 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
637 $domain = false; // local connection requested
638 }
639
640 $groups = ( $groups === false || $groups === [] )
641 ? [ false ] // check one "group": the generic pool
642 : (array)$groups;
643
644 $masterOnly = ( $i == self::DB_MASTER || $i == $this->getWriterIndex() );
645 $oldConnsOpened = $this->connsOpened; // connections open now
646
647 if ( $i == self::DB_MASTER ) {
648 $i = $this->getWriterIndex();
649 } else {
650 # Try to find an available server in any the query groups (in order)
651 foreach ( $groups as $group ) {
652 $groupIndex = $this->getReaderIndex( $group, $domain );
653 if ( $groupIndex !== false ) {
654 $i = $groupIndex;
655 break;
656 }
657 }
658 }
659
660 # Operation-based index
661 if ( $i == self::DB_REPLICA ) {
662 $this->mLastError = 'Unknown error'; // reset error string
663 # Try the general server pool if $groups are unavailable.
664 $i = ( $groups === [ false ] )
665 ? false // don't bother with this if that is what was tried above
666 : $this->getReaderIndex( false, $domain );
667 # Couldn't find a working server in getReaderIndex()?
668 if ( $i === false ) {
669 $this->mLastError = 'No working replica DB server: ' . $this->mLastError;
670 // Throw an exception
671 $this->reportConnectionError();
672 return null; // not reached
673 }
674 }
675
676 # Now we have an explicit index into the servers array
677 $conn = $this->openConnection( $i, $domain, $flags );
678 if ( !$conn ) {
679 // Throw an exception
680 $this->reportConnectionError();
681 return null; // not reached
682 }
683
684 # Profile any new connections that happen
685 if ( $this->connsOpened > $oldConnsOpened ) {
686 $host = $conn->getServer();
687 $dbname = $conn->getDBname();
688 $this->trxProfiler->recordConnection( $host, $dbname, $masterOnly );
689 }
690
691 if ( $masterOnly ) {
692 # Make master-requested DB handles inherit any read-only mode setting
693 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $domain, $conn ) );
694 }
695
696 return $conn;
697 }
698
699 public function reuseConnection( $conn ) {
700 $serverIndex = $conn->getLBInfo( 'serverIndex' );
701 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
702 if ( $serverIndex === null || $refCount === null ) {
703 /**
704 * This can happen in code like:
705 * foreach ( $dbs as $db ) {
706 * $conn = $lb->getConnection( $lb::DB_REPLICA, [], $db );
707 * ...
708 * $lb->reuseConnection( $conn );
709 * }
710 * When a connection to the local DB is opened in this way, reuseConnection()
711 * should be ignored
712 */
713 return;
714 } elseif ( $conn instanceof DBConnRef ) {
715 // DBConnRef already handles calling reuseConnection() and only passes the live
716 // Database instance to this method. Any caller passing in a DBConnRef is broken.
717 $this->connLogger->error( __METHOD__ . ": got DBConnRef instance.\n" .
718 ( new RuntimeException() )->getTraceAsString() );
719
720 return;
721 }
722
723 if ( $this->disabled ) {
724 return; // DBConnRef handle probably survived longer than the LoadBalancer
725 }
726
727 if ( $conn->getLBInfo( 'autoCommitOnly' ) ) {
728 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
729 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
730 } else {
731 $connFreeKey = self::KEY_FOREIGN_FREE;
732 $connInUseKey = self::KEY_FOREIGN_INUSE;
733 }
734
735 $domain = $conn->getDomainID();
736 if ( !isset( $this->mConns[$connInUseKey][$serverIndex][$domain] ) ) {
737 throw new InvalidArgumentException( __METHOD__ .
738 ": connection $serverIndex/$domain not found; it may have already been freed." );
739 } elseif ( $this->mConns[$connInUseKey][$serverIndex][$domain] !== $conn ) {
740 throw new InvalidArgumentException( __METHOD__ .
741 ": connection $serverIndex/$domain mismatched; it may have already been freed." );
742 }
743
744 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
745 if ( $refCount <= 0 ) {
746 $this->mConns[$connFreeKey][$serverIndex][$domain] = $conn;
747 unset( $this->mConns[$connInUseKey][$serverIndex][$domain] );
748 if ( !$this->mConns[$connInUseKey][$serverIndex] ) {
749 unset( $this->mConns[$connInUseKey][$serverIndex] ); // clean up
750 }
751 $this->connLogger->debug( __METHOD__ . ": freed connection $serverIndex/$domain" );
752 } else {
753 $this->connLogger->debug( __METHOD__ .
754 ": reference count for $serverIndex/$domain reduced to $refCount" );
755 }
756 }
757
758 public function getConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
759 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
760
761 return new DBConnRef( $this, $this->getConnection( $db, $groups, $domain, $flags ) );
762 }
763
764 public function getLazyConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
765 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
766
767 return new DBConnRef( $this, [ $db, $groups, $domain, $flags ] );
768 }
769
770 public function getMaintenanceConnectionRef( $db, $groups = [], $domain = false, $flags = 0 ) {
771 $domain = ( $domain !== false ) ? $domain : $this->localDomain;
772
773 return new MaintainableDBConnRef(
774 $this, $this->getConnection( $db, $groups, $domain, $flags ) );
775 }
776
777 public function openConnection( $i, $domain = false, $flags = 0 ) {
778 if ( $this->localDomain->equals( $domain ) || $domain === $this->localDomainIdAlias ) {
779 $domain = false; // local connection requested
780 }
781
782 if ( !$this->chronProtInitialized && $this->chronProt ) {
783 $this->connLogger->debug( __METHOD__ . ': calling initLB() before first connection.' );
784 // Load CP positions before connecting so that doWait() triggers later if needed
785 $this->chronProtInitialized = true;
786 $this->chronProt->initLB( $this );
787 }
788
789 // Check if an auto-commit connection is being requested. If so, it will not reuse the
790 // main set of DB connections but rather its own pool since:
791 // a) those are usually set to implicitly use transaction rounds via DBO_TRX
792 // b) those must support the use of explicit transaction rounds via beginMasterChanges()
793 $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
794
795 if ( $domain !== false ) {
796 // Connection is to a foreign domain
797 $conn = $this->openForeignConnection( $i, $domain, $flags );
798 } else {
799 // Connection is to the local domain
800 $connKey = $autoCommit ? self::KEY_LOCAL_NOROUND : self::KEY_LOCAL;
801 if ( isset( $this->mConns[$connKey][$i][0] ) ) {
802 $conn = $this->mConns[$connKey][$i][0];
803 } else {
804 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
805 throw new InvalidArgumentException( "No server with index '$i'." );
806 }
807 // Open a new connection
808 $server = $this->mServers[$i];
809 $server['serverIndex'] = $i;
810 $server['autoCommitOnly'] = $autoCommit;
811 $conn = $this->reallyOpenConnection( $server, false );
812 $host = $this->getServerName( $i );
813 if ( $conn->isOpen() ) {
814 $this->connLogger->debug( "Connected to database $i at '$host'." );
815 $this->mConns[$connKey][$i][0] = $conn;
816 } else {
817 $this->connLogger->warning( "Failed to connect to database $i at '$host'." );
818 $this->errorConnection = $conn;
819 $conn = false;
820 }
821 }
822 }
823
824 if ( $conn instanceof IDatabase && !$conn->isOpen() ) {
825 // Connection was made but later unrecoverably lost for some reason.
826 // Do not return a handle that will just throw exceptions on use,
827 // but let the calling code (e.g. getReaderIndex) try another server.
828 // See DatabaseMyslBase::ping() for how this can happen.
829 $this->errorConnection = $conn;
830 $conn = false;
831 }
832
833 if ( $autoCommit && $conn instanceof IDatabase ) {
834 $conn->clearFlag( $conn::DBO_TRX ); // auto-commit mode
835 }
836
837 return $conn;
838 }
839
840 /**
841 * Open a connection to a foreign DB, or return one if it is already open.
842 *
843 * Increments a reference count on the returned connection which locks the
844 * connection to the requested domain. This reference count can be
845 * decremented by calling reuseConnection().
846 *
847 * If a connection is open to the appropriate server already, but with the wrong
848 * database, it will be switched to the right database and returned, as long as
849 * it has been freed first with reuseConnection().
850 *
851 * On error, returns false, and the connection which caused the
852 * error will be available via $this->errorConnection.
853 *
854 * @note If disable() was called on this LoadBalancer, this method will throw a DBAccessError.
855 *
856 * @param int $i Server index
857 * @param string $domain Domain ID to open
858 * @param int $flags Class CONN_* constant bitfield
859 * @return Database
860 */
861 private function openForeignConnection( $i, $domain, $flags = 0 ) {
862 $domainInstance = DatabaseDomain::newFromId( $domain );
863 $dbName = $domainInstance->getDatabase();
864 $prefix = $domainInstance->getTablePrefix();
865 $autoCommit = ( ( $flags & self::CONN_TRX_AUTO ) == self::CONN_TRX_AUTO );
866
867 if ( $autoCommit ) {
868 $connFreeKey = self::KEY_FOREIGN_FREE_NOROUND;
869 $connInUseKey = self::KEY_FOREIGN_INUSE_NOROUND;
870 } else {
871 $connFreeKey = self::KEY_FOREIGN_FREE;
872 $connInUseKey = self::KEY_FOREIGN_INUSE;
873 }
874
875 if ( isset( $this->mConns[$connInUseKey][$i][$domain] ) ) {
876 // Reuse an in-use connection for the same domain
877 $conn = $this->mConns[$connInUseKey][$i][$domain];
878 $this->connLogger->debug( __METHOD__ . ": reusing connection $i/$domain" );
879 } elseif ( isset( $this->mConns[$connFreeKey][$i][$domain] ) ) {
880 // Reuse a free connection for the same domain
881 $conn = $this->mConns[$connFreeKey][$i][$domain];
882 unset( $this->mConns[$connFreeKey][$i][$domain] );
883 $this->mConns[$connInUseKey][$i][$domain] = $conn;
884 $this->connLogger->debug( __METHOD__ . ": reusing free connection $i/$domain" );
885 } elseif ( !empty( $this->mConns[$connFreeKey][$i] ) ) {
886 // Reuse a free connection from another domain
887 $conn = reset( $this->mConns[$connFreeKey][$i] );
888 $oldDomain = key( $this->mConns[$connFreeKey][$i] );
889 // The empty string as a DB name means "don't care".
890 // DatabaseMysqlBase::open() already handle this on connection.
891 if ( strlen( $dbName ) && !$conn->selectDB( $dbName ) ) {
892 $this->mLastError = "Error selecting database '$dbName' on server " .
893 $conn->getServer() . " from client host {$this->host}";
894 $this->errorConnection = $conn;
895 $conn = false;
896 } else {
897 $conn->tablePrefix( $prefix );
898 unset( $this->mConns[$connFreeKey][$i][$oldDomain] );
899 $this->mConns[$connInUseKey][$i][$domain] = $conn;
900 $this->connLogger->debug( __METHOD__ .
901 ": reusing free connection from $oldDomain for $domain" );
902 }
903 } else {
904 if ( !isset( $this->mServers[$i] ) || !is_array( $this->mServers[$i] ) ) {
905 throw new InvalidArgumentException( "No server with index '$i'." );
906 }
907 // Open a new connection
908 $server = $this->mServers[$i];
909 $server['serverIndex'] = $i;
910 $server['foreignPoolRefCount'] = 0;
911 $server['foreign'] = true;
912 $server['autoCommitOnly'] = $autoCommit;
913 $conn = $this->reallyOpenConnection( $server, $dbName );
914 if ( !$conn->isOpen() ) {
915 $this->connLogger->warning( __METHOD__ . ": connection error for $i/$domain" );
916 $this->errorConnection = $conn;
917 $conn = false;
918 } else {
919 $conn->tablePrefix( $prefix );
920 $this->mConns[$connInUseKey][$i][$domain] = $conn;
921 $this->connLogger->debug( __METHOD__ . ": opened new connection for $i/$domain" );
922 }
923 }
924
925 // Increment reference count
926 if ( $conn instanceof IDatabase ) {
927 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
928 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
929 }
930
931 return $conn;
932 }
933
934 /**
935 * Test if the specified index represents an open connection
936 *
937 * @param int $index Server index
938 * @access private
939 * @return bool
940 */
941 private function isOpen( $index ) {
942 if ( !is_integer( $index ) ) {
943 return false;
944 }
945
946 return (bool)$this->getAnyOpenConnection( $index );
947 }
948
949 /**
950 * Really opens a connection. Uncached.
951 * Returns a Database object whether or not the connection was successful.
952 * @access private
953 *
954 * @param array $server
955 * @param string|bool $dbNameOverride Use "" to not select any database
956 * @return Database
957 * @throws DBAccessError
958 * @throws InvalidArgumentException
959 */
960 protected function reallyOpenConnection( array $server, $dbNameOverride = false ) {
961 if ( $this->disabled ) {
962 throw new DBAccessError();
963 }
964
965 if ( $dbNameOverride !== false ) {
966 $server['dbname'] = $dbNameOverride;
967 }
968
969 // Let the handle know what the cluster master is (e.g. "db1052")
970 $masterName = $this->getServerName( $this->getWriterIndex() );
971 $server['clusterMasterHost'] = $masterName;
972
973 // Log when many connection are made on requests
974 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
975 $this->perfLogger->warning( __METHOD__ . ": " .
976 "{$this->connsOpened}+ connections made (master=$masterName)" );
977 }
978
979 $server['srvCache'] = $this->srvCache;
980 // Set loggers and profilers
981 $server['connLogger'] = $this->connLogger;
982 $server['queryLogger'] = $this->queryLogger;
983 $server['errorLogger'] = $this->errorLogger;
984 $server['profiler'] = $this->profiler;
985 $server['trxProfiler'] = $this->trxProfiler;
986 // Use the same agent and PHP mode for all DB handles
987 $server['cliMode'] = $this->cliMode;
988 $server['agent'] = $this->agent;
989 // Use DBO_DEFAULT flags by default for LoadBalancer managed databases. Assume that the
990 // application calls LoadBalancer::commitMasterChanges() before the PHP script completes.
991 $server['flags'] = isset( $server['flags'] ) ? $server['flags'] : IDatabase::DBO_DEFAULT;
992
993 // Create a live connection object
994 try {
995 $db = Database::factory( $server['type'], $server );
996 } catch ( DBConnectionError $e ) {
997 // FIXME: This is probably the ugliest thing I have ever done to
998 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
999 $db = $e->db;
1000 }
1001
1002 $db->setLBInfo( $server );
1003 $db->setLazyMasterHandle(
1004 $this->getLazyConnectionRef( self::DB_MASTER, [], $db->getDomainID() )
1005 );
1006 $db->setTableAliases( $this->tableAliases );
1007
1008 if ( $server['serverIndex'] === $this->getWriterIndex() ) {
1009 if ( $this->trxRoundId !== false ) {
1010 $this->applyTransactionRoundFlags( $db );
1011 }
1012 foreach ( $this->trxRecurringCallbacks as $name => $callback ) {
1013 $db->setTransactionListener( $name, $callback );
1014 }
1015 }
1016
1017 return $db;
1018 }
1019
1020 /**
1021 * @throws DBConnectionError
1022 */
1023 private function reportConnectionError() {
1024 $conn = $this->errorConnection; // the connection which caused the error
1025 $context = [
1026 'method' => __METHOD__,
1027 'last_error' => $this->mLastError,
1028 ];
1029
1030 if ( $conn instanceof IDatabase ) {
1031 $context['db_server'] = $conn->getServer();
1032 $this->connLogger->warning(
1033 "Connection error: {last_error} ({db_server})",
1034 $context
1035 );
1036
1037 // throws DBConnectionError
1038 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
1039 } else {
1040 // No last connection, probably due to all servers being too busy
1041 $this->connLogger->error(
1042 "LB failure with no last connection. Connection error: {last_error}",
1043 $context
1044 );
1045
1046 // If all servers were busy, mLastError will contain something sensible
1047 throw new DBConnectionError( null, $this->mLastError );
1048 }
1049 }
1050
1051 public function getWriterIndex() {
1052 return 0;
1053 }
1054
1055 public function haveIndex( $i ) {
1056 return array_key_exists( $i, $this->mServers );
1057 }
1058
1059 public function isNonZeroLoad( $i ) {
1060 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
1061 }
1062
1063 public function getServerCount() {
1064 return count( $this->mServers );
1065 }
1066
1067 public function getServerName( $i ) {
1068 if ( isset( $this->mServers[$i]['hostName'] ) ) {
1069 $name = $this->mServers[$i]['hostName'];
1070 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
1071 $name = $this->mServers[$i]['host'];
1072 } else {
1073 $name = '';
1074 }
1075
1076 return ( $name != '' ) ? $name : 'localhost';
1077 }
1078
1079 public function getServerType( $i ) {
1080 return isset( $this->mServers[$i]['type'] ) ? $this->mServers[$i]['type'] : 'unknown';
1081 }
1082
1083 /**
1084 * @deprecated Since 1.30, no alternative
1085 */
1086 public function getServerInfo( $i ) {
1087 wfDeprecated( __METHOD__, '1.30' );
1088 if ( isset( $this->mServers[$i] ) ) {
1089 return $this->mServers[$i];
1090 } else {
1091 return false;
1092 }
1093 }
1094
1095 /**
1096 * @deprecated Since 1.30, construct new object
1097 */
1098 public function setServerInfo( $i, array $serverInfo ) {
1099 wfDeprecated( __METHOD__, '1.30' );
1100 $this->mServers[$i] = $serverInfo;
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' );