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