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