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