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