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