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