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