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