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