Merge "Documentation: Remove paragraph about not creating a 2nd WebRequest"
[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
44 /** @var array LBFactory information */
45 private $mParentInfo;
46 /** @var string The LoadMonitor subclass name */
47 private $mLoadMonitorClass;
48 /** @var LoadMonitor */
49 private $mLoadMonitor;
50 /** @var BagOStuff */
51 private $srvCache;
52
53 /** @var bool|DatabaseBase Database connection that caused a problem */
54 private $mErrorConnection;
55 /** @var integer The generic (not query grouped) slave index (of $mServers) */
56 private $mReadIndex;
57 /** @var bool|DBMasterPos False if not set */
58 private $mWaitForPos;
59 /** @var bool Whether the generic reader fell back to a lagged slave */
60 private $laggedSlaveMode = false;
61 /** @var bool Whether the generic reader fell back to a lagged slave */
62 private $slavesDownMode = false;
63 /** @var string The last DB selection or connection error */
64 private $mLastError = 'Unknown error';
65 /** @var string|bool Reason the LB is read-only or false if not */
66 private $readOnlyReason = false;
67 /** @var integer Total connections opened */
68 private $connsOpened = 0;
69
70 /** @var integer Warn when this many connection are held */
71 const CONN_HELD_WARN_THRESHOLD = 10;
72 /** @var integer Default 'max lag' when unspecified */
73 const MAX_LAG = 10;
74 /** @var integer Max time to wait for a slave to catch up (e.g. ChronologyProtector) */
75 const POS_WAIT_TIMEOUT = 10;
76
77 /**
78 * @param array $params Array with keys:
79 * - servers : Required. Array of server info structures.
80 * - loadMonitor : Name of a class used to fetch server lag and load.
81 * - readOnlyReason : Reason the master DB is read-only if so [optional]
82 * @throws MWException
83 */
84 public function __construct( array $params ) {
85 if ( !isset( $params['servers'] ) ) {
86 throw new MWException( __CLASS__ . ': missing servers parameter' );
87 }
88 $this->mServers = $params['servers'];
89 $this->mWaitTimeout = self::POS_WAIT_TIMEOUT;
90
91 $this->mReadIndex = -1;
92 $this->mWriteIndex = -1;
93 $this->mConns = array(
94 'local' => array(),
95 'foreignUsed' => array(),
96 'foreignFree' => array() );
97 $this->mLoads = array();
98 $this->mWaitForPos = false;
99 $this->mErrorConnection = false;
100 $this->mAllowLagged = false;
101
102 if ( isset( $params['readOnlyReason'] ) && is_string( $params['readOnlyReason'] ) ) {
103 $this->readOnlyReason = $params['readOnlyReason'];
104 }
105
106 if ( isset( $params['loadMonitor'] ) ) {
107 $this->mLoadMonitorClass = $params['loadMonitor'];
108 } else {
109 $master = reset( $params['servers'] );
110 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
111 $this->mLoadMonitorClass = 'LoadMonitorMySQL';
112 } else {
113 $this->mLoadMonitorClass = 'LoadMonitorNull';
114 }
115 }
116
117 foreach ( $params['servers'] as $i => $server ) {
118 $this->mLoads[$i] = $server['load'];
119 if ( isset( $server['groupLoads'] ) ) {
120 foreach ( $server['groupLoads'] as $group => $ratio ) {
121 if ( !isset( $this->mGroupLoads[$group] ) ) {
122 $this->mGroupLoads[$group] = array();
123 }
124 $this->mGroupLoads[$group][$i] = $ratio;
125 }
126 }
127 }
128
129 $this->srvCache = ObjectCache::getLocalServerInstance();
130 }
131
132 /**
133 * Get a LoadMonitor instance
134 *
135 * @return LoadMonitor
136 */
137 private function getLoadMonitor() {
138 if ( !isset( $this->mLoadMonitor ) ) {
139 $class = $this->mLoadMonitorClass;
140 $this->mLoadMonitor = new $class( $this );
141 }
142
143 return $this->mLoadMonitor;
144 }
145
146 /**
147 * Get or set arbitrary data used by the parent object, usually an LBFactory
148 * @param mixed $x
149 * @return mixed
150 */
151 public function parentInfo( $x = null ) {
152 return wfSetVar( $this->mParentInfo, $x );
153 }
154
155 /**
156 * Given an array of non-normalised probabilities, this function will select
157 * an element and return the appropriate key
158 *
159 * @deprecated since 1.21, use ArrayUtils::pickRandom()
160 *
161 * @param array $weights
162 * @return bool|int|string
163 */
164 public function pickRandom( array $weights ) {
165 return ArrayUtils::pickRandom( $weights );
166 }
167
168 /**
169 * @param array $loads
170 * @param bool|string $wiki Wiki to get non-lagged for
171 * @param int $maxLag Restrict the maximum allowed lag to this many seconds
172 * @return bool|int|string
173 */
174 private function getRandomNonLagged( array $loads, $wiki = false, $maxLag = self::MAX_LAG ) {
175 $lags = $this->getLagTimes( $wiki );
176
177 # Unset excessively lagged servers
178 foreach ( $lags as $i => $lag ) {
179 if ( $i != 0 ) {
180 $maxServerLag = $maxLag;
181 if ( isset( $this->mServers[$i]['max lag'] ) ) {
182 $maxServerLag = min( $maxServerLag, $this->mServers[$i]['max lag'] );
183 }
184 if ( $lag === false ) {
185 wfDebugLog( 'replication', "Server #$i is not replicating" );
186 unset( $loads[$i] );
187 } elseif ( $lag > $maxServerLag ) {
188 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)" );
189 unset( $loads[$i] );
190 }
191 }
192 }
193
194 # Find out if all the slaves with non-zero load are lagged
195 $sum = 0;
196 foreach ( $loads as $load ) {
197 $sum += $load;
198 }
199 if ( $sum == 0 ) {
200 # No appropriate DB servers except maybe the master and some slaves with zero load
201 # Do NOT use the master
202 # Instead, this function will return false, triggering read-only mode,
203 # and a lagged slave will be used instead.
204 return false;
205 }
206
207 if ( count( $loads ) == 0 ) {
208 return false;
209 }
210
211 # Return a random representative of the remainder
212 return ArrayUtils::pickRandom( $loads );
213 }
214
215 /**
216 * Get the index of the reader connection, which may be a slave
217 * This takes into account load ratios and lag times. It should
218 * always return a consistent index during a given invocation
219 *
220 * Side effect: opens connections to databases
221 * @param string|bool $group Query group, or false for the generic reader
222 * @param string|bool $wiki Wiki ID, or false for the current wiki
223 * @throws MWException
224 * @return bool|int|string
225 */
226 public function getReaderIndex( $group = false, $wiki = false ) {
227 global $wgDBtype;
228
229 # @todo FIXME: For now, only go through all this for mysql databases
230 if ( $wgDBtype != 'mysql' ) {
231 return $this->getWriterIndex();
232 }
233
234 if ( count( $this->mServers ) == 1 ) {
235 # Skip the load balancing if there's only one server
236 return 0;
237 } elseif ( $group === false && $this->mReadIndex >= 0 ) {
238 # Shortcut if generic reader exists already
239 return $this->mReadIndex;
240 }
241
242 # Find the relevant load array
243 if ( $group !== false ) {
244 if ( isset( $this->mGroupLoads[$group] ) ) {
245 $nonErrorLoads = $this->mGroupLoads[$group];
246 } else {
247 # No loads for this group, return false and the caller can use some other group
248 wfDebugLog( 'connect', __METHOD__ . ": no loads for group $group\n" );
249
250 return false;
251 }
252 } else {
253 $nonErrorLoads = $this->mLoads;
254 }
255
256 if ( !count( $nonErrorLoads ) ) {
257 throw new MWException( "Empty server array given to LoadBalancer" );
258 }
259
260 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
261 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
262
263 $laggedSlaveMode = false;
264
265 # No server found yet
266 $i = false;
267 $conn = false;
268 # First try quickly looking through the available servers for a server that
269 # meets our criteria
270 $currentLoads = $nonErrorLoads;
271 while ( count( $currentLoads ) ) {
272 if ( $this->mAllowLagged || $laggedSlaveMode ) {
273 $i = ArrayUtils::pickRandom( $currentLoads );
274 } else {
275 $i = false;
276 if ( $this->mWaitForPos && $this->mWaitForPos->asOfTime() ) {
277 # ChronologyProtecter causes mWaitForPos to be set via sessions.
278 # This triggers doWait() after connect, so it's especially good to
279 # avoid lagged servers so as to avoid just blocking in that method.
280 $ago = microtime( true ) - $this->mWaitForPos->asOfTime();
281 # Aim for <= 1 second of waiting (being too picky can backfire)
282 $i = $this->getRandomNonLagged( $currentLoads, $wiki, $ago + 1 );
283 }
284 if ( $i === false ) {
285 # Any server with less lag than it's 'max lag' param is preferable
286 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
287 }
288 if ( $i === false && count( $currentLoads ) != 0 ) {
289 # All slaves lagged. Switch to read-only mode
290 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode" );
291 $i = ArrayUtils::pickRandom( $currentLoads );
292 $laggedSlaveMode = true;
293 }
294 }
295
296 if ( $i === false ) {
297 # pickRandom() returned false
298 # This is permanent and means the configuration or the load monitor
299 # wants us to return false.
300 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false" );
301
302 return false;
303 }
304
305 $serverName = $this->getServerName( $i );
306 wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: $serverName..." );
307
308 $conn = $this->openConnection( $i, $wiki );
309 if ( !$conn ) {
310 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki" );
311 unset( $nonErrorLoads[$i] );
312 unset( $currentLoads[$i] );
313 $i = false;
314 continue;
315 }
316
317 // Decrement reference counter, we are finished with this connection.
318 // It will be incremented for the caller later.
319 if ( $wiki !== false ) {
320 $this->reuseConnection( $conn );
321 }
322
323 # Return this server
324 break;
325 }
326
327 # If all servers were down, quit now
328 if ( !count( $nonErrorLoads ) ) {
329 wfDebugLog( 'connect', "All servers down" );
330 }
331
332 if ( $i !== false ) {
333 # Slave connection successful
334 # Wait for the session master pos for a short time
335 if ( $this->mWaitForPos && $i > 0 ) {
336 if ( !$this->doWait( $i ) ) {
337 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
338 }
339 }
340 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $group === false ) {
341 $this->mReadIndex = $i;
342 # Record if the generic reader index is in "lagged slave" mode
343 if ( $laggedSlaveMode ) {
344 $this->laggedSlaveMode = true;
345 }
346 }
347 $serverName = $this->getServerName( $i );
348 wfDebugLog( 'connect', __METHOD__ .
349 ": using server $serverName for group '$group'\n" );
350 }
351
352 return $i;
353 }
354
355 /**
356 * Set the master wait position
357 * If a DB_SLAVE connection has been opened already, waits
358 * Otherwise sets a variable telling it to wait if such a connection is opened
359 * @param DBMasterPos $pos
360 */
361 public function waitFor( $pos ) {
362 $this->mWaitForPos = $pos;
363 $i = $this->mReadIndex;
364
365 if ( $i > 0 ) {
366 if ( !$this->doWait( $i ) ) {
367 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
368 $this->laggedSlaveMode = true;
369 }
370 }
371 }
372
373 /**
374 * Set the master wait position and wait for a "generic" slave to catch up to it
375 *
376 * This can be used a faster proxy for waitForAll()
377 *
378 * @param DBMasterPos $pos
379 * @param int $timeout Max seconds to wait; default is mWaitTimeout
380 * @return bool Success (able to connect and no timeouts reached)
381 * @since 1.26
382 */
383 public function waitForOne( $pos, $timeout = null ) {
384 $this->mWaitForPos = $pos;
385
386 $i = $this->mReadIndex;
387 if ( $i <= 0 ) {
388 // Pick a generic slave if there isn't one yet
389 $readLoads = $this->mLoads;
390 unset( $readLoads[$this->getWriterIndex()] ); // slaves only
391 $readLoads = array_filter( $readLoads ); // with non-zero load
392 $i = ArrayUtils::pickRandom( $readLoads );
393 }
394
395 if ( $i > 0 ) {
396 $ok = $this->doWait( $i, true, $timeout );
397 } else {
398 $ok = true; // no applicable loads
399 }
400
401 return $ok;
402 }
403
404 /**
405 * Set the master wait position and wait for ALL slaves to catch up to it
406 * @param DBMasterPos $pos
407 * @param int $timeout Max seconds to wait; default is mWaitTimeout
408 * @return bool Success (able to connect and no timeouts reached)
409 */
410 public function waitForAll( $pos, $timeout = null ) {
411 $this->mWaitForPos = $pos;
412 $serverCount = count( $this->mServers );
413
414 $ok = true;
415 for ( $i = 1; $i < $serverCount; $i++ ) {
416 if ( $this->mLoads[$i] > 0 ) {
417 $ok = $this->doWait( $i, true, $timeout ) && $ok;
418 }
419 }
420
421 return $ok;
422 }
423
424 /**
425 * Get any open connection to a given server index, local or foreign
426 * Returns false if there is no connection open
427 *
428 * @param int $i
429 * @return DatabaseBase|bool False on failure
430 */
431 public function getAnyOpenConnection( $i ) {
432 foreach ( $this->mConns as $conns ) {
433 if ( !empty( $conns[$i] ) ) {
434 return reset( $conns[$i] );
435 }
436 }
437
438 return false;
439 }
440
441 /**
442 * Wait for a given slave to catch up to the master pos stored in $this
443 * @param int $index Server index
444 * @param bool $open Check the server even if a new connection has to be made
445 * @param int $timeout Max seconds to wait; default is mWaitTimeout
446 * @return bool
447 */
448 protected function doWait( $index, $open = false, $timeout = null ) {
449 $close = false; // close the connection afterwards
450
451 // Check if we already know that the DB has reached this point
452 $server = $this->getServerName( $index );
453 $key = $this->srvCache->makeGlobalKey( __CLASS__, 'last-known-pos', $server );
454 /** @var DBMasterPos $knownReachedPos */
455 $knownReachedPos = $this->srvCache->get( $key );
456 if ( $knownReachedPos && $knownReachedPos->hasReached( $this->mWaitForPos ) ) {
457 wfDebugLog( 'replication', __METHOD__ .
458 ": slave $server known to be caught up (pos >= $knownReachedPos).\n" );
459 return true;
460 }
461
462 // Find a connection to wait on, creating one if needed and allowed
463 $conn = $this->getAnyOpenConnection( $index );
464 if ( !$conn ) {
465 if ( !$open ) {
466 wfDebugLog( 'replication', __METHOD__ . ": no connection open for $server\n" );
467
468 return false;
469 } else {
470 $conn = $this->openConnection( $index, '' );
471 if ( !$conn ) {
472 wfDebugLog( 'replication', __METHOD__ . ": failed to connect to $server\n" );
473
474 return false;
475 }
476 // Avoid connection spam in waitForAll() when connections
477 // are made just for the sake of doing this lag check.
478 $close = true;
479 }
480 }
481
482 wfDebugLog( 'replication', __METHOD__ . ": Waiting for slave $server to catch up...\n" );
483 $timeout = $timeout ?: $this->mWaitTimeout;
484 $result = $conn->masterPosWait( $this->mWaitForPos, $timeout );
485
486 if ( $result == -1 || is_null( $result ) ) {
487 // Timed out waiting for slave, use master instead
488 $msg = __METHOD__ . ": Timed out waiting on $server pos {$this->mWaitForPos}";
489 wfDebugLog( 'replication', "$msg\n" );
490 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
491 $ok = false;
492 } else {
493 wfDebugLog( 'replication', __METHOD__ . ": Done\n" );
494 $ok = true;
495 // Remember that the DB reached this point
496 $this->srvCache->set( $key, $this->mWaitForPos, BagOStuff::TTL_DAY );
497 }
498
499 if ( $close ) {
500 $this->closeConnection( $conn );
501 }
502
503 return $ok;
504 }
505
506 /**
507 * Get a connection by index
508 * This is the main entry point for this class.
509 *
510 * @param int $i Server index
511 * @param array|string|bool $groups Query group(s), or false for the generic reader
512 * @param string|bool $wiki Wiki ID, or false for the current wiki
513 *
514 * @throws MWException
515 * @return DatabaseBase
516 */
517 public function getConnection( $i, $groups = array(), $wiki = false ) {
518 if ( $i === null || $i === false ) {
519 throw new MWException( 'Attempt to call ' . __METHOD__ .
520 ' with invalid server index' );
521 }
522
523 if ( $wiki === wfWikiID() ) {
524 $wiki = false;
525 }
526
527 $groups = ( $groups === false || $groups === array() )
528 ? array( false ) // check one "group": the generic pool
529 : (array)$groups;
530
531 $masterOnly = ( $i == DB_MASTER || $i == $this->getWriterIndex() );
532 $oldConnsOpened = $this->connsOpened; // connections open now
533
534 if ( $i == DB_MASTER ) {
535 $i = $this->getWriterIndex();
536 } else {
537 # Try to find an available server in any the query groups (in order)
538 foreach ( $groups as $group ) {
539 $groupIndex = $this->getReaderIndex( $group, $wiki );
540 if ( $groupIndex !== false ) {
541 $i = $groupIndex;
542 break;
543 }
544 }
545 }
546
547 # Operation-based index
548 if ( $i == DB_SLAVE ) {
549 $this->mLastError = 'Unknown error'; // reset error string
550 # Try the general server pool if $groups are unavailable.
551 $i = in_array( false, $groups, true )
552 ? false // don't bother with this if that is what was tried above
553 : $this->getReaderIndex( false, $wiki );
554 # Couldn't find a working server in getReaderIndex()?
555 if ( $i === false ) {
556 $this->mLastError = 'No working slave server: ' . $this->mLastError;
557
558 return $this->reportConnectionError();
559 }
560 }
561
562 # Now we have an explicit index into the servers array
563 $conn = $this->openConnection( $i, $wiki );
564 if ( !$conn ) {
565 return $this->reportConnectionError();
566 }
567
568 # Profile any new connections that happen
569 if ( $this->connsOpened > $oldConnsOpened ) {
570 $host = $conn->getServer();
571 $dbname = $conn->getDBname();
572 $trxProf = Profiler::instance()->getTransactionProfiler();
573 $trxProf->recordConnection( $host, $dbname, $masterOnly );
574 }
575
576 if ( $masterOnly ) {
577 # Make master-requested DB handles inherit any read-only mode setting
578 $conn->setLBInfo( 'readOnlyReason', $this->getReadOnlyReason( $wiki ) );
579 }
580
581 return $conn;
582 }
583
584 /**
585 * Mark a foreign connection as being available for reuse under a different
586 * DB name or prefix. This mechanism is reference-counted, and must be called
587 * the same number of times as getConnection() to work.
588 *
589 * @param DatabaseBase $conn
590 * @throws MWException
591 */
592 public function reuseConnection( $conn ) {
593 $serverIndex = $conn->getLBInfo( 'serverIndex' );
594 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
595 if ( $serverIndex === null || $refCount === null ) {
596 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
597 /**
598 * This can happen in code like:
599 * foreach ( $dbs as $db ) {
600 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
601 * ...
602 * $lb->reuseConnection( $conn );
603 * }
604 * When a connection to the local DB is opened in this way, reuseConnection()
605 * should be ignored
606 */
607 return;
608 }
609
610 $dbName = $conn->getDBname();
611 $prefix = $conn->tablePrefix();
612 if ( strval( $prefix ) !== '' ) {
613 $wiki = "$dbName-$prefix";
614 } else {
615 $wiki = $dbName;
616 }
617 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
618 throw new MWException( __METHOD__ . ": connection not found, has " .
619 "the connection been freed already?" );
620 }
621 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
622 if ( $refCount <= 0 ) {
623 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
624 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
625 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
626 } else {
627 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
628 }
629 }
630
631 /**
632 * Get a database connection handle reference
633 *
634 * The handle's methods wrap simply wrap those of a DatabaseBase handle
635 *
636 * @see LoadBalancer::getConnection() for parameter information
637 *
638 * @param int $db
639 * @param array|string|bool $groups Query group(s), or false for the generic reader
640 * @param string|bool $wiki Wiki ID, or false for the current wiki
641 * @return DBConnRef
642 */
643 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
644 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
645 }
646
647 /**
648 * Get a database connection handle reference without connecting yet
649 *
650 * The handle's methods wrap simply wrap those of a DatabaseBase handle
651 *
652 * @see LoadBalancer::getConnection() for parameter information
653 *
654 * @param int $db
655 * @param array|string|bool $groups Query group(s), or false for the generic reader
656 * @param string|bool $wiki Wiki ID, or false for the current wiki
657 * @return DBConnRef
658 */
659 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
660 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
661 }
662
663 /**
664 * Open a connection to the server given by the specified index
665 * Index must be an actual index into the array.
666 * If the server is already open, returns it.
667 *
668 * On error, returns false, and the connection which caused the
669 * error will be available via $this->mErrorConnection.
670 *
671 * @param int $i Server index
672 * @param string|bool $wiki Wiki ID, or false for the current wiki
673 * @return DatabaseBase
674 *
675 * @access private
676 */
677 public function openConnection( $i, $wiki = false ) {
678 if ( $wiki !== false ) {
679 $conn = $this->openForeignConnection( $i, $wiki );
680 } elseif ( isset( $this->mConns['local'][$i][0] ) ) {
681 $conn = $this->mConns['local'][$i][0];
682 } else {
683 $server = $this->mServers[$i];
684 $server['serverIndex'] = $i;
685 $conn = $this->reallyOpenConnection( $server, false );
686 $serverName = $this->getServerName( $i );
687 if ( $conn->isOpen() ) {
688 wfDebugLog( 'connect', "Connected to database $i at $serverName\n" );
689 $this->mConns['local'][$i][0] = $conn;
690 } else {
691 wfDebugLog( 'connect', "Failed to connect to database $i at $serverName\n" );
692 $this->mErrorConnection = $conn;
693 $conn = false;
694 }
695 }
696
697 if ( $conn && !$conn->isOpen() ) {
698 // Connection was made but later unrecoverably lost for some reason.
699 // Do not return a handle that will just throw exceptions on use,
700 // but let the calling code (e.g. getReaderIndex) try another server.
701 // See DatabaseMyslBase::ping() for how this can happen.
702 $this->mErrorConnection = $conn;
703 $conn = false;
704 }
705
706 return $conn;
707 }
708
709 /**
710 * Open a connection to a foreign DB, or return one if it is already open.
711 *
712 * Increments a reference count on the returned connection which locks the
713 * connection to the requested wiki. This reference count can be
714 * decremented by calling reuseConnection().
715 *
716 * If a connection is open to the appropriate server already, but with the wrong
717 * database, it will be switched to the right database and returned, as long as
718 * it has been freed first with reuseConnection().
719 *
720 * On error, returns false, and the connection which caused the
721 * error will be available via $this->mErrorConnection.
722 *
723 * @param int $i Server index
724 * @param string $wiki Wiki ID to open
725 * @return DatabaseBase
726 */
727 private function openForeignConnection( $i, $wiki ) {
728 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
729 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
730 // Reuse an already-used connection
731 $conn = $this->mConns['foreignUsed'][$i][$wiki];
732 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
733 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
734 // Reuse a free connection for the same wiki
735 $conn = $this->mConns['foreignFree'][$i][$wiki];
736 unset( $this->mConns['foreignFree'][$i][$wiki] );
737 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
738 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
739 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
740 // Reuse a connection from another wiki
741 $conn = reset( $this->mConns['foreignFree'][$i] );
742 $oldWiki = key( $this->mConns['foreignFree'][$i] );
743
744 // The empty string as a DB name means "don't care".
745 // DatabaseMysqlBase::open() already handle this on connection.
746 if ( $dbName !== '' && !$conn->selectDB( $dbName ) ) {
747 $this->mLastError = "Error selecting database $dbName on server " .
748 $conn->getServer() . " from client host " . wfHostname() . "\n";
749 $this->mErrorConnection = $conn;
750 $conn = false;
751 } else {
752 $conn->tablePrefix( $prefix );
753 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
754 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
755 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
756 }
757 } else {
758 // Open a new connection
759 $server = $this->mServers[$i];
760 $server['serverIndex'] = $i;
761 $server['foreignPoolRefCount'] = 0;
762 $server['foreign'] = true;
763 $conn = $this->reallyOpenConnection( $server, $dbName );
764 if ( !$conn->isOpen() ) {
765 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
766 $this->mErrorConnection = $conn;
767 $conn = false;
768 } else {
769 $conn->tablePrefix( $prefix );
770 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
771 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
772 }
773 }
774
775 // Increment reference count
776 if ( $conn ) {
777 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
778 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
779 }
780
781 return $conn;
782 }
783
784 /**
785 * Test if the specified index represents an open connection
786 *
787 * @param int $index Server index
788 * @access private
789 * @return bool
790 */
791 private function isOpen( $index ) {
792 if ( !is_integer( $index ) ) {
793 return false;
794 }
795
796 return (bool)$this->getAnyOpenConnection( $index );
797 }
798
799 /**
800 * Really opens a connection. Uncached.
801 * Returns a Database object whether or not the connection was successful.
802 * @access private
803 *
804 * @param array $server
805 * @param bool $dbNameOverride
806 * @throws MWException
807 * @return DatabaseBase
808 */
809 protected function reallyOpenConnection( $server, $dbNameOverride = false ) {
810 if ( !is_array( $server ) ) {
811 throw new MWException( 'You must update your load-balancing configuration. ' .
812 'See DefaultSettings.php entry for $wgDBservers.' );
813 }
814
815 if ( $dbNameOverride !== false ) {
816 $server['dbname'] = $dbNameOverride;
817 }
818
819 // Let the handle know what the cluster master is (e.g. "db1052")
820 $masterName = $this->getServerName( 0 );
821 $server['clusterMasterHost'] = $masterName;
822
823 // Log when many connection are made on requests
824 if ( ++$this->connsOpened >= self::CONN_HELD_WARN_THRESHOLD ) {
825 wfDebugLog( 'DBPerformance', __METHOD__ . ": " .
826 "{$this->connsOpened}+ connections made (master=$masterName)\n" .
827 wfBacktrace( true ) );
828 }
829
830 # Create object
831 try {
832 $db = DatabaseBase::factory( $server['type'], $server );
833 } catch ( DBConnectionError $e ) {
834 // FIXME: This is probably the ugliest thing I have ever done to
835 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
836 $db = $e->db;
837 }
838
839 $db->setLBInfo( $server );
840 $db->setLazyMasterHandle(
841 $this->getLazyConnectionRef( DB_MASTER, array(), $db->getWikiID() )
842 );
843
844 return $db;
845 }
846
847 /**
848 * @throws DBConnectionError
849 * @return bool
850 */
851 private function reportConnectionError() {
852 $conn = $this->mErrorConnection; // The connection which caused the error
853 $context = array(
854 'method' => __METHOD__,
855 'last_error' => $this->mLastError,
856 );
857
858 if ( !is_object( $conn ) ) {
859 // No last connection, probably due to all servers being too busy
860 wfLogDBError(
861 "LB failure with no last connection. Connection error: {last_error}",
862 $context
863 );
864
865 // If all servers were busy, mLastError will contain something sensible
866 throw new DBConnectionError( null, $this->mLastError );
867 } else {
868 $context['db_server'] = $conn->getProperty( 'mServer' );
869 wfLogDBError(
870 "Connection error: {last_error} ({db_server})",
871 $context
872 );
873
874 // throws DBConnectionError
875 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
876 }
877
878 return false; /* not reached */
879 }
880
881 /**
882 * @return int
883 * @since 1.26
884 */
885 public function getWriterIndex() {
886 return 0;
887 }
888
889 /**
890 * Returns true if the specified index is a valid server index
891 *
892 * @param string $i
893 * @return bool
894 */
895 public function haveIndex( $i ) {
896 return array_key_exists( $i, $this->mServers );
897 }
898
899 /**
900 * Returns true if the specified index is valid and has non-zero load
901 *
902 * @param string $i
903 * @return bool
904 */
905 public function isNonZeroLoad( $i ) {
906 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
907 }
908
909 /**
910 * Get the number of defined servers (not the number of open connections)
911 *
912 * @return int
913 */
914 public function getServerCount() {
915 return count( $this->mServers );
916 }
917
918 /**
919 * Get the host name or IP address of the server with the specified index
920 * Prefer a readable name if available.
921 * @param string $i
922 * @return string
923 */
924 public function getServerName( $i ) {
925 if ( isset( $this->mServers[$i]['hostName'] ) ) {
926 $name = $this->mServers[$i]['hostName'];
927 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
928 $name = $this->mServers[$i]['host'];
929 } else {
930 $name = '';
931 }
932
933 return ( $name != '' ) ? $name : 'localhost';
934 }
935
936 /**
937 * Return the server info structure for a given index, or false if the index is invalid.
938 * @param int $i
939 * @return array|bool
940 */
941 public function getServerInfo( $i ) {
942 if ( isset( $this->mServers[$i] ) ) {
943 return $this->mServers[$i];
944 } else {
945 return false;
946 }
947 }
948
949 /**
950 * Sets the server info structure for the given index. Entry at index $i
951 * is created if it doesn't exist
952 * @param int $i
953 * @param array $serverInfo
954 */
955 public function setServerInfo( $i, array $serverInfo ) {
956 $this->mServers[$i] = $serverInfo;
957 }
958
959 /**
960 * Get the current master position for chronology control purposes
961 * @return mixed
962 */
963 public function getMasterPos() {
964 # If this entire request was served from a slave without opening a connection to the
965 # master (however unlikely that may be), then we can fetch the position from the slave.
966 $masterConn = $this->getAnyOpenConnection( 0 );
967 if ( !$masterConn ) {
968 $serverCount = count( $this->mServers );
969 for ( $i = 1; $i < $serverCount; $i++ ) {
970 $conn = $this->getAnyOpenConnection( $i );
971 if ( $conn ) {
972 return $conn->getSlavePos();
973 }
974 }
975 } else {
976 return $masterConn->getMasterPos();
977 }
978
979 return false;
980 }
981
982 /**
983 * Close all open connections
984 */
985 public function closeAll() {
986 foreach ( $this->mConns as $conns2 ) {
987 foreach ( $conns2 as $conns3 ) {
988 /** @var DatabaseBase $conn */
989 foreach ( $conns3 as $conn ) {
990 $conn->close();
991 }
992 }
993 }
994 $this->mConns = array(
995 'local' => array(),
996 'foreignFree' => array(),
997 'foreignUsed' => array(),
998 );
999 $this->connsOpened = 0;
1000 }
1001
1002 /**
1003 * Close a connection
1004 * Using this function makes sure the LoadBalancer knows the connection is closed.
1005 * If you use $conn->close() directly, the load balancer won't update its state.
1006 * @param DatabaseBase $conn
1007 */
1008 public function closeConnection( $conn ) {
1009 $done = false;
1010 foreach ( $this->mConns as $i1 => $conns2 ) {
1011 foreach ( $conns2 as $i2 => $conns3 ) {
1012 foreach ( $conns3 as $i3 => $candidateConn ) {
1013 if ( $conn === $candidateConn ) {
1014 $conn->close();
1015 unset( $this->mConns[$i1][$i2][$i3] );
1016 --$this->connsOpened;
1017 $done = true;
1018 break;
1019 }
1020 }
1021 }
1022 }
1023 if ( !$done ) {
1024 $conn->close();
1025 }
1026 }
1027
1028 /**
1029 * Commit transactions on all open connections
1030 * @param string $fname Caller name
1031 */
1032 public function commitAll( $fname = __METHOD__ ) {
1033 foreach ( $this->mConns as $conns2 ) {
1034 foreach ( $conns2 as $conns3 ) {
1035 /** @var DatabaseBase[] $conns3 */
1036 foreach ( $conns3 as $conn ) {
1037 if ( $conn->trxLevel() ) {
1038 $conn->commit( $fname, 'flush' );
1039 }
1040 }
1041 }
1042 }
1043 }
1044
1045 /**
1046 * Issue COMMIT only on master, only if queries were done on connection
1047 * @param string $fname Caller name
1048 */
1049 public function commitMasterChanges( $fname = __METHOD__ ) {
1050 $masterIndex = $this->getWriterIndex();
1051 foreach ( $this->mConns as $conns2 ) {
1052 if ( empty( $conns2[$masterIndex] ) ) {
1053 continue;
1054 }
1055 /** @var DatabaseBase $conn */
1056 foreach ( $conns2[$masterIndex] as $conn ) {
1057 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1058 $conn->commit( $fname, 'flush' );
1059 }
1060 }
1061 }
1062 }
1063
1064 /**
1065 * Issue ROLLBACK only on master, only if queries were done on connection
1066 * @param string $fname Caller name
1067 * @throws DBExpectedError
1068 * @since 1.23
1069 */
1070 public function rollbackMasterChanges( $fname = __METHOD__ ) {
1071 $failedServers = array();
1072
1073 $masterIndex = $this->getWriterIndex();
1074 foreach ( $this->mConns as $conns2 ) {
1075 if ( empty( $conns2[$masterIndex] ) ) {
1076 continue;
1077 }
1078 /** @var DatabaseBase $conn */
1079 foreach ( $conns2[$masterIndex] as $conn ) {
1080 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1081 try {
1082 $conn->rollback( $fname, 'flush' );
1083 } catch ( DBError $e ) {
1084 MWExceptionHandler::logException( $e );
1085 $failedServers[] = $conn->getServer();
1086 }
1087 }
1088 }
1089 }
1090
1091 if ( $failedServers ) {
1092 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1093 implode( ', ', array_unique( $failedServers ) ) );
1094 }
1095 }
1096
1097 /**
1098 * @return bool Whether a master connection is already open
1099 * @since 1.24
1100 */
1101 public function hasMasterConnection() {
1102 return $this->isOpen( $this->getWriterIndex() );
1103 }
1104
1105 /**
1106 * Determine if there are pending changes in a transaction by this thread
1107 * @since 1.23
1108 * @return bool
1109 */
1110 public function hasMasterChanges() {
1111 $masterIndex = $this->getWriterIndex();
1112 foreach ( $this->mConns as $conns2 ) {
1113 if ( empty( $conns2[$masterIndex] ) ) {
1114 continue;
1115 }
1116 /** @var DatabaseBase $conn */
1117 foreach ( $conns2[$masterIndex] as $conn ) {
1118 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1119 return true;
1120 }
1121 }
1122 }
1123 return false;
1124 }
1125
1126 /**
1127 * Get the timestamp of the latest write query done by this thread
1128 * @since 1.25
1129 * @return float|bool UNIX timestamp or false
1130 */
1131 public function lastMasterChangeTimestamp() {
1132 $lastTime = false;
1133 $masterIndex = $this->getWriterIndex();
1134 foreach ( $this->mConns as $conns2 ) {
1135 if ( empty( $conns2[$masterIndex] ) ) {
1136 continue;
1137 }
1138 /** @var DatabaseBase $conn */
1139 foreach ( $conns2[$masterIndex] as $conn ) {
1140 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1141 }
1142 }
1143 return $lastTime;
1144 }
1145
1146 /**
1147 * Check if this load balancer object had any recent or still
1148 * pending writes issued against it by this PHP thread
1149 *
1150 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1151 * @return bool
1152 * @since 1.25
1153 */
1154 public function hasOrMadeRecentMasterChanges( $age = null ) {
1155 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1156
1157 return ( $this->hasMasterChanges()
1158 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1159 }
1160
1161 /**
1162 * @param mixed $value
1163 * @return mixed
1164 */
1165 public function waitTimeout( $value = null ) {
1166 return wfSetVar( $this->mWaitTimeout, $value );
1167 }
1168
1169 /**
1170 * @note This method will trigger a DB connection if not yet done
1171 *
1172 * @param string|bool $wiki Wiki ID, or false for the current wiki
1173 * @return bool Whether the generic connection for reads is highly "lagged"
1174 */
1175 public function getLaggedSlaveMode( $wiki = false ) {
1176 // No-op if there is only one DB (also avoids recursion)
1177 if ( !$this->laggedSlaveMode && $this->getServerCount() > 1 ) {
1178 try {
1179 // See if laggedSlaveMode gets set
1180 $conn = $this->getConnection( DB_SLAVE, false, $wiki );
1181 $this->reuseConnection( $conn );
1182 } catch ( DBConnectionError $e ) {
1183 // Avoid expensive re-connect attempts and failures
1184 $this->slavesDownMode = true;
1185 $this->laggedSlaveMode = true;
1186 }
1187 }
1188
1189 return $this->laggedSlaveMode;
1190 }
1191
1192 /**
1193 * @note This method will never cause a new DB connection
1194 * @return bool Whether any generic connection used for reads was highly "lagged"
1195 * @since 1.27
1196 */
1197 public function laggedSlaveUsed() {
1198 return $this->laggedSlaveMode;
1199 }
1200
1201 /**
1202 * @note This method may trigger a DB connection if not yet done
1203 * @param string|bool $wiki Wiki ID, or false for the current wiki
1204 * @return string|bool Reason the master is read-only or false if it is not
1205 * @since 1.27
1206 */
1207 public function getReadOnlyReason( $wiki = false ) {
1208 if ( $this->readOnlyReason !== false ) {
1209 return $this->readOnlyReason;
1210 } elseif ( $this->getLaggedSlaveMode( $wiki ) ) {
1211 if ( $this->slavesDownMode ) {
1212 return 'The database has been automatically locked ' .
1213 'until the slave database servers become available';
1214 } else {
1215 return 'The database has been automatically locked ' .
1216 'while the slave database servers catch up to the master.';
1217 }
1218 }
1219
1220 return false;
1221 }
1222
1223 /**
1224 * Disables/enables lag checks
1225 * @param null|bool $mode
1226 * @return bool
1227 */
1228 public function allowLagged( $mode = null ) {
1229 if ( $mode === null ) {
1230 return $this->mAllowLagged;
1231 }
1232 $this->mAllowLagged = $mode;
1233
1234 return $this->mAllowLagged;
1235 }
1236
1237 /**
1238 * @return bool
1239 */
1240 public function pingAll() {
1241 $success = true;
1242 foreach ( $this->mConns as $conns2 ) {
1243 foreach ( $conns2 as $conns3 ) {
1244 /** @var DatabaseBase[] $conns3 */
1245 foreach ( $conns3 as $conn ) {
1246 if ( !$conn->ping() ) {
1247 $success = false;
1248 }
1249 }
1250 }
1251 }
1252
1253 return $success;
1254 }
1255
1256 /**
1257 * Call a function with each open connection object
1258 * @param callable $callback
1259 * @param array $params
1260 */
1261 public function forEachOpenConnection( $callback, array $params = array() ) {
1262 foreach ( $this->mConns as $conns2 ) {
1263 foreach ( $conns2 as $conns3 ) {
1264 foreach ( $conns3 as $conn ) {
1265 $mergedParams = array_merge( array( $conn ), $params );
1266 call_user_func_array( $callback, $mergedParams );
1267 }
1268 }
1269 }
1270 }
1271
1272 /**
1273 * Get the hostname and lag time of the most-lagged slave
1274 *
1275 * This is useful for maintenance scripts that need to throttle their updates.
1276 * May attempt to open connections to slaves on the default DB. If there is
1277 * no lag, the maximum lag will be reported as -1.
1278 *
1279 * @param bool|string $wiki Wiki ID, or false for the default database
1280 * @return array ( host, max lag, index of max lagged host )
1281 */
1282 public function getMaxLag( $wiki = false ) {
1283 $maxLag = -1;
1284 $host = '';
1285 $maxIndex = 0;
1286
1287 if ( $this->getServerCount() <= 1 ) {
1288 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1289 }
1290
1291 $lagTimes = $this->getLagTimes( $wiki );
1292 foreach ( $lagTimes as $i => $lag ) {
1293 if ( $lag > $maxLag ) {
1294 $maxLag = $lag;
1295 $host = $this->mServers[$i]['host'];
1296 $maxIndex = $i;
1297 }
1298 }
1299
1300 return array( $host, $maxLag, $maxIndex );
1301 }
1302
1303 /**
1304 * Get an estimate of replication lag (in seconds) for each server
1305 *
1306 * Results are cached for a short time in memcached/process cache
1307 *
1308 * Values may be "false" if replication is too broken to estimate
1309 *
1310 * @param string|bool $wiki
1311 * @return int[] Map of (server index => float|int|bool)
1312 */
1313 public function getLagTimes( $wiki = false ) {
1314 if ( $this->getServerCount() <= 1 ) {
1315 return array( 0 => 0 ); // no replication = no lag
1316 }
1317
1318 # Send the request to the load monitor
1319 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1320 }
1321
1322 /**
1323 * Get the lag in seconds for a given connection, or zero if this load
1324 * balancer does not have replication enabled.
1325 *
1326 * This should be used in preference to Database::getLag() in cases where
1327 * replication may not be in use, since there is no way to determine if
1328 * replication is in use at the connection level without running
1329 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1330 * function instead of Database::getLag() avoids a fatal error in this
1331 * case on many installations.
1332 *
1333 * @param DatabaseBase $conn
1334 * @return int
1335 */
1336 public function safeGetLag( $conn ) {
1337 if ( $this->getServerCount() == 1 ) {
1338 return 0;
1339 } else {
1340 return $conn->getLag();
1341 }
1342 }
1343
1344 /**
1345 * Clear the cache for slag lag delay times
1346 *
1347 * This is only used for testing
1348 */
1349 public function clearLagTimeCache() {
1350 $this->getLoadMonitor()->clearCaches();
1351 }
1352 }