Kill some crappy "failFunction" stuff, marked as old in r14625
[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 $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 * masterWaitTimeout Replication lag wait timeout
28 * loadMonitor Name of a class used to fetch server lag and load.
29 */
30 function __construct( $params )
31 {
32 if ( !isset( $params['servers'] ) ) {
33 throw new MWException( __CLASS__.': missing servers parameter' );
34 }
35 $this->mServers = $params['servers'];
36
37 if ( isset( $params['waitTimeout'] ) ) {
38 $this->mWaitTimeout = $params['waitTimeout'];
39 } else {
40 $this->mWaitTimeout = 10;
41 }
42
43 $this->mReadIndex = -1;
44 $this->mWriteIndex = -1;
45 $this->mConns = array(
46 'local' => array(),
47 'foreignUsed' => array(),
48 'foreignFree' => array() );
49 $this->mLoads = array();
50 $this->mWaitForPos = false;
51 $this->mLaggedSlaveMode = false;
52 $this->mErrorConnection = false;
53 $this->mAllowLag = false;
54 $this->mLoadMonitorClass = isset( $params['loadMonitor'] )
55 ? $params['loadMonitor'] : 'LoadMonitor_MySQL';
56
57 foreach( $params['servers'] as $i => $server ) {
58 $this->mLoads[$i] = $server['load'];
59 if ( isset( $server['groupLoads'] ) ) {
60 foreach ( $server['groupLoads'] as $group => $ratio ) {
61 if ( !isset( $this->mGroupLoads[$group] ) ) {
62 $this->mGroupLoads[$group] = array();
63 }
64 $this->mGroupLoads[$group][$i] = $ratio;
65 }
66 }
67 }
68 }
69
70 static function newFromParams( $servers, $waitTimeout = 10 )
71 {
72 return new LoadBalancer( $servers, $waitTimeout );
73 }
74
75 /**
76 * Get a LoadMonitor instance
77 */
78 function getLoadMonitor() {
79 if ( !isset( $this->mLoadMonitor ) ) {
80 $class = $this->mLoadMonitorClass;
81 $this->mLoadMonitor = new $class( $this );
82 }
83 return $this->mLoadMonitor;
84 }
85
86 /**
87 * Get or set arbitrary data used by the parent object, usually an LBFactory
88 */
89 function parentInfo( $x = null ) {
90 return wfSetVar( $this->mParentInfo, $x );
91 }
92
93 /**
94 * Given an array of non-normalised probabilities, this function will select
95 * an element and return the appropriate key
96 */
97 function pickRandom( $weights )
98 {
99 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
100 return false;
101 }
102
103 $sum = array_sum( $weights );
104 if ( $sum == 0 ) {
105 # No loads on any of them
106 # In previous versions, this triggered an unweighted random selection,
107 # but this feature has been removed as of April 2006 to allow for strict
108 # separation of query groups.
109 return false;
110 }
111 $max = mt_getrandmax();
112 $rand = mt_rand(0, $max) / $max * $sum;
113
114 $sum = 0;
115 foreach ( $weights as $i => $w ) {
116 $sum += $w;
117 if ( $sum >= $rand ) {
118 break;
119 }
120 }
121 return $i;
122 }
123
124 function getRandomNonLagged( $loads, $wiki = false ) {
125 # Unset excessively lagged servers
126 $lags = $this->getLagTimes( $wiki );
127 foreach ( $lags as $i => $lag ) {
128 if ( $i != 0 && isset( $this->mServers[$i]['max lag'] ) ) {
129 if ( $lag === false ) {
130 wfDebug( "Server #$i is not replicating\n" );
131 unset( $loads[$i] );
132 } elseif ( $lag > $this->mServers[$i]['max lag'] ) {
133 wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
134 unset( $loads[$i] );
135 }
136 }
137 }
138
139 # Find out if all the slaves with non-zero load are lagged
140 $sum = 0;
141 foreach ( $loads as $load ) {
142 $sum += $load;
143 }
144 if ( $sum == 0 ) {
145 # No appropriate DB servers except maybe the master and some slaves with zero load
146 # Do NOT use the master
147 # Instead, this function will return false, triggering read-only mode,
148 # and a lagged slave will be used instead.
149 return false;
150 }
151
152 if ( count( $loads ) == 0 ) {
153 return false;
154 }
155
156 #wfDebugLog( 'connect', var_export( $loads, true ) );
157
158 # Return a random representative of the remainder
159 return $this->pickRandom( $loads );
160 }
161
162 /**
163 * Get the index of the reader connection, which may be a slave
164 * This takes into account load ratios and lag times. It should
165 * always return a consistent index during a given invocation
166 *
167 * Side effect: opens connections to databases
168 */
169 function getReaderIndex( $group = false, $wiki = false ) {
170 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
171
172 # FIXME: For now, only go through all this for mysql databases
173 if ($wgDBtype != 'mysql') {
174 return $this->getWriterIndex();
175 }
176
177 if ( count( $this->mServers ) == 1 ) {
178 # Skip the load balancing if there's only one server
179 return 0;
180 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
181 # Shortcut if generic reader exists already
182 return $this->mReadIndex;
183 }
184
185 wfProfileIn( __METHOD__ );
186
187 $totalElapsed = 0;
188
189 # convert from seconds to microseconds
190 $timeout = $wgDBClusterTimeout * 1e6;
191
192 # Find the relevant load array
193 if ( $group !== false ) {
194 if ( isset( $this->mGroupLoads[$group] ) ) {
195 $nonErrorLoads = $this->mGroupLoads[$group];
196 } else {
197 # No loads for this group, return false and the caller can use some other group
198 wfDebug( __METHOD__.": no loads for group $group\n" );
199 wfProfileOut( __METHOD__ );
200 return false;
201 }
202 } else {
203 $nonErrorLoads = $this->mLoads;
204 }
205
206 if ( !$nonErrorLoads ) {
207 throw new MWException( "Empty server array given to LoadBalancer" );
208 }
209
210 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
211 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
212
213 $i = false;
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 $type => $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\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
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
670 // If all servers were busy, mLastError will contain something sensible
671 throw new DBConnectionError( $conn, $this->mLastError );
672 } else {
673
674 $server = $conn->getProperty( 'mServer' );
675 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
676 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
677 }
678 wfProfileOut( __METHOD__ );
679 }
680
681 function getWriterIndex() {
682 return 0;
683 }
684
685 /**
686 * Returns true if the specified index is a valid server index
687 */
688 function haveIndex( $i ) {
689 return array_key_exists( $i, $this->mServers );
690 }
691
692 /**
693 * Returns true if the specified index is valid and has non-zero load
694 */
695 function isNonZeroLoad( $i ) {
696 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
697 }
698
699 /**
700 * Get the number of defined servers (not the number of open connections)
701 */
702 function getServerCount() {
703 return count( $this->mServers );
704 }
705
706 /**
707 * Get the host name or IP address of the server with the specified index
708 * Prefer a readable name if available.
709 */
710 function getServerName( $i ) {
711 if ( isset( $this->mServers[$i]['hostName'] ) ) {
712 return $this->mServers[$i]['hostName'];
713 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
714 return $this->mServers[$i]['host'];
715 } else {
716 return '';
717 }
718 }
719
720 /**
721 * Return the server info structure for a given index, or false if the index is invalid.
722 */
723 function getServerInfo( $i ) {
724 if ( isset( $this->mServers[$i] ) ) {
725 return $this->mServers[$i];
726 } else {
727 return false;
728 }
729 }
730
731 /**
732 * Get the current master position for chronology control purposes
733 * @return mixed
734 */
735 function getMasterPos() {
736 # If this entire request was served from a slave without opening a connection to the
737 # master (however unlikely that may be), then we can fetch the position from the slave.
738 $masterConn = $this->getAnyOpenConnection( 0 );
739 if ( !$masterConn ) {
740 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
741 $conn = $this->getAnyOpenConnection( $i );
742 if ( $conn ) {
743 wfDebug( "Master pos fetched from slave\n" );
744 return $conn->getSlavePos();
745 }
746 }
747 } else {
748 wfDebug( "Master pos fetched from master\n" );
749 return $masterConn->getMasterPos();
750 }
751 return false;
752 }
753
754 /**
755 * Close all open connections
756 */
757 function closeAll() {
758 foreach ( $this->mConns as $conns2 ) {
759 foreach ( $conns2 as $conns3 ) {
760 foreach ( $conns3 as $conn ) {
761 $conn->close();
762 }
763 }
764 }
765 $this->mConns = array(
766 'local' => array(),
767 'foreignFree' => array(),
768 'foreignUsed' => array(),
769 );
770 }
771
772 /**
773 * Close a connection
774 * Using this function makes sure the LoadBalancer knows the connection is closed.
775 * If you use $conn->close() directly, the load balancer won't update its state.
776 */
777 function closeConnecton( $conn ) {
778 $done = false;
779 foreach ( $this->mConns as $i1 => $conns2 ) {
780 foreach ( $conns2 as $i2 => $conns3 ) {
781 foreach ( $conns3 as $i3 => $candidateConn ) {
782 if ( $conn === $candidateConn ) {
783 $conn->close();
784 unset( $this->mConns[$i1][$i2][$i3] );
785 $done = true;
786 break;
787 }
788 }
789 }
790 }
791 if ( !$done ) {
792 $conn->close();
793 }
794 }
795
796 /**
797 * Commit transactions on all open connections
798 */
799 function commitAll() {
800 foreach ( $this->mConns as $conns2 ) {
801 foreach ( $conns2 as $conns3 ) {
802 foreach ( $conns3 as $conn ) {
803 $conn->commit();
804 }
805 }
806 }
807 }
808
809 /* Issue COMMIT only on master, only if queries were done on connection */
810 function commitMasterChanges() {
811 // Always 0, but who knows.. :)
812 $masterIndex = $this->getWriterIndex();
813 foreach ( $this->mConns as $type => $conns2 ) {
814 if ( empty( $conns2[$masterIndex] ) ) {
815 continue;
816 }
817 foreach ( $conns2[$masterIndex] as $conn ) {
818 if ( $conn->doneWrites() ) {
819 $conn->commit();
820 }
821 }
822 }
823 }
824
825 function waitTimeout( $value = null ) {
826 return wfSetVar( $this->mWaitTimeout, $value );
827 }
828
829 function getLaggedSlaveMode() {
830 return $this->mLaggedSlaveMode;
831 }
832
833 /* Disables/enables lag checks */
834 function allowLagged($mode=null) {
835 if ($mode===null)
836 return $this->mAllowLagged;
837 $this->mAllowLagged=$mode;
838 }
839
840 function pingAll() {
841 $success = true;
842 foreach ( $this->mConns as $conns2 ) {
843 foreach ( $conns2 as $conns3 ) {
844 foreach ( $conns3 as $conn ) {
845 if ( !$conn->ping() ) {
846 $success = false;
847 }
848 }
849 }
850 }
851 return $success;
852 }
853
854 /**
855 * Call a function with each open connection object
856 */
857 function forEachOpenConnection( $callback, $params = array() ) {
858 foreach ( $this->mConns as $conns2 ) {
859 foreach ( $conns2 as $conns3 ) {
860 foreach ( $conns3 as $conn ) {
861 $mergedParams = array_merge( array( $conn ), $params );
862 call_user_func_array( $callback, $mergedParams );
863 }
864 }
865 }
866 }
867
868 /**
869 * Get the hostname and lag time of the most-lagged slave.
870 * This is useful for maintenance scripts that need to throttle their updates.
871 * May attempt to open connections to slaves on the default DB.
872 * @param $wiki string Wiki ID, or false for the default database
873 */
874 function getMaxLag( $wiki = false ) {
875 $maxLag = -1;
876 $host = '';
877 foreach ( $this->mServers as $i => $conn ) {
878 $conn = false;
879 if ( $wiki === false ) {
880 $conn = $this->getAnyOpenConnection( $i );
881 }
882 if ( !$conn ) {
883 $conn = $this->openConnection( $i, $wiki );
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
911 /**
912 * Clear the cache for getLagTimes
913 */
914 function clearLagTimeCache() {
915 $this->mLagTimes = null;
916 }
917 }