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