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