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