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