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