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