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