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