Revert some recent ES-related changes -- they made behavior much worse when we encoun...
[lhc/web/wiklou.git] / includes / db / LoadBalancer.php
1 <?php
2 /**
3 * @file
4 * @ingroup Database
5 */
6
7 /**
8 * Database load balancing object
9 *
10 * @todo document
11 * @ingroup Database
12 */
13 class LoadBalancer {
14 /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
15 /* private */ var $mFailFunction, $mErrorConnection;
16 /* private */ var $mReadIndex, $mAllowLagged;
17 /* private */ var $mWaitForPos, $mWaitTimeout;
18 /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
19 /* private */ var $mParentInfo, $mLagTimes;
20 /* private */ var $mLoadMonitorClass, $mLoadMonitor;
21
22 /**
23 * @param array $params Array with keys:
24 * servers Required. Array of server info structures.
25 * failFunction Deprecated, use exceptions instead.
26 * masterWaitTimeout Replication lag wait timeout
27 * loadMonitor Name of a class used to fetch server lag and load.
28 */
29 function __construct( $params )
30 {
31 if ( !isset( $params['servers'] ) ) {
32 throw new MWException( __CLASS__.': missing servers parameter' );
33 }
34 $this->mServers = $params['servers'];
35
36 if ( isset( $params['failFunction'] ) ) {
37 $this->mFailFunction = $params['failFunction'];
38 } else {
39 $this->mFailFunction = false;
40 }
41 if ( isset( $params['waitTimeout'] ) ) {
42 $this->mWaitTimeout = $params['waitTimeout'];
43 } else {
44 $this->mWaitTimeout = 10;
45 }
46
47 $this->mReadIndex = -1;
48 $this->mWriteIndex = -1;
49 $this->mConns = array(
50 'local' => array(),
51 'foreignUsed' => array(),
52 'foreignFree' => array() );
53 $this->mLoads = array();
54 $this->mWaitForPos = false;
55 $this->mLaggedSlaveMode = false;
56 $this->mErrorConnection = false;
57 $this->mAllowLag = false;
58 $this->mLoadMonitorClass = isset( $params['loadMonitor'] )
59 ? $params['loadMonitor'] : 'LoadMonitor_MySQL';
60
61 foreach( $params['servers'] as $i => $server ) {
62 $this->mLoads[$i] = $server['load'];
63 if ( isset( $server['groupLoads'] ) ) {
64 foreach ( $server['groupLoads'] as $group => $ratio ) {
65 if ( !isset( $this->mGroupLoads[$group] ) ) {
66 $this->mGroupLoads[$group] = array();
67 }
68 $this->mGroupLoads[$group][$i] = $ratio;
69 }
70 }
71 }
72 }
73
74 static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
75 {
76 return new LoadBalancer( $servers, $failFunction, $waitTimeout );
77 }
78
79 /**
80 * Get a LoadMonitor instance
81 */
82 function getLoadMonitor() {
83 if ( !isset( $this->mLoadMonitor ) ) {
84 $class = $this->mLoadMonitorClass;
85 $this->mLoadMonitor = new $class( $this );
86 }
87 return $this->mLoadMonitor;
88 }
89
90 /**
91 * Get or set arbitrary data used by the parent object, usually an LBFactory
92 */
93 function parentInfo( $x = null ) {
94 return wfSetVar( $this->mParentInfo, $x );
95 }
96
97 /**
98 * Given an array of non-normalised probabilities, this function will select
99 * an element and return the appropriate key
100 */
101 function pickRandom( $weights )
102 {
103 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
104 return false;
105 }
106
107 $sum = array_sum( $weights );
108 if ( $sum == 0 ) {
109 # No loads on any of them
110 # In previous versions, this triggered an unweighted random selection,
111 # but this feature has been removed as of April 2006 to allow for strict
112 # separation of query groups.
113 return false;
114 }
115 $max = mt_getrandmax();
116 $rand = mt_rand(0, $max) / $max * $sum;
117
118 $sum = 0;
119 foreach ( $weights as $i => $w ) {
120 $sum += $w;
121 if ( $sum >= $rand ) {
122 break;
123 }
124 }
125 return $i;
126 }
127
128 function getRandomNonLagged( $loads, $wiki = false ) {
129 # Unset excessively lagged servers
130 $lags = $this->getLagTimes( $wiki );
131 foreach ( $lags as $i => $lag ) {
132 if ( $i != 0 && isset( $this->mServers[$i]['max lag'] ) ) {
133 if ( $lag === false ) {
134 wfDebug( "Server #$i is not replicating\n" );
135 unset( $loads[$i] );
136 } elseif ( $lag > $this->mServers[$i]['max lag'] ) {
137 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
138 unset( $loads[$i] );
139 }
140 }
141 }
142
143 # Find out if all the slaves with non-zero load are lagged
144 $sum = 0;
145 foreach ( $loads as $load ) {
146 $sum += $load;
147 }
148 if ( $sum == 0 ) {
149 # No appropriate DB servers except maybe the master and some slaves with zero load
150 # Do NOT use the master
151 # Instead, this function will return false, triggering read-only mode,
152 # and a lagged slave will be used instead.
153 return false;
154 }
155
156 if ( count( $loads ) == 0 ) {
157 return false;
158 }
159
160 #wfDebugLog( 'connect', var_export( $loads, true ) );
161
162 # Return a random representative of the remainder
163 return $this->pickRandom( $loads );
164 }
165
166 /**
167 * Get the index of the reader connection, which may be a slave
168 * This takes into account load ratios and lag times. It should
169 * always return a consistent index during a given invocation
170 *
171 * Side effect: opens connections to databases
172 */
173 function getReaderIndex( $group = false, $wiki = false ) {
174 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
175
176 # FIXME: For now, only go through all this for mysql databases
177 if ($wgDBtype != 'mysql') {
178 return $this->getWriterIndex();
179 }
180
181 if ( count( $this->mServers ) == 1 ) {
182 # Skip the load balancing if there's only one server
183 return 0;
184 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
185 # Shortcut if generic reader exists already
186 return $this->mReadIndex;
187 }
188
189 wfProfileIn( __METHOD__ );
190
191 $totalElapsed = 0;
192
193 # convert from seconds to microseconds
194 $timeout = $wgDBClusterTimeout * 1e6;
195
196 # Find the relevant load array
197 if ( $group !== false ) {
198 if ( isset( $this->mGroupLoads[$group] ) ) {
199 $nonErrorLoads = $this->mGroupLoads[$group];
200 } else {
201 # No loads for this group, return false and the caller can use some other group
202 wfDebug( __METHOD__.": no loads for group $group\n" );
203 wfProfileOut( __METHOD__ );
204 return false;
205 }
206 } else {
207 $nonErrorLoads = $this->mLoads;
208 }
209
210 if ( !$nonErrorLoads ) {
211 throw new MWException( "Empty server array given to LoadBalancer" );
212 }
213
214 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
215 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
216
217 $i = false;
218 $found = false;
219 $laggedSlaveMode = false;
220
221 # First try quickly looking through the available servers for a server that
222 # meets our criteria
223 do {
224 $totalThreadsConnected = 0;
225 $overloadedServers = 0;
226 $currentLoads = $nonErrorLoads;
227 while ( count( $currentLoads ) ) {
228 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
229 $i = $this->pickRandom( $currentLoads );
230 } else {
231 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
232 if ( $i === false && count( $currentLoads ) != 0 ) {
233 # All slaves lagged. Switch to read-only mode
234 $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
235 $i = $this->pickRandom( $currentLoads );
236 $laggedSlaveMode = true;
237 }
238 }
239
240 if ( $i === false ) {
241 # pickRandom() returned false
242 # This is permanent and means the configuration or the load monitor
243 # wants us to return false.
244 wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
245 wfProfileOut( __METHOD__ );
246 return false;
247 }
248
249 wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
250 $conn = $this->openConnection( $i, $wiki );
251
252 if ( !$conn ) {
253 wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
254 unset( $nonErrorLoads[$i] );
255 unset( $currentLoads[$i] );
256 continue;
257 }
258
259 // Perform post-connection backoff
260 $threshold = isset( $this->mServers[$i]['max threads'] )
261 ? $this->mServers[$i]['max threads'] : false;
262 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
263
264 // Decrement reference counter, we are finished with this connection.
265 // It will be incremented for the caller later.
266 if ( $wiki !== false ) {
267 $this->reuseConnection( $conn );
268 }
269
270 if ( $backoff ) {
271 # Post-connection overload, don't use this server for now
272 $totalThreadsConnected += $backoff;
273 $overloadedServers++;
274 unset( $currentLoads[$i] );
275 } else {
276 # Return this server
277 break 2;
278 }
279 }
280
281 # No server found yet
282 $i = false;
283
284 # If all servers were down, quit now
285 if ( !count( $nonErrorLoads ) ) {
286 wfDebugLog( 'connect', "All servers down\n" );
287 break;
288 }
289
290 # Some servers must have been overloaded
291 if ( $overloadedServers == 0 ) {
292 throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
293 }
294 # Back off for a while
295 # Scale the sleep time by the number of connected threads, to produce a
296 # roughly constant global poll rate
297 $avgThreads = $totalThreadsConnected / $overloadedServers;
298 $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
299 } while ( $totalElapsed < $timeout );
300
301 if ( $totalElapsed >= $timeout ) {
302 wfDebugLog( 'connect', "All servers busy\n" );
303 $this->mErrorConnection = false;
304 $this->mLastError = 'All servers busy';
305 }
306
307 if ( $i !== false ) {
308 # Slave connection successful
309 # Wait for the session master pos for a short time
310 if ( $this->mWaitForPos && $i > 0 ) {
311 if ( !$this->doWait( $i ) ) {
312 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
313 }
314 }
315 if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
316 $this->mReadIndex = $i;
317 }
318 }
319 wfProfileOut( __METHOD__ );
320 return $i;
321 }
322
323 /**
324 * Wait for a specified number of microseconds, and return the period waited
325 */
326 function sleep( $t ) {
327 wfProfileIn( __METHOD__ );
328 wfDebug( __METHOD__.": waiting $t us\n" );
329 usleep( $t );
330 wfProfileOut( __METHOD__ );
331 return $t;
332 }
333
334 /**
335 * Get a random server to use in a query group
336 * @deprecated use getReaderIndex
337 */
338 function getGroupIndex( $group ) {
339 return $this->getReaderIndex( $group );
340 }
341
342 /**
343 * Set the master wait position
344 * If a DB_SLAVE connection has been opened already, waits
345 * Otherwise sets a variable telling it to wait if such a connection is opened
346 */
347 public function waitFor( $pos ) {
348 wfProfileIn( __METHOD__ );
349 $this->mWaitForPos = $pos;
350 $i = $this->mReadIndex;
351
352 if ( $i > 0 ) {
353 if ( !$this->doWait( $i ) ) {
354 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
355 $this->mLaggedSlaveMode = true;
356 }
357 }
358 wfProfileOut( __METHOD__ );
359 }
360
361 /**
362 * Get any open connection to a given server index, local or foreign
363 * Returns false if there is no connection open
364 */
365 function getAnyOpenConnection( $i ) {
366 foreach ( $this->mConns as $type => $conns ) {
367 if ( !empty( $conns[$i] ) ) {
368 return reset( $conns[$i] );
369 }
370 }
371 return false;
372 }
373
374 /**
375 * Wait for a given slave to catch up to the master pos stored in $this
376 */
377 function doWait( $index ) {
378 # Find a connection to wait on
379 $conn = $this->getAnyOpenConnection( $index );
380 if ( !$conn ) {
381 wfDebug( __METHOD__ . ": no connection open\n" );
382 return false;
383 }
384
385 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
386 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
387
388 if ( $result == -1 || is_null( $result ) ) {
389 # Timed out waiting for slave, use master instead
390 wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
391 return false;
392 } else {
393 wfDebug( __METHOD__.": Done\n" );
394 return true;
395 }
396 }
397
398 /**
399 * Get a connection by index
400 * This is the main entry point for this class.
401 */
402 public function &getConnection( $i, $groups = array(), $wiki = false ) {
403 global $wgDBtype;
404 wfProfileIn( __METHOD__ );
405
406 if ( $wiki === wfWikiID() ) {
407 $wiki = false;
408 }
409
410 # Query groups
411 if ( $i == DB_MASTER ) {
412 $i = $this->getWriterIndex();
413 } elseif ( !is_array( $groups ) ) {
414 $groupIndex = $this->getReaderIndex( $groups, $wiki );
415 if ( $groupIndex !== false ) {
416 $serverName = $this->getServerName( $groupIndex );
417 wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
418 $i = $groupIndex;
419 }
420 } else {
421 foreach ( $groups as $group ) {
422 $groupIndex = $this->getReaderIndex( $group, $wiki );
423 if ( $groupIndex !== false ) {
424 $serverName = $this->getServerName( $groupIndex );
425 wfDebug( __METHOD__.": using server $serverName for group $group\n" );
426 $i = $groupIndex;
427 break;
428 }
429 }
430 }
431
432 # Operation-based index
433 if ( $i == DB_SLAVE ) {
434 $i = $this->getReaderIndex( false, $wiki );
435 } elseif ( $i == DB_LAST ) {
436 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
437 }
438 # Couldn't find a working server in getReaderIndex()?
439 if ( $i === false ) {
440 $this->reportConnectionError( $this->mErrorConnection );
441 }
442
443 # Now we have an explicit index into the servers array
444 $conn = $this->openConnection( $i, $wiki );
445 if ( !$conn ) {
446 $this->reportConnectionError( $this->mErrorConnection );
447 }
448
449 wfProfileOut( __METHOD__ );
450 return $conn;
451 }
452
453 /**
454 * Mark a foreign connection as being available for reuse under a different
455 * DB name or prefix. This mechanism is reference-counted, and must be called
456 * the same number of times as getConnection() to work.
457 */
458 public function reuseConnection( $conn ) {
459 $serverIndex = $conn->getLBInfo('serverIndex');
460 $refCount = $conn->getLBInfo('foreignPoolRefCount');
461 $dbName = $conn->getDBname();
462 $prefix = $conn->tablePrefix();
463 if ( strval( $prefix ) !== '' ) {
464 $wiki = "$dbName-$prefix";
465 } else {
466 $wiki = $dbName;
467 }
468 if ( $serverIndex === null || $refCount === null ) {
469 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
470 /**
471 * This can happen in code like:
472 * foreach ( $dbs as $db ) {
473 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
474 * ...
475 * $lb->reuseConnection( $conn );
476 * }
477 * When a connection to the local DB is opened in this way, reuseConnection()
478 * should be ignored
479 */
480 return;
481 }
482 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
483 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
484 }
485 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
486 if ( $refCount <= 0 ) {
487 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
488 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
489 wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
490 } else {
491 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
492 }
493 }
494
495 /**
496 * Open a connection to the server given by the specified index
497 * Index must be an actual index into the array.
498 * If the server is already open, returns it.
499 *
500 * On error, returns false, and the connection which caused the
501 * error will be available via $this->mErrorConnection.
502 *
503 * @param integer $i Server index
504 * @param string $wiki Wiki ID to open
505 * @return Database
506 *
507 * @access private
508 */
509 function openConnection( $i, $wiki = false ) {
510 wfProfileIn( __METHOD__ );
511 if ( $wiki !== false ) {
512 $conn = $this->openForeignConnection( $i, $wiki );
513 wfProfileOut( __METHOD__);
514 return $conn;
515 }
516 if ( isset( $this->mConns['local'][$i][0] ) ) {
517 $conn = $this->mConns['local'][$i][0];
518 } else {
519 $server = $this->mServers[$i];
520 $server['serverIndex'] = $i;
521 $conn = $this->reallyOpenConnection( $server );
522 if ( $conn->isOpen() ) {
523 $this->mConns['local'][$i][0] = $conn;
524 } else {
525 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
526 $this->mErrorConnection = $conn;
527 $conn = false;
528 }
529 }
530 wfProfileOut( __METHOD__ );
531 return $conn;
532 }
533
534 /**
535 * Open a connection to a foreign DB, or return one if it is already open.
536 *
537 * Increments a reference count on the returned connection which locks the
538 * connection to the requested wiki. This reference count can be
539 * decremented by calling reuseConnection().
540 *
541 * If a connection is open to the appropriate server already, but with the wrong
542 * database, it will be switched to the right database and returned, as long as
543 * it has been freed first with reuseConnection().
544 *
545 * On error, returns false, and the connection which caused the
546 * error will be available via $this->mErrorConnection.
547 *
548 * @param integer $i Server index
549 * @param string $wiki Wiki ID to open
550 * @return Database
551 */
552 function openForeignConnection( $i, $wiki ) {
553 wfProfileIn(__METHOD__);
554 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
555 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
556 // Reuse an already-used connection
557 $conn = $this->mConns['foreignUsed'][$i][$wiki];
558 wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
559 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
560 // Reuse a free connection for the same wiki
561 $conn = $this->mConns['foreignFree'][$i][$wiki];
562 unset( $this->mConns['foreignFree'][$i][$wiki] );
563 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
564 wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
565 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
566 // Reuse a connection from another wiki
567 $conn = reset( $this->mConns['foreignFree'][$i] );
568 $oldWiki = key( $this->mConns['foreignFree'][$i] );
569
570 if ( !$conn->selectDB( $dbName ) ) {
571 global $wguname;
572 $this->mLastError = "Error selecting database $dbName on server " .
573 $conn->getServer() . " from client host {$wguname['nodename']}\n";
574 $this->mErrorConnection = $conn;
575 $conn = false;
576 } else {
577 $conn->tablePrefix( $prefix );
578 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
579 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
580 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
581 }
582 } else {
583 // Open a new connection
584 $server = $this->mServers[$i];
585 $server['serverIndex'] = $i;
586 $server['foreignPoolRefCount'] = 0;
587 $conn = $this->reallyOpenConnection( $server, $dbName );
588 if ( !$conn->isOpen() ) {
589 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
590 $this->mErrorConnection = $conn;
591 $conn = false;
592 } else {
593 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
594 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
595 }
596 }
597
598 // Increment reference count
599 if ( $conn ) {
600 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
601 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
602 }
603 wfProfileOut(__METHOD__);
604 return $conn;
605 }
606
607 /**
608 * Test if the specified index represents an open connection
609 * @access private
610 */
611 function isOpen( $index ) {
612 if( !is_integer( $index ) ) {
613 return false;
614 }
615 return (bool)$this->getAnyOpenConnection( $index );
616 }
617
618 /**
619 * Really opens a connection. Uncached.
620 * Returns a Database object whether or not the connection was successful.
621 * @access private
622 */
623 function reallyOpenConnection( $server, $dbNameOverride = false ) {
624 if( !is_array( $server ) ) {
625 throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
626 }
627
628 extract( $server );
629 if ( $dbNameOverride !== false ) {
630 $dbname = $dbNameOverride;
631 }
632
633 # Get class for this database type
634 $class = 'Database' . ucfirst( $type );
635
636 # Create object
637 wfDebug( "Connecting to $host $dbname...\n" );
638 $db = new $class( $host, $user, $password, $dbname, 1, $flags );
639 if ( $db->isOpen() ) {
640 wfDebug( "Connected\n" );
641 } else {
642 wfDebug( "Failed\n" );
643 }
644 $db->setLBInfo( $server );
645 if ( isset( $server['fakeSlaveLag'] ) ) {
646 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
647 }
648 if ( isset( $server['fakeMaster'] ) ) {
649 $db->setFakeMaster( true );
650 }
651 return $db;
652 }
653
654 function reportConnectionError( &$conn ) {
655 wfProfileIn( __METHOD__ );
656 # Prevent infinite recursion
657
658 static $reporting = false;
659 if ( !$reporting ) {
660 $reporting = true;
661 if ( !is_object( $conn ) ) {
662 // No last connection, probably due to all servers being too busy
663 $conn = new Database;
664 if ( $this->mFailFunction ) {
665 $conn->failFunction( $this->mFailFunction );
666 $conn->reportConnectionError( $this->mLastError );
667 } else {
668 // If all servers were busy, mLastError will contain something sensible
669 throw new DBConnectionError( $conn, $this->mLastError );
670 }
671 } else {
672 if ( $this->mFailFunction ) {
673 $conn->failFunction( $this->mFailFunction );
674 } else {
675 $conn->failFunction( false );
676 }
677 $server = $conn->getProperty( 'mServer' );
678 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
679 }
680 $reporting = false;
681 }
682 wfProfileOut( __METHOD__ );
683 }
684
685 function getWriterIndex() {
686 return 0;
687 }
688
689 /**
690 * Returns true if the specified index is a valid server index
691 */
692 function haveIndex( $i ) {
693 return array_key_exists( $i, $this->mServers );
694 }
695
696 /**
697 * Returns true if the specified index is valid and has non-zero load
698 */
699 function isNonZeroLoad( $i ) {
700 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
701 }
702
703 /**
704 * Get the number of defined servers (not the number of open connections)
705 */
706 function getServerCount() {
707 return count( $this->mServers );
708 }
709
710 /**
711 * Get the host name or IP address of the server with the specified index
712 * Prefer a readable name if available.
713 */
714 function getServerName( $i ) {
715 if ( isset( $this->mServers[$i]['hostName'] ) ) {
716 return $this->mServers[$i]['hostName'];
717 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
718 return $this->mServers[$i]['host'];
719 } else {
720 return '';
721 }
722 }
723
724 /**
725 * Return the server info structure for a given index, or false if the index is invalid.
726 */
727 function getServerInfo( $i ) {
728 if ( isset( $this->mServers[$i] ) ) {
729 return $this->mServers[$i];
730 } else {
731 return false;
732 }
733 }
734
735 /**
736 * Get the current master position for chronology control purposes
737 * @return mixed
738 */
739 function getMasterPos() {
740 # If this entire request was served from a slave without opening a connection to the
741 # master (however unlikely that may be), then we can fetch the position from the slave.
742 $masterConn = $this->getAnyOpenConnection( 0 );
743 if ( !$masterConn ) {
744 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
745 $conn = $this->getAnyOpenConnection( $i );
746 if ( $conn ) {
747 wfDebug( "Master pos fetched from slave\n" );
748 return $conn->getSlavePos();
749 }
750 }
751 } else {
752 wfDebug( "Master pos fetched from master\n" );
753 return $masterConn->getMasterPos();
754 }
755 return false;
756 }
757
758 /**
759 * Close all open connections
760 */
761 function closeAll() {
762 foreach ( $this->mConns as $conns2 ) {
763 foreach ( $conns2 as $conns3 ) {
764 foreach ( $conns3 as $conn ) {
765 $conn->close();
766 }
767 }
768 }
769 $this->mConns = array(
770 'local' => array(),
771 'foreignFree' => array(),
772 'foreignUsed' => array(),
773 );
774 }
775
776 /**
777 * Close a connection
778 * Using this function makes sure the LoadBalancer knows the connection is closed.
779 * If you use $conn->close() directly, the load balancer won't update its state.
780 */
781 function closeConnecton( $conn ) {
782 $done = false;
783 foreach ( $this->mConns as $i1 => $conns2 ) {
784 foreach ( $conns2 as $i2 => $conns3 ) {
785 foreach ( $conns3 as $i3 => $candidateConn ) {
786 if ( $conn === $candidateConn ) {
787 $conn->close();
788 unset( $this->mConns[$i1][$i2][$i3] );
789 $done = true;
790 break;
791 }
792 }
793 }
794 }
795 if ( !$done ) {
796 $conn->close();
797 }
798 }
799
800 /**
801 * Commit transactions on all open connections
802 */
803 function commitAll() {
804 foreach ( $this->mConns as $conns2 ) {
805 foreach ( $conns2 as $conns3 ) {
806 foreach ( $conns3 as $conn ) {
807 $conn->immediateCommit();
808 }
809 }
810 }
811 }
812
813 /* Issue COMMIT only on master, only if queries were done on connection */
814 function commitMasterChanges() {
815 // Always 0, but who knows.. :)
816 $masterIndex = $this->getWriterIndex();
817 foreach ( $this->mConns as $type => $conns2 ) {
818 if ( empty( $conns2[$masterIndex] ) ) {
819 continue;
820 }
821 foreach ( $conns2[$masterIndex] as $conn ) {
822 if ( $conn->lastQuery() != '' ) {
823 $conn->commit();
824 }
825 }
826 }
827 }
828
829 function waitTimeout( $value = NULL ) {
830 return wfSetVar( $this->mWaitTimeout, $value );
831 }
832
833 function getLaggedSlaveMode() {
834 return $this->mLaggedSlaveMode;
835 }
836
837 /* Disables/enables lag checks */
838 function allowLagged($mode=null) {
839 if ($mode===null)
840 return $this->mAllowLagged;
841 $this->mAllowLagged=$mode;
842 }
843
844 function pingAll() {
845 $success = true;
846 foreach ( $this->mConns as $conns2 ) {
847 foreach ( $conns2 as $conns3 ) {
848 foreach ( $conns3 as $conn ) {
849 if ( !$conn->ping() ) {
850 $success = false;
851 }
852 }
853 }
854 }
855 return $success;
856 }
857
858 /**
859 * Call a function with each open connection object
860 */
861 function forEachOpenConnection( $callback, $params = array() ) {
862 foreach ( $this->mConns as $conns2 ) {
863 foreach ( $conns2 as $conns3 ) {
864 foreach ( $conns3 as $conn ) {
865 $mergedParams = array_merge( array( $conn ), $params );
866 call_user_func_array( $callback, $mergedParams );
867 }
868 }
869 }
870 }
871
872 /**
873 * Get the hostname and lag time of the most-lagged slave.
874 * This is useful for maintenance scripts that need to throttle their updates.
875 * May attempt to open connections to slaves on the default DB.
876 */
877 function getMaxLag() {
878 $maxLag = -1;
879 $host = '';
880 foreach ( $this->mServers as $i => $conn ) {
881 $conn = $this->getAnyOpenConnection( $i );
882 if ( !$conn ) {
883 $conn = $this->openConnection( $i );
884 }
885 if ( !$conn ) {
886 continue;
887 }
888 $lag = $conn->getLag();
889 if ( $lag > $maxLag ) {
890 $maxLag = $lag;
891 $host = $this->mServers[$i]['host'];
892 }
893 }
894 return array( $host, $maxLag );
895 }
896
897 /**
898 * Get lag time for each server
899 * Results are cached for a short time in memcached, and indefinitely in the process cache
900 */
901 function getLagTimes( $wiki = false ) {
902 # Try process cache
903 if ( isset( $this->mLagTimes ) ) {
904 return $this->mLagTimes;
905 }
906 # No, send the request to the load monitor
907 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
908 return $this->mLagTimes;
909 }
910 }