f7020478854050d1330414e9f3ec458dfb9ba31e
[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 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
38
39 /**
40 * @param array $params with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
44 * @throws MWException
45 */
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__ . ': missing servers parameter' );
49 }
50 $this->mServers = $params['servers'];
51
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout = $params['waitTimeout'];
54 } else {
55 $this->mWaitTimeout = 10;
56 }
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 = 'LoadMonitor_MySQL';
76 } else {
77 $this->mLoadMonitorClass = 'LoadMonitor_Null';
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 return $this->mLoadMonitor;
105 }
106
107 /**
108 * Get or set arbitrary data used by the parent object, usually an LBFactory
109 * @param $x
110 * @return Mixed
111 */
112 function parentInfo( $x = null ) {
113 return wfSetVar( $this->mParentInfo, $x );
114 }
115
116 /**
117 * Given an array of non-normalised probabilities, this function will select
118 * an element and return the appropriate key
119 *
120 * @deprecated 1.21, use ArrayUtils::pickRandom()
121 *
122 * @param $weights array
123 *
124 * @return bool|int|string
125 */
126 function pickRandom( $weights ) {
127 return ArrayUtils::pickRandom( $weights );
128 }
129
130 /**
131 * @param $loads array
132 * @param $wiki bool
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\n" );
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)\n" );
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 $this->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 $group bool
180 * @param $wiki bool
181 * @throws MWException
182 * @return bool|int|string
183 */
184 function getReaderIndex( $group = false, $wiki = false ) {
185 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $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 and $this->mReadIndex >= 0 ) {
196 # Shortcut if generic reader exists already
197 return $this->mReadIndex;
198 }
199
200 wfProfileIn( __METHOD__ );
201
202 $totalElapsed = 0;
203
204 # convert from seconds to microseconds
205 $timeout = $wgDBClusterTimeout * 1e6;
206
207 # Find the relevant load array
208 if ( $group !== false ) {
209 if ( isset( $this->mGroupLoads[$group] ) ) {
210 $nonErrorLoads = $this->mGroupLoads[$group];
211 } else {
212 # No loads for this group, return false and the caller can use some other group
213 wfDebug( __METHOD__ . ": no loads for group $group\n" );
214 wfProfileOut( __METHOD__ );
215 return false;
216 }
217 } else {
218 $nonErrorLoads = $this->mLoads;
219 }
220
221 if ( !$nonErrorLoads ) {
222 wfProfileOut( __METHOD__ );
223 throw new MWException( "Empty server array given to LoadBalancer" );
224 }
225
226 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
227 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
228
229 $laggedSlaveMode = false;
230
231 # First try quickly looking through the available servers for a server that
232 # meets our criteria
233 do {
234 $totalThreadsConnected = 0;
235 $overloadedServers = 0;
236 $currentLoads = $nonErrorLoads;
237 while ( count( $currentLoads ) ) {
238 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
239 $i = $this->pickRandom( $currentLoads );
240 } else {
241 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
242 if ( $i === false && count( $currentLoads ) != 0 ) {
243 # All slaves lagged. Switch to read-only mode
244 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
245 $wgReadOnly = 'The database has been automatically locked ' .
246 'while the slave database servers catch up to the master';
247 $i = $this->pickRandom( $currentLoads );
248 $laggedSlaveMode = true;
249 }
250 }
251
252 if ( $i === false ) {
253 # pickRandom() returned false
254 # This is permanent and means the configuration or the load monitor
255 # wants us to return false.
256 wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false\n" );
257 wfProfileOut( __METHOD__ );
258 return false;
259 }
260
261 wfDebugLog( 'connect', __METHOD__ . ": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
262 $conn = $this->openConnection( $i, $wiki );
263
264 if ( !$conn ) {
265 wfDebugLog( 'connect', __METHOD__ . ": Failed connecting to $i/$wiki\n" );
266 unset( $nonErrorLoads[$i] );
267 unset( $currentLoads[$i] );
268 continue;
269 }
270
271 // Perform post-connection backoff
272 $threshold = isset( $this->mServers[$i]['max threads'] )
273 ? $this->mServers[$i]['max threads'] : false;
274 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
275
276 // Decrement reference counter, we are finished with this connection.
277 // It will be incremented for the caller later.
278 if ( $wiki !== false ) {
279 $this->reuseConnection( $conn );
280 }
281
282 if ( $backoff ) {
283 # Post-connection overload, don't use this server for now
284 $totalThreadsConnected += $backoff;
285 $overloadedServers++;
286 unset( $currentLoads[$i] );
287 } else {
288 # Return this server
289 break 2;
290 }
291 }
292
293 # No server found yet
294 $i = false;
295
296 # If all servers were down, quit now
297 if ( !count( $nonErrorLoads ) ) {
298 wfDebugLog( 'connect', "All servers down\n" );
299 break;
300 }
301
302 # Some servers must have been overloaded
303 if ( $overloadedServers == 0 ) {
304 throw new MWException( __METHOD__ . ": unexpectedly found no overloaded servers" );
305 }
306 # Back off for a while
307 # Scale the sleep time by the number of connected threads, to produce a
308 # roughly constant global poll rate
309 $avgThreads = $totalThreadsConnected / $overloadedServers;
310 $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
311 } while ( $totalElapsed < $timeout );
312
313 if ( $totalElapsed >= $timeout ) {
314 wfDebugLog( 'connect', "All servers busy\n" );
315 $this->mErrorConnection = false;
316 $this->mLastError = 'All servers busy';
317 }
318
319 if ( $i !== false ) {
320 # Slave connection successful
321 # Wait for the session master pos for a short time
322 if ( $this->mWaitForPos && $i > 0 ) {
323 if ( !$this->doWait( $i ) ) {
324 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
325 }
326 }
327 if ( $this->mReadIndex <= 0 && $this->mLoads[$i] > 0 && $i !== false ) {
328 $this->mReadIndex = $i;
329 }
330 }
331 wfProfileOut( __METHOD__ );
332 return $i;
333 }
334
335 /**
336 * Wait for a specified number of microseconds, and return the period waited
337 * @param $t int
338 * @return int
339 */
340 function sleep( $t ) {
341 wfProfileIn( __METHOD__ );
342 wfDebug( __METHOD__ . ": waiting $t us\n" );
343 usleep( $t );
344 wfProfileOut( __METHOD__ );
345 return $t;
346 }
347
348 /**
349 * Set the master wait position
350 * If a DB_SLAVE connection has been opened already, waits
351 * Otherwise sets a variable telling it to wait if such a connection is opened
352 * @param $pos DBMasterPos
353 */
354 public function waitFor( $pos ) {
355 wfProfileIn( __METHOD__ );
356 $this->mWaitForPos = $pos;
357 $i = $this->mReadIndex;
358
359 if ( $i > 0 ) {
360 if ( !$this->doWait( $i ) ) {
361 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
362 $this->mLaggedSlaveMode = true;
363 }
364 }
365 wfProfileOut( __METHOD__ );
366 }
367
368 /**
369 * Set the master wait position and wait for ALL slaves to catch up to it
370 * @param $pos DBMasterPos
371 */
372 public function waitForAll( $pos ) {
373 wfProfileIn( __METHOD__ );
374 $this->mWaitForPos = $pos;
375 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
376 $this->doWait( $i, true );
377 }
378 wfProfileOut( __METHOD__ );
379 }
380
381 /**
382 * Get any open connection to a given server index, local or foreign
383 * Returns false if there is no connection open
384 *
385 * @param $i int
386 * @return DatabaseBase|bool False on failure
387 */
388 function getAnyOpenConnection( $i ) {
389 foreach ( $this->mConns as $conns ) {
390 if ( !empty( $conns[$i] ) ) {
391 return reset( $conns[$i] );
392 }
393 }
394 return false;
395 }
396
397 /**
398 * Wait for a given slave to catch up to the master pos stored in $this
399 * @param $index
400 * @param $open bool
401 * @return bool
402 */
403 protected function doWait( $index, $open = false ) {
404 # Find a connection to wait on
405 $conn = $this->getAnyOpenConnection( $index );
406 if ( !$conn ) {
407 if ( !$open ) {
408 wfDebug( __METHOD__ . ": no connection open\n" );
409 return false;
410 } else {
411 $conn = $this->openConnection( $index, '' );
412 if ( !$conn ) {
413 wfDebug( __METHOD__ . ": failed to open connection\n" );
414 return false;
415 }
416 }
417 }
418
419 wfDebug( __METHOD__ . ": Waiting for slave #$index to catch up...\n" );
420 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
421
422 if ( $result == -1 || is_null( $result ) ) {
423 # Timed out waiting for slave, use master instead
424 wfDebug( __METHOD__ . ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
425 return false;
426 } else {
427 wfDebug( __METHOD__ . ": Done\n" );
428 return true;
429 }
430 }
431
432 /**
433 * Get a connection by index
434 * This is the main entry point for this class.
435 *
436 * @param $i Integer: server index
437 * @param array $groups query groups
438 * @param bool|string $wiki Wiki ID
439 *
440 * @throws MWException
441 * @return DatabaseBase
442 */
443 public function &getConnection( $i, $groups = array(), $wiki = false ) {
444 wfProfileIn( __METHOD__ );
445
446 if ( $i == DB_LAST ) {
447 wfProfileOut( __METHOD__ );
448 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
449 } elseif ( $i === null || $i === false ) {
450 wfProfileOut( __METHOD__ );
451 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
452 }
453
454 if ( $wiki === wfWikiID() ) {
455 $wiki = false;
456 }
457
458 # Query groups
459 if ( $i == DB_MASTER ) {
460 $i = $this->getWriterIndex();
461 } elseif ( !is_array( $groups ) ) {
462 $groupIndex = $this->getReaderIndex( $groups, $wiki );
463 if ( $groupIndex !== false ) {
464 $serverName = $this->getServerName( $groupIndex );
465 wfDebug( __METHOD__ . ": using server $serverName for group $groups\n" );
466 $i = $groupIndex;
467 }
468 } else {
469 foreach ( $groups as $group ) {
470 $groupIndex = $this->getReaderIndex( $group, $wiki );
471 if ( $groupIndex !== false ) {
472 $serverName = $this->getServerName( $groupIndex );
473 wfDebug( __METHOD__ . ": using server $serverName for group $group\n" );
474 $i = $groupIndex;
475 break;
476 }
477 }
478 }
479
480 # Operation-based index
481 if ( $i == DB_SLAVE ) {
482 $i = $this->getReaderIndex( false, $wiki );
483 # Couldn't find a working server in getReaderIndex()?
484 if ( $i === false ) {
485 $this->mLastError = 'No working slave server: ' . $this->mLastError;
486 wfProfileOut( __METHOD__ );
487 return $this->reportConnectionError();
488 }
489 }
490
491 # Now we have an explicit index into the servers array
492 $conn = $this->openConnection( $i, $wiki );
493 if ( !$conn ) {
494 wfProfileOut( __METHOD__ );
495 return $this->reportConnectionError();
496 }
497
498 wfProfileOut( __METHOD__ );
499 return $conn;
500 }
501
502 /**
503 * Mark a foreign connection as being available for reuse under a different
504 * DB name or prefix. This mechanism is reference-counted, and must be called
505 * the same number of times as getConnection() to work.
506 *
507 * @param DatabaseBase $conn
508 * @throws MWException
509 */
510 public function reuseConnection( $conn ) {
511 $serverIndex = $conn->getLBInfo( 'serverIndex' );
512 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
513 $dbName = $conn->getDBname();
514 $prefix = $conn->tablePrefix();
515 if ( strval( $prefix ) !== '' ) {
516 $wiki = "$dbName-$prefix";
517 } else {
518 $wiki = $dbName;
519 }
520 if ( $serverIndex === null || $refCount === null ) {
521 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
522 /**
523 * This can happen in code like:
524 * foreach ( $dbs as $db ) {
525 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
526 * ...
527 * $lb->reuseConnection( $conn );
528 * }
529 * When a connection to the local DB is opened in this way, reuseConnection()
530 * should be ignored
531 */
532 return;
533 }
534 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
535 throw new MWException( __METHOD__ . ": connection not found, has the connection been freed already?" );
536 }
537 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
538 if ( $refCount <= 0 ) {
539 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
540 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
541 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
542 } else {
543 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
544 }
545 }
546
547 /**
548 * Open a connection to the server given by the specified index
549 * Index must be an actual index into the array.
550 * If the server is already open, returns it.
551 *
552 * On error, returns false, and the connection which caused the
553 * error will be available via $this->mErrorConnection.
554 *
555 * @param $i Integer server index
556 * @param string $wiki wiki ID to open
557 * @return DatabaseBase
558 *
559 * @access private
560 */
561 function openConnection( $i, $wiki = false ) {
562 wfProfileIn( __METHOD__ );
563 if ( $wiki !== false ) {
564 $conn = $this->openForeignConnection( $i, $wiki );
565 wfProfileOut( __METHOD__ );
566 return $conn;
567 }
568 if ( isset( $this->mConns['local'][$i][0] ) ) {
569 $conn = $this->mConns['local'][$i][0];
570 } else {
571 $server = $this->mServers[$i];
572 $server['serverIndex'] = $i;
573 $conn = $this->reallyOpenConnection( $server, false );
574 if ( $conn->isOpen() ) {
575 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
576 $this->mConns['local'][$i][0] = $conn;
577 } else {
578 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
579 $this->mErrorConnection = $conn;
580 $conn = false;
581 }
582 }
583 wfProfileOut( __METHOD__ );
584 return $conn;
585 }
586
587 /**
588 * Open a connection to a foreign DB, or return one if it is already open.
589 *
590 * Increments a reference count on the returned connection which locks the
591 * connection to the requested wiki. This reference count can be
592 * decremented by calling reuseConnection().
593 *
594 * If a connection is open to the appropriate server already, but with the wrong
595 * database, it will be switched to the right database and returned, as long as
596 * it has been freed first with reuseConnection().
597 *
598 * On error, returns false, and the connection which caused the
599 * error will be available via $this->mErrorConnection.
600 *
601 * @param $i Integer: server index
602 * @param string $wiki wiki ID to open
603 * @return DatabaseBase
604 */
605 function openForeignConnection( $i, $wiki ) {
606 wfProfileIn( __METHOD__ );
607 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
608 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
609 // Reuse an already-used connection
610 $conn = $this->mConns['foreignUsed'][$i][$wiki];
611 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
612 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
613 // Reuse a free connection for the same wiki
614 $conn = $this->mConns['foreignFree'][$i][$wiki];
615 unset( $this->mConns['foreignFree'][$i][$wiki] );
616 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
617 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
618 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
619 // Reuse a connection from another wiki
620 $conn = reset( $this->mConns['foreignFree'][$i] );
621 $oldWiki = key( $this->mConns['foreignFree'][$i] );
622
623 if ( !$conn->selectDB( $dbName ) ) {
624 $this->mLastError = "Error selecting database $dbName on server " .
625 $conn->getServer() . " from client host " . wfHostname() . "\n";
626 $this->mErrorConnection = $conn;
627 $conn = false;
628 } else {
629 $conn->tablePrefix( $prefix );
630 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
631 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
632 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
633 }
634 } else {
635 // Open a new connection
636 $server = $this->mServers[$i];
637 $server['serverIndex'] = $i;
638 $server['foreignPoolRefCount'] = 0;
639 $conn = $this->reallyOpenConnection( $server, $dbName );
640 if ( !$conn->isOpen() ) {
641 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
642 $this->mErrorConnection = $conn;
643 $conn = false;
644 } else {
645 $conn->tablePrefix( $prefix );
646 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
647 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
648 }
649 }
650
651 // Increment reference count
652 if ( $conn ) {
653 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
654 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
655 }
656 wfProfileOut( __METHOD__ );
657 return $conn;
658 }
659
660 /**
661 * Test if the specified index represents an open connection
662 *
663 * @param $index Integer: server index
664 * @access private
665 * @return bool
666 */
667 function isOpen( $index ) {
668 if ( !is_integer( $index ) ) {
669 return false;
670 }
671 return (bool)$this->getAnyOpenConnection( $index );
672 }
673
674 /**
675 * Really opens a connection. Uncached.
676 * Returns a Database object whether or not the connection was successful.
677 * @access private
678 *
679 * @param $server
680 * @param $dbNameOverride bool
681 * @throws MWException
682 * @return DatabaseBase
683 */
684 function reallyOpenConnection( $server, $dbNameOverride = false ) {
685 if ( !is_array( $server ) ) {
686 throw new MWException( 'You must update your load-balancing configuration. ' .
687 'See DefaultSettings.php entry for $wgDBservers.' );
688 }
689
690 if ( $dbNameOverride !== false ) {
691 $server['dbname'] = $dbNameOverride;
692 }
693
694 # Create object
695 try {
696 $db = DatabaseBase::factory( $server['type'], $server );
697 } catch ( DBConnectionError $e ) {
698 // FIXME: This is probably the ugliest thing I have ever done to
699 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
700 $db = $e->db;
701 }
702
703 $db->setLBInfo( $server );
704 if ( isset( $server['fakeSlaveLag'] ) ) {
705 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
706 }
707 if ( isset( $server['fakeMaster'] ) ) {
708 $db->setFakeMaster( true );
709 }
710 return $db;
711 }
712
713 /**
714 * @throws DBConnectionError
715 * @return bool
716 */
717 private function reportConnectionError() {
718 $conn = $this->mErrorConnection; // The connection which caused the error
719
720 if ( !is_object( $conn ) ) {
721 // No last connection, probably due to all servers being too busy
722 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
723
724 // If all servers were busy, mLastError will contain something sensible
725 throw new DBConnectionError( null, $this->mLastError );
726 } else {
727 $server = $conn->getProperty( 'mServer' );
728 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
729 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
730 }
731 return false; /* not reached */
732 }
733
734 /**
735 * @return int
736 */
737 function getWriterIndex() {
738 return 0;
739 }
740
741 /**
742 * Returns true if the specified index is a valid server index
743 *
744 * @param $i
745 * @return bool
746 */
747 function haveIndex( $i ) {
748 return array_key_exists( $i, $this->mServers );
749 }
750
751 /**
752 * Returns true if the specified index is valid and has non-zero load
753 *
754 * @param $i
755 * @return bool
756 */
757 function isNonZeroLoad( $i ) {
758 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
759 }
760
761 /**
762 * Get the number of defined servers (not the number of open connections)
763 *
764 * @return int
765 */
766 function getServerCount() {
767 return count( $this->mServers );
768 }
769
770 /**
771 * Get the host name or IP address of the server with the specified index
772 * Prefer a readable name if available.
773 * @param $i
774 * @return string
775 */
776 function getServerName( $i ) {
777 if ( isset( $this->mServers[$i]['hostName'] ) ) {
778 return $this->mServers[$i]['hostName'];
779 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
780 return $this->mServers[$i]['host'];
781 } else {
782 return '';
783 }
784 }
785
786 /**
787 * Return the server info structure for a given index, or false if the index is invalid.
788 * @param $i
789 * @return bool
790 */
791 function getServerInfo( $i ) {
792 if ( isset( $this->mServers[$i] ) ) {
793 return $this->mServers[$i];
794 } else {
795 return false;
796 }
797 }
798
799 /**
800 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
801 * @param $i
802 * @param $serverInfo
803 */
804 function setServerInfo( $i, $serverInfo ) {
805 $this->mServers[$i] = $serverInfo;
806 }
807
808 /**
809 * Get the current master position for chronology control purposes
810 * @return mixed
811 */
812 function getMasterPos() {
813 # If this entire request was served from a slave without opening a connection to the
814 # master (however unlikely that may be), then we can fetch the position from the slave.
815 $masterConn = $this->getAnyOpenConnection( 0 );
816 if ( !$masterConn ) {
817 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
818 $conn = $this->getAnyOpenConnection( $i );
819 if ( $conn ) {
820 wfDebug( "Master pos fetched from slave\n" );
821 return $conn->getSlavePos();
822 }
823 }
824 } else {
825 wfDebug( "Master pos fetched from master\n" );
826 return $masterConn->getMasterPos();
827 }
828 return false;
829 }
830
831 /**
832 * Close all open connections
833 */
834 function closeAll() {
835 foreach ( $this->mConns as $conns2 ) {
836 foreach ( $conns2 as $conns3 ) {
837 foreach ( $conns3 as $conn ) {
838 $conn->close();
839 }
840 }
841 }
842 $this->mConns = array(
843 'local' => array(),
844 'foreignFree' => array(),
845 'foreignUsed' => array(),
846 );
847 }
848
849 /**
850 * Deprecated function, typo in function name
851 *
852 * @deprecated in 1.18
853 * @param $conn
854 */
855 function closeConnecton( $conn ) {
856 wfDeprecated( __METHOD__, '1.18' );
857 $this->closeConnection( $conn );
858 }
859
860 /**
861 * Close a connection
862 * Using this function makes sure the LoadBalancer knows the connection is closed.
863 * If you use $conn->close() directly, the load balancer won't update its state.
864 * @param $conn DatabaseBase
865 */
866 function closeConnection( $conn ) {
867 $done = false;
868 foreach ( $this->mConns as $i1 => $conns2 ) {
869 foreach ( $conns2 as $i2 => $conns3 ) {
870 foreach ( $conns3 as $i3 => $candidateConn ) {
871 if ( $conn === $candidateConn ) {
872 $conn->close();
873 unset( $this->mConns[$i1][$i2][$i3] );
874 $done = true;
875 break;
876 }
877 }
878 }
879 }
880 if ( !$done ) {
881 $conn->close();
882 }
883 }
884
885 /**
886 * Commit transactions on all open connections
887 */
888 function commitAll() {
889 foreach ( $this->mConns as $conns2 ) {
890 foreach ( $conns2 as $conns3 ) {
891 foreach ( $conns3 as $conn ) {
892 if ( $conn->trxLevel() ) {
893 $conn->commit( __METHOD__, 'flush' );
894 }
895 }
896 }
897 }
898 }
899
900 /**
901 * Issue COMMIT only on master, only if queries were done on connection
902 */
903 function commitMasterChanges() {
904 // Always 0, but who knows.. :)
905 $masterIndex = $this->getWriterIndex();
906 foreach ( $this->mConns as $conns2 ) {
907 if ( empty( $conns2[$masterIndex] ) ) {
908 continue;
909 }
910 foreach ( $conns2[$masterIndex] as $conn ) {
911 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
912 $conn->commit( __METHOD__, 'flush' );
913 }
914 }
915 }
916 }
917
918 /**
919 * @param $value null
920 * @return Mixed
921 */
922 function waitTimeout( $value = null ) {
923 return wfSetVar( $this->mWaitTimeout, $value );
924 }
925
926 /**
927 * @return bool
928 */
929 function getLaggedSlaveMode() {
930 return $this->mLaggedSlaveMode;
931 }
932
933 /**
934 * Disables/enables lag checks
935 * @param $mode null
936 * @return bool
937 */
938 function allowLagged( $mode = null ) {
939 if ( $mode === null ) {
940 return $this->mAllowLagged;
941 }
942 $this->mAllowLagged = $mode;
943 return $this->mAllowLagged;
944 }
945
946 /**
947 * @return bool
948 */
949 function pingAll() {
950 $success = true;
951 foreach ( $this->mConns as $conns2 ) {
952 foreach ( $conns2 as $conns3 ) {
953 foreach ( $conns3 as $conn ) {
954 if ( !$conn->ping() ) {
955 $success = false;
956 }
957 }
958 }
959 }
960 return $success;
961 }
962
963 /**
964 * Call a function with each open connection object
965 * @param $callback
966 * @param array $params
967 */
968 function forEachOpenConnection( $callback, $params = array() ) {
969 foreach ( $this->mConns as $conns2 ) {
970 foreach ( $conns2 as $conns3 ) {
971 foreach ( $conns3 as $conn ) {
972 $mergedParams = array_merge( array( $conn ), $params );
973 call_user_func_array( $callback, $mergedParams );
974 }
975 }
976 }
977 }
978
979 /**
980 * Get the hostname and lag time of the most-lagged slave.
981 * This is useful for maintenance scripts that need to throttle their updates.
982 * May attempt to open connections to slaves on the default DB. If there is
983 * no lag, the maximum lag will be reported as -1.
984 *
985 * @param string $wiki Wiki ID, or false for the default database
986 *
987 * @return array ( host, max lag, index of max lagged host )
988 */
989 function getMaxLag( $wiki = false ) {
990 $maxLag = -1;
991 $host = '';
992 $maxIndex = 0;
993 if ( $this->getServerCount() > 1 ) { // no replication = no lag
994 foreach ( $this->mServers as $i => $conn ) {
995 $conn = false;
996 if ( $wiki === false ) {
997 $conn = $this->getAnyOpenConnection( $i );
998 }
999 if ( !$conn ) {
1000 $conn = $this->openConnection( $i, $wiki );
1001 }
1002 if ( !$conn ) {
1003 continue;
1004 }
1005 $lag = $conn->getLag();
1006 if ( $lag > $maxLag ) {
1007 $maxLag = $lag;
1008 $host = $this->mServers[$i]['host'];
1009 $maxIndex = $i;
1010 }
1011 }
1012 }
1013 return array( $host, $maxLag, $maxIndex );
1014 }
1015
1016 /**
1017 * Get lag time for each server
1018 * Results are cached for a short time in memcached, and indefinitely in the process cache
1019 *
1020 * @param $wiki
1021 *
1022 * @return array
1023 */
1024 function getLagTimes( $wiki = false ) {
1025 # Try process cache
1026 if ( isset( $this->mLagTimes ) ) {
1027 return $this->mLagTimes;
1028 }
1029 if ( $this->getServerCount() == 1 ) {
1030 # No replication
1031 $this->mLagTimes = array( 0 => 0 );
1032 } else {
1033 # Send the request to the load monitor
1034 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
1035 array_keys( $this->mServers ), $wiki );
1036 }
1037 return $this->mLagTimes;
1038 }
1039
1040 /**
1041 * Get the lag in seconds for a given connection, or zero if this load
1042 * balancer does not have replication enabled.
1043 *
1044 * This should be used in preference to Database::getLag() in cases where
1045 * replication may not be in use, since there is no way to determine if
1046 * replication is in use at the connection level without running
1047 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1048 * function instead of Database::getLag() avoids a fatal error in this
1049 * case on many installations.
1050 *
1051 * @param $conn DatabaseBase
1052 *
1053 * @return int
1054 */
1055 function safeGetLag( $conn ) {
1056 if ( $this->getServerCount() == 1 ) {
1057 return 0;
1058 } else {
1059 return $conn->getLag();
1060 }
1061 }
1062
1063 /**
1064 * Clear the cache for getLagTimes
1065 */
1066 function clearLagTimeCache() {
1067 $this->mLagTimes = null;
1068 }
1069 }