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