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