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