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