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