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