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