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