Removed old fake slave hacks used for debug log testing
[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 # 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
807 return $db;
808 }
809
810 /**
811 * @throws DBConnectionError
812 * @return bool
813 */
814 private function reportConnectionError() {
815 $conn = $this->mErrorConnection; // The connection which caused the error
816 $context = array(
817 'method' => __METHOD__,
818 'last_error' => $this->mLastError,
819 );
820
821 if ( !is_object( $conn ) ) {
822 // No last connection, probably due to all servers being too busy
823 wfLogDBError(
824 "LB failure with no last connection. Connection error: {last_error}",
825 $context
826 );
827
828 // If all servers were busy, mLastError will contain something sensible
829 throw new DBConnectionError( null, $this->mLastError );
830 } else {
831 $context['db_server'] = $conn->getProperty( 'mServer' );
832 wfLogDBError(
833 "Connection error: {last_error} ({db_server})",
834 $context
835 );
836
837 // throws DBConnectionError
838 $conn->reportConnectionError( "{$this->mLastError} ({$context['db_server']})" );
839 }
840
841 return false; /* not reached */
842 }
843
844 /**
845 * @return int
846 * @since 1.26
847 */
848 public function getWriterIndex() {
849 return 0;
850 }
851
852 /**
853 * Returns true if the specified index is a valid server index
854 *
855 * @param string $i
856 * @return bool
857 */
858 public function haveIndex( $i ) {
859 return array_key_exists( $i, $this->mServers );
860 }
861
862 /**
863 * Returns true if the specified index is valid and has non-zero load
864 *
865 * @param string $i
866 * @return bool
867 */
868 public function isNonZeroLoad( $i ) {
869 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
870 }
871
872 /**
873 * Get the number of defined servers (not the number of open connections)
874 *
875 * @return int
876 */
877 public function getServerCount() {
878 return count( $this->mServers );
879 }
880
881 /**
882 * Get the host name or IP address of the server with the specified index
883 * Prefer a readable name if available.
884 * @param string $i
885 * @return string
886 */
887 public function getServerName( $i ) {
888 if ( isset( $this->mServers[$i]['hostName'] ) ) {
889 $name = $this->mServers[$i]['hostName'];
890 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
891 $name = $this->mServers[$i]['host'];
892 } else {
893 $name = '';
894 }
895
896 return ( $name != '' ) ? $name : 'localhost';
897 }
898
899 /**
900 * Return the server info structure for a given index, or false if the index is invalid.
901 * @param int $i
902 * @return array|bool
903 */
904 public function getServerInfo( $i ) {
905 if ( isset( $this->mServers[$i] ) ) {
906 return $this->mServers[$i];
907 } else {
908 return false;
909 }
910 }
911
912 /**
913 * Sets the server info structure for the given index. Entry at index $i
914 * is created if it doesn't exist
915 * @param int $i
916 * @param array $serverInfo
917 */
918 public function setServerInfo( $i, array $serverInfo ) {
919 $this->mServers[$i] = $serverInfo;
920 }
921
922 /**
923 * Get the current master position for chronology control purposes
924 * @return mixed
925 */
926 public function getMasterPos() {
927 # If this entire request was served from a slave without opening a connection to the
928 # master (however unlikely that may be), then we can fetch the position from the slave.
929 $masterConn = $this->getAnyOpenConnection( 0 );
930 if ( !$masterConn ) {
931 $serverCount = count( $this->mServers );
932 for ( $i = 1; $i < $serverCount; $i++ ) {
933 $conn = $this->getAnyOpenConnection( $i );
934 if ( $conn ) {
935 wfDebug( "Master pos fetched from slave\n" );
936
937 return $conn->getSlavePos();
938 }
939 }
940 } else {
941 wfDebug( "Master pos fetched from master\n" );
942
943 return $masterConn->getMasterPos();
944 }
945
946 return false;
947 }
948
949 /**
950 * Close all open connections
951 */
952 public function closeAll() {
953 foreach ( $this->mConns as $conns2 ) {
954 foreach ( $conns2 as $conns3 ) {
955 /** @var DatabaseBase $conn */
956 foreach ( $conns3 as $conn ) {
957 $conn->close();
958 }
959 }
960 }
961 $this->mConns = array(
962 'local' => array(),
963 'foreignFree' => array(),
964 'foreignUsed' => array(),
965 );
966 $this->connsOpened = 0;
967 }
968
969 /**
970 * Close a connection
971 * Using this function makes sure the LoadBalancer knows the connection is closed.
972 * If you use $conn->close() directly, the load balancer won't update its state.
973 * @param DatabaseBase $conn
974 */
975 public function closeConnection( $conn ) {
976 $done = false;
977 foreach ( $this->mConns as $i1 => $conns2 ) {
978 foreach ( $conns2 as $i2 => $conns3 ) {
979 foreach ( $conns3 as $i3 => $candidateConn ) {
980 if ( $conn === $candidateConn ) {
981 $conn->close();
982 unset( $this->mConns[$i1][$i2][$i3] );
983 --$this->connsOpened;
984 $done = true;
985 break;
986 }
987 }
988 }
989 }
990 if ( !$done ) {
991 $conn->close();
992 }
993 }
994
995 /**
996 * Commit transactions on all open connections
997 */
998 public function commitAll() {
999 foreach ( $this->mConns as $conns2 ) {
1000 foreach ( $conns2 as $conns3 ) {
1001 /** @var DatabaseBase[] $conns3 */
1002 foreach ( $conns3 as $conn ) {
1003 if ( $conn->trxLevel() ) {
1004 $conn->commit( __METHOD__, 'flush' );
1005 }
1006 }
1007 }
1008 }
1009 }
1010
1011 /**
1012 * Issue COMMIT only on master, only if queries were done on connection
1013 */
1014 public function commitMasterChanges() {
1015 $masterIndex = $this->getWriterIndex();
1016 foreach ( $this->mConns as $conns2 ) {
1017 if ( empty( $conns2[$masterIndex] ) ) {
1018 continue;
1019 }
1020 /** @var DatabaseBase $conn */
1021 foreach ( $conns2[$masterIndex] as $conn ) {
1022 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1023 $conn->commit( __METHOD__, 'flush' );
1024 }
1025 }
1026 }
1027 }
1028
1029 /**
1030 * Issue ROLLBACK only on master, only if queries were done on connection
1031 * @since 1.23
1032 */
1033 public function rollbackMasterChanges() {
1034 $failedServers = array();
1035
1036 $masterIndex = $this->getWriterIndex();
1037 foreach ( $this->mConns as $conns2 ) {
1038 if ( empty( $conns2[$masterIndex] ) ) {
1039 continue;
1040 }
1041 /** @var DatabaseBase $conn */
1042 foreach ( $conns2[$masterIndex] as $conn ) {
1043 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1044 try {
1045 $conn->rollback( __METHOD__, 'flush' );
1046 } catch ( DBError $e ) {
1047 MWExceptionHandler::logException( $e );
1048 $failedServers[] = $conn->getServer();
1049 }
1050 }
1051 }
1052 }
1053
1054 if ( $failedServers ) {
1055 throw new DBExpectedError( null, "Rollback failed on server(s) " .
1056 implode( ', ', array_unique( $failedServers ) ) );
1057 }
1058 }
1059
1060 /**
1061 * @return bool Whether a master connection is already open
1062 * @since 1.24
1063 */
1064 public function hasMasterConnection() {
1065 return $this->isOpen( $this->getWriterIndex() );
1066 }
1067
1068 /**
1069 * Determine if there are pending changes in a transaction by this thread
1070 * @since 1.23
1071 * @return bool
1072 */
1073 public function hasMasterChanges() {
1074 $masterIndex = $this->getWriterIndex();
1075 foreach ( $this->mConns as $conns2 ) {
1076 if ( empty( $conns2[$masterIndex] ) ) {
1077 continue;
1078 }
1079 /** @var DatabaseBase $conn */
1080 foreach ( $conns2[$masterIndex] as $conn ) {
1081 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
1082 return true;
1083 }
1084 }
1085 }
1086 return false;
1087 }
1088
1089 /**
1090 * Get the timestamp of the latest write query done by this thread
1091 * @since 1.25
1092 * @return float|bool UNIX timestamp or false
1093 */
1094 public function lastMasterChangeTimestamp() {
1095 $lastTime = false;
1096 $masterIndex = $this->getWriterIndex();
1097 foreach ( $this->mConns as $conns2 ) {
1098 if ( empty( $conns2[$masterIndex] ) ) {
1099 continue;
1100 }
1101 /** @var DatabaseBase $conn */
1102 foreach ( $conns2[$masterIndex] as $conn ) {
1103 $lastTime = max( $lastTime, $conn->lastDoneWrites() );
1104 }
1105 }
1106 return $lastTime;
1107 }
1108
1109 /**
1110 * Check if this load balancer object had any recent or still
1111 * pending writes issued against it by this PHP thread
1112 *
1113 * @param float $age How many seconds ago is "recent" [defaults to mWaitTimeout]
1114 * @return bool
1115 * @since 1.25
1116 */
1117 public function hasOrMadeRecentMasterChanges( $age = null ) {
1118 $age = ( $age === null ) ? $this->mWaitTimeout : $age;
1119
1120 return ( $this->hasMasterChanges()
1121 || $this->lastMasterChangeTimestamp() > microtime( true ) - $age );
1122 }
1123
1124 /**
1125 * @param mixed $value
1126 * @return mixed
1127 */
1128 public function waitTimeout( $value = null ) {
1129 return wfSetVar( $this->mWaitTimeout, $value );
1130 }
1131
1132 /**
1133 * @return bool Whether the generic connection for reads is highly "lagged"
1134 */
1135 public function getLaggedSlaveMode() {
1136 # Get a generic reader connection
1137 $this->getConnection( DB_SLAVE );
1138
1139 return $this->mLaggedSlaveMode;
1140 }
1141
1142 /**
1143 * Disables/enables lag checks
1144 * @param null|bool $mode
1145 * @return bool
1146 */
1147 public function allowLagged( $mode = null ) {
1148 if ( $mode === null ) {
1149 return $this->mAllowLagged;
1150 }
1151 $this->mAllowLagged = $mode;
1152
1153 return $this->mAllowLagged;
1154 }
1155
1156 /**
1157 * @return bool
1158 */
1159 public function pingAll() {
1160 $success = true;
1161 foreach ( $this->mConns as $conns2 ) {
1162 foreach ( $conns2 as $conns3 ) {
1163 /** @var DatabaseBase[] $conns3 */
1164 foreach ( $conns3 as $conn ) {
1165 if ( !$conn->ping() ) {
1166 $success = false;
1167 }
1168 }
1169 }
1170 }
1171
1172 return $success;
1173 }
1174
1175 /**
1176 * Call a function with each open connection object
1177 * @param callable $callback
1178 * @param array $params
1179 */
1180 public function forEachOpenConnection( $callback, array $params = array() ) {
1181 foreach ( $this->mConns as $conns2 ) {
1182 foreach ( $conns2 as $conns3 ) {
1183 foreach ( $conns3 as $conn ) {
1184 $mergedParams = array_merge( array( $conn ), $params );
1185 call_user_func_array( $callback, $mergedParams );
1186 }
1187 }
1188 }
1189 }
1190
1191 /**
1192 * Get the hostname and lag time of the most-lagged slave
1193 *
1194 * This is useful for maintenance scripts that need to throttle their updates.
1195 * May attempt to open connections to slaves on the default DB. If there is
1196 * no lag, the maximum lag will be reported as -1.
1197 *
1198 * @param bool|string $wiki Wiki ID, or false for the default database
1199 * @return array ( host, max lag, index of max lagged host )
1200 */
1201 public function getMaxLag( $wiki = false ) {
1202 $maxLag = -1;
1203 $host = '';
1204 $maxIndex = 0;
1205
1206 if ( $this->getServerCount() <= 1 ) {
1207 return array( $host, $maxLag, $maxIndex ); // no replication = no lag
1208 }
1209
1210 $lagTimes = $this->getLagTimes( $wiki );
1211 foreach ( $lagTimes as $i => $lag ) {
1212 if ( $lag > $maxLag ) {
1213 $maxLag = $lag;
1214 $host = $this->mServers[$i]['host'];
1215 $maxIndex = $i;
1216 }
1217 }
1218
1219 return array( $host, $maxLag, $maxIndex );
1220 }
1221
1222 /**
1223 * Get lag time for each server
1224 *
1225 * Results are cached for a short time in memcached/process cache
1226 *
1227 * @param string|bool $wiki
1228 * @return int[] Map of (server index => seconds)
1229 */
1230 public function getLagTimes( $wiki = false ) {
1231 if ( $this->getServerCount() <= 1 ) {
1232 return array( 0 => 0 ); // no replication = no lag
1233 }
1234
1235 # Send the request to the load monitor
1236 return $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
1237 }
1238
1239 /**
1240 * Get the lag in seconds for a given connection, or zero if this load
1241 * balancer does not have replication enabled.
1242 *
1243 * This should be used in preference to Database::getLag() in cases where
1244 * replication may not be in use, since there is no way to determine if
1245 * replication is in use at the connection level without running
1246 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1247 * function instead of Database::getLag() avoids a fatal error in this
1248 * case on many installations.
1249 *
1250 * @param DatabaseBase $conn
1251 * @return int
1252 */
1253 public function safeGetLag( $conn ) {
1254 if ( $this->getServerCount() == 1 ) {
1255 return 0;
1256 } else {
1257 return $conn->getLag();
1258 }
1259 }
1260
1261 /**
1262 * Clear the cache for slag lag delay times
1263 *
1264 * This is only used for testing
1265 */
1266 public function clearLagTimeCache() {
1267 $this->getLoadMonitor()->clearCaches();
1268 }
1269 }