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