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