Fix for r79231: $dbname was missing
[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 $type = $server['type'];
624 $host = $server['host'];
625 $user = $server['user'];
626 $password = $server['password'];
627 $flags = $server['flags'];
628 $dbname = $server['dbname'];
629
630 if ( $dbNameOverride !== false ) {
631 $dbname = $dbNameOverride;
632 }
633
634 # Get class for this database type
635 $class = 'Database' . ucfirst( $type );
636
637 # Create object
638 wfDebug( "Connecting to $host $dbname...\n" );
639 $db = new $class( $host, $user, $password, $dbname, $flags );
640 if ( $db->isOpen() ) {
641 wfDebug( "Connected to $host $dbname.\n" );
642 } else {
643 wfDebug( "Connection failed to $host $dbname.\n" );
644 }
645 $db->setLBInfo( $server );
646 if ( isset( $server['fakeSlaveLag'] ) ) {
647 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
648 }
649 if ( isset( $server['fakeMaster'] ) ) {
650 $db->setFakeMaster( true );
651 }
652 return $db;
653 }
654
655 function reportConnectionError( &$conn ) {
656 wfProfileIn( __METHOD__ );
657
658 if ( !is_object( $conn ) ) {
659 // No last connection, probably due to all servers being too busy
660 wfLogDBError( "LB failure with no last connection\n" );
661 $conn = new Database;
662 // If all servers were busy, mLastError will contain something sensible
663 throw new DBConnectionError( $conn, $this->mLastError );
664 } else {
665 $server = $conn->getProperty( 'mServer' );
666 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
667 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
668 }
669 wfProfileOut( __METHOD__ );
670 }
671
672 function getWriterIndex() {
673 return 0;
674 }
675
676 /**
677 * Returns true if the specified index is a valid server index
678 */
679 function haveIndex( $i ) {
680 return array_key_exists( $i, $this->mServers );
681 }
682
683 /**
684 * Returns true if the specified index is valid and has non-zero load
685 */
686 function isNonZeroLoad( $i ) {
687 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
688 }
689
690 /**
691 * Get the number of defined servers (not the number of open connections)
692 */
693 function getServerCount() {
694 return count( $this->mServers );
695 }
696
697 /**
698 * Get the host name or IP address of the server with the specified index
699 * Prefer a readable name if available.
700 */
701 function getServerName( $i ) {
702 if ( isset( $this->mServers[$i]['hostName'] ) ) {
703 return $this->mServers[$i]['hostName'];
704 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
705 return $this->mServers[$i]['host'];
706 } else {
707 return '';
708 }
709 }
710
711 /**
712 * Return the server info structure for a given index, or false if the index is invalid.
713 */
714 function getServerInfo( $i ) {
715 if ( isset( $this->mServers[$i] ) ) {
716 return $this->mServers[$i];
717 } else {
718 return false;
719 }
720 }
721
722 /**
723 * Get the current master position for chronology control purposes
724 * @return mixed
725 */
726 function getMasterPos() {
727 # If this entire request was served from a slave without opening a connection to the
728 # master (however unlikely that may be), then we can fetch the position from the slave.
729 $masterConn = $this->getAnyOpenConnection( 0 );
730 if ( !$masterConn ) {
731 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
732 $conn = $this->getAnyOpenConnection( $i );
733 if ( $conn ) {
734 wfDebug( "Master pos fetched from slave\n" );
735 return $conn->getSlavePos();
736 }
737 }
738 } else {
739 wfDebug( "Master pos fetched from master\n" );
740 return $masterConn->getMasterPos();
741 }
742 return false;
743 }
744
745 /**
746 * Close all open connections
747 */
748 function closeAll() {
749 foreach ( $this->mConns as $conns2 ) {
750 foreach ( $conns2 as $conns3 ) {
751 foreach ( $conns3 as $conn ) {
752 $conn->close();
753 }
754 }
755 }
756 $this->mConns = array(
757 'local' => array(),
758 'foreignFree' => array(),
759 'foreignUsed' => array(),
760 );
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 */
768 function closeConnecton( $conn ) {
769 $done = false;
770 foreach ( $this->mConns as $i1 => $conns2 ) {
771 foreach ( $conns2 as $i2 => $conns3 ) {
772 foreach ( $conns3 as $i3 => $candidateConn ) {
773 if ( $conn === $candidateConn ) {
774 $conn->close();
775 unset( $this->mConns[$i1][$i2][$i3] );
776 $done = true;
777 break;
778 }
779 }
780 }
781 }
782 if ( !$done ) {
783 $conn->close();
784 }
785 }
786
787 /**
788 * Commit transactions on all open connections
789 */
790 function commitAll() {
791 foreach ( $this->mConns as $conns2 ) {
792 foreach ( $conns2 as $conns3 ) {
793 foreach ( $conns3 as $conn ) {
794 $conn->commit();
795 }
796 }
797 }
798 }
799
800 /* Issue COMMIT only on master, only if queries were done on connection */
801 function commitMasterChanges() {
802 // Always 0, but who knows.. :)
803 $masterIndex = $this->getWriterIndex();
804 foreach ( $this->mConns as $conns2 ) {
805 if ( empty( $conns2[$masterIndex] ) ) {
806 continue;
807 }
808 foreach ( $conns2[$masterIndex] as $conn ) {
809 if ( $conn->doneWrites() ) {
810 $conn->commit();
811 }
812 }
813 }
814 }
815
816 function waitTimeout( $value = null ) {
817 return wfSetVar( $this->mWaitTimeout, $value );
818 }
819
820 function getLaggedSlaveMode() {
821 return $this->mLaggedSlaveMode;
822 }
823
824 /* Disables/enables lag checks */
825 function allowLagged($mode=null) {
826 if ($mode===null)
827 return $this->mAllowLagged;
828 $this->mAllowLagged=$mode;
829 }
830
831 function pingAll() {
832 $success = true;
833 foreach ( $this->mConns as $conns2 ) {
834 foreach ( $conns2 as $conns3 ) {
835 foreach ( $conns3 as $conn ) {
836 if ( !$conn->ping() ) {
837 $success = false;
838 }
839 }
840 }
841 }
842 return $success;
843 }
844
845 /**
846 * Call a function with each open connection object
847 */
848 function forEachOpenConnection( $callback, $params = array() ) {
849 foreach ( $this->mConns as $conns2 ) {
850 foreach ( $conns2 as $conns3 ) {
851 foreach ( $conns3 as $conn ) {
852 $mergedParams = array_merge( array( $conn ), $params );
853 call_user_func_array( $callback, $mergedParams );
854 }
855 }
856 }
857 }
858
859 /**
860 * Get the hostname and lag time of the most-lagged slave.
861 * This is useful for maintenance scripts that need to throttle their updates.
862 * May attempt to open connections to slaves on the default DB.
863 * @param $wiki string Wiki ID, or false for the default database
864 */
865 function getMaxLag( $wiki = false ) {
866 $maxLag = -1;
867 $host = '';
868 foreach ( $this->mServers as $i => $conn ) {
869 $conn = false;
870 if ( $wiki === false ) {
871 $conn = $this->getAnyOpenConnection( $i );
872 }
873 if ( !$conn ) {
874 $conn = $this->openConnection( $i, $wiki );
875 }
876 if ( !$conn ) {
877 continue;
878 }
879 $lag = $conn->getLag();
880 if ( $lag > $maxLag ) {
881 $maxLag = $lag;
882 $host = $this->mServers[$i]['host'];
883 }
884 }
885 return array( $host, $maxLag );
886 }
887
888 /**
889 * Get lag time for each server
890 * Results are cached for a short time in memcached, and indefinitely in the process cache
891 */
892 function getLagTimes( $wiki = false ) {
893 # Try process cache
894 if ( isset( $this->mLagTimes ) ) {
895 return $this->mLagTimes;
896 }
897 # No, send the request to the load monitor
898 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
899 return $this->mLagTimes;
900 }
901
902 /**
903 * Clear the cache for getLagTimes
904 */
905 function clearLagTimeCache() {
906 $this->mLagTimes = null;
907 }
908 }