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