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