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