Followup r83558, r83555
[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 * Set the master wait position and wait for ALL slaves to catch up to it
344 */
345 public function waitForAll( $pos ) {
346 wfProfileIn( __METHOD__ );
347 $this->mWaitForPos = $pos;
348 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
349 $this->doWait( $i , true );
350 }
351 wfProfileOut( __METHOD__ );
352 }
353
354 /**
355 * Get any open connection to a given server index, local or foreign
356 * Returns false if there is no connection open
357 */
358 function getAnyOpenConnection( $i ) {
359 foreach ( $this->mConns as $conns ) {
360 if ( !empty( $conns[$i] ) ) {
361 return reset( $conns[$i] );
362 }
363 }
364 return false;
365 }
366
367 /**
368 * Wait for a given slave to catch up to the master pos stored in $this
369 */
370 function doWait( $index, $open = false ) {
371 # Find a connection to wait on
372 $conn = $this->getAnyOpenConnection( $index );
373 if ( !$conn ) {
374 if ( !$open ) {
375 wfDebug( __METHOD__ . ": no connection open\n" );
376 return false;
377 } else {
378 $conn = $this->openConnection( $index );
379 if ( !$conn ) {
380 wfDebug( __METHOD__ . ": failed to open connection\n" );
381 return false;
382 }
383 }
384 }
385
386 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
387 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
388
389 if ( $result == -1 || is_null( $result ) ) {
390 # Timed out waiting for slave, use master instead
391 wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
392 return false;
393 } else {
394 wfDebug( __METHOD__.": Done\n" );
395 return true;
396 }
397 }
398
399 /**
400 * Get a connection by index
401 * This is the main entry point for this class.
402 *
403 * @param $i Integer: server index
404 * @param $groups Array: query groups
405 * @param $wiki String: wiki ID
406 *
407 * @return DatabaseBase
408 */
409 public function &getConnection( $i, $groups = array(), $wiki = false ) {
410 wfProfileIn( __METHOD__ );
411
412 if ( $i == DB_LAST ) {
413 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
414 } elseif ( $i === null || $i === false ) {
415 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
416 }
417
418 if ( $wiki === wfWikiID() ) {
419 $wiki = false;
420 }
421
422 # Query groups
423 if ( $i == DB_MASTER ) {
424 $i = $this->getWriterIndex();
425 } elseif ( !is_array( $groups ) ) {
426 $groupIndex = $this->getReaderIndex( $groups, $wiki );
427 if ( $groupIndex !== false ) {
428 $serverName = $this->getServerName( $groupIndex );
429 wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
430 $i = $groupIndex;
431 }
432 } else {
433 foreach ( $groups as $group ) {
434 $groupIndex = $this->getReaderIndex( $group, $wiki );
435 if ( $groupIndex !== false ) {
436 $serverName = $this->getServerName( $groupIndex );
437 wfDebug( __METHOD__.": using server $serverName for group $group\n" );
438 $i = $groupIndex;
439 break;
440 }
441 }
442 }
443
444 # Operation-based index
445 if ( $i == DB_SLAVE ) {
446 $i = $this->getReaderIndex( false, $wiki );
447 # Couldn't find a working server in getReaderIndex()?
448 if ( $i === false ) {
449 $this->mLastError = 'No working slave server: ' . $this->mLastError;
450 $this->reportConnectionError( $this->mErrorConnection );
451 wfProfileOut( __METHOD__ );
452 return false;
453 }
454 }
455
456 # Now we have an explicit index into the servers array
457 $conn = $this->openConnection( $i, $wiki );
458 if ( !$conn ) {
459 $this->reportConnectionError( $this->mErrorConnection );
460 }
461
462 wfProfileOut( __METHOD__ );
463 return $conn;
464 }
465
466 /**
467 * Mark a foreign connection as being available for reuse under a different
468 * DB name or prefix. This mechanism is reference-counted, and must be called
469 * the same number of times as getConnection() to work.
470 */
471 public function reuseConnection( $conn ) {
472 $serverIndex = $conn->getLBInfo('serverIndex');
473 $refCount = $conn->getLBInfo('foreignPoolRefCount');
474 $dbName = $conn->getDBname();
475 $prefix = $conn->tablePrefix();
476 if ( strval( $prefix ) !== '' ) {
477 $wiki = "$dbName-$prefix";
478 } else {
479 $wiki = $dbName;
480 }
481 if ( $serverIndex === null || $refCount === null ) {
482 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
483 /**
484 * This can happen in code like:
485 * foreach ( $dbs as $db ) {
486 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
487 * ...
488 * $lb->reuseConnection( $conn );
489 * }
490 * When a connection to the local DB is opened in this way, reuseConnection()
491 * should be ignored
492 */
493 return;
494 }
495 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
496 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
497 }
498 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
499 if ( $refCount <= 0 ) {
500 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
501 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
502 wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
503 } else {
504 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
505 }
506 }
507
508 /**
509 * Open a connection to the server given by the specified index
510 * Index must be an actual index into the array.
511 * If the server is already open, returns it.
512 *
513 * On error, returns false, and the connection which caused the
514 * error will be available via $this->mErrorConnection.
515 *
516 * @param $i Integer: server index
517 * @param $wiki String: wiki ID to open
518 * @return DatabaseBase
519 *
520 * @access private
521 */
522 function openConnection( $i, $wiki = false ) {
523 wfProfileIn( __METHOD__ );
524 if ( $wiki !== false ) {
525 $conn = $this->openForeignConnection( $i, $wiki );
526 wfProfileOut( __METHOD__);
527 return $conn;
528 }
529 if ( isset( $this->mConns['local'][$i][0] ) ) {
530 $conn = $this->mConns['local'][$i][0];
531 } else {
532 $server = $this->mServers[$i];
533 $server['serverIndex'] = $i;
534 $conn = $this->reallyOpenConnection( $server, false );
535 if ( $conn->isOpen() ) {
536 $this->mConns['local'][$i][0] = $conn;
537 } else {
538 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
539 $this->mErrorConnection = $conn;
540 $conn = false;
541 }
542 }
543 wfProfileOut( __METHOD__ );
544 return $conn;
545 }
546
547 /**
548 * Open a connection to a foreign DB, or return one if it is already open.
549 *
550 * Increments a reference count on the returned connection which locks the
551 * connection to the requested wiki. This reference count can be
552 * decremented by calling reuseConnection().
553 *
554 * If a connection is open to the appropriate server already, but with the wrong
555 * database, it will be switched to the right database and returned, as long as
556 * it has been freed first with reuseConnection().
557 *
558 * On error, returns false, and the connection which caused the
559 * error will be available via $this->mErrorConnection.
560 *
561 * @param $i Integer: server index
562 * @param $wiki String: wiki ID to open
563 * @return DatabaseBase
564 */
565 function openForeignConnection( $i, $wiki ) {
566 wfProfileIn(__METHOD__);
567 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
568 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
569 // Reuse an already-used connection
570 $conn = $this->mConns['foreignUsed'][$i][$wiki];
571 wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
572 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
573 // Reuse a free connection for the same wiki
574 $conn = $this->mConns['foreignFree'][$i][$wiki];
575 unset( $this->mConns['foreignFree'][$i][$wiki] );
576 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
577 wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
578 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
579 // Reuse a connection from another wiki
580 $conn = reset( $this->mConns['foreignFree'][$i] );
581 $oldWiki = key( $this->mConns['foreignFree'][$i] );
582
583 if ( !$conn->selectDB( $dbName ) ) {
584 $this->mLastError = "Error selecting database $dbName on server " .
585 $conn->getServer() . " from client host " . wfHostname() . "\n";
586 $this->mErrorConnection = $conn;
587 $conn = false;
588 } else {
589 $conn->tablePrefix( $prefix );
590 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
591 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
592 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
593 }
594 } else {
595 // Open a new connection
596 $server = $this->mServers[$i];
597 $server['serverIndex'] = $i;
598 $server['foreignPoolRefCount'] = 0;
599 $conn = $this->reallyOpenConnection( $server, $dbName );
600 if ( !$conn->isOpen() ) {
601 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
602 $this->mErrorConnection = $conn;
603 $conn = false;
604 } else {
605 $conn->tablePrefix( $prefix );
606 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
607 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
608 }
609 }
610
611 // Increment reference count
612 if ( $conn ) {
613 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
614 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
615 }
616 wfProfileOut(__METHOD__);
617 return $conn;
618 }
619
620 /**
621 * Test if the specified index represents an open connection
622 *
623 * @param $index Integer: server index
624 * @access private
625 */
626 function isOpen( $index ) {
627 if( !is_integer( $index ) ) {
628 return false;
629 }
630 return (bool)$this->getAnyOpenConnection( $index );
631 }
632
633 /**
634 * Really opens a connection. Uncached.
635 * Returns a Database object whether or not the connection was successful.
636 * @access private
637 */
638 function reallyOpenConnection( $server, $dbNameOverride = false ) {
639 if( !is_array( $server ) ) {
640 throw new MWException( 'You must update your load-balancing configuration. ' .
641 'See DefaultSettings.php entry for $wgDBservers.' );
642 }
643
644 $host = $server['host'];
645 $dbname = $server['dbname'];
646
647 if ( $dbNameOverride !== false ) {
648 $server['dbname'] = $dbname = $dbNameOverride;
649 }
650
651 # Create object
652 wfDebug( "Connecting to $host $dbname...\n" );
653 $db = DatabaseBase::newFromType( $server['type'], $server );
654 if ( $db->isOpen() ) {
655 wfDebug( "Connected to $host $dbname.\n" );
656 } else {
657 wfDebug( "Connection failed to $host $dbname.\n" );
658 }
659 $db->setLBInfo( $server );
660 if ( isset( $server['fakeSlaveLag'] ) ) {
661 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
662 }
663 if ( isset( $server['fakeMaster'] ) ) {
664 $db->setFakeMaster( true );
665 }
666 return $db;
667 }
668
669 function reportConnectionError( &$conn ) {
670 wfProfileIn( __METHOD__ );
671
672 if ( !is_object( $conn ) ) {
673 // No last connection, probably due to all servers being too busy
674 wfLogDBError( "LB failure with no last connection\n" );
675 $conn = new Database;
676 // If all servers were busy, mLastError will contain something sensible
677 throw new DBConnectionError( $conn, $this->mLastError );
678 } else {
679 $server = $conn->getProperty( 'mServer' );
680 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
681 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
682 }
683 wfProfileOut( __METHOD__ );
684 }
685
686 function getWriterIndex() {
687 return 0;
688 }
689
690 /**
691 * Returns true if the specified index is a valid server index
692 */
693 function haveIndex( $i ) {
694 return array_key_exists( $i, $this->mServers );
695 }
696
697 /**
698 * Returns true if the specified index is valid and has non-zero load
699 */
700 function isNonZeroLoad( $i ) {
701 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
702 }
703
704 /**
705 * Get the number of defined servers (not the number of open connections)
706 */
707 function getServerCount() {
708 return count( $this->mServers );
709 }
710
711 /**
712 * Get the host name or IP address of the server with the specified index
713 * Prefer a readable name if available.
714 */
715 function getServerName( $i ) {
716 if ( isset( $this->mServers[$i]['hostName'] ) ) {
717 return $this->mServers[$i]['hostName'];
718 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
719 return $this->mServers[$i]['host'];
720 } else {
721 return '';
722 }
723 }
724
725 /**
726 * Return the server info structure for a given index, or false if the index is invalid.
727 */
728 function getServerInfo( $i ) {
729 if ( isset( $this->mServers[$i] ) ) {
730 return $this->mServers[$i];
731 } else {
732 return false;
733 }
734 }
735
736 /**
737 * Get the current master position for chronology control purposes
738 * @return mixed
739 */
740 function getMasterPos() {
741 # If this entire request was served from a slave without opening a connection to the
742 # master (however unlikely that may be), then we can fetch the position from the slave.
743 $masterConn = $this->getAnyOpenConnection( 0 );
744 if ( !$masterConn ) {
745 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
746 $conn = $this->getAnyOpenConnection( $i );
747 if ( $conn ) {
748 wfDebug( "Master pos fetched from slave\n" );
749 return $conn->getSlavePos();
750 }
751 }
752 } else {
753 wfDebug( "Master pos fetched from master\n" );
754 return $masterConn->getMasterPos();
755 }
756 return false;
757 }
758
759 /**
760 * Close all open connections
761 */
762 function closeAll() {
763 foreach ( $this->mConns as $conns2 ) {
764 foreach ( $conns2 as $conns3 ) {
765 foreach ( $conns3 as $conn ) {
766 $conn->close();
767 }
768 }
769 }
770 $this->mConns = array(
771 'local' => array(),
772 'foreignFree' => array(),
773 'foreignUsed' => array(),
774 );
775 }
776
777 /**
778 * Deprecated function, typo in function name
779 */
780 function closeConnecton( $conn ) {
781 $this->closeConnection( $conn );
782 }
783
784 /**
785 * Close a connection
786 * Using this function makes sure the LoadBalancer knows the connection is closed.
787 * If you use $conn->close() directly, the load balancer won't update its state.
788 * @param $conn
789 * @return void
790 */
791 function closeConnection( $conn ) {
792 $done = false;
793 foreach ( $this->mConns as $i1 => $conns2 ) {
794 foreach ( $conns2 as $i2 => $conns3 ) {
795 foreach ( $conns3 as $i3 => $candidateConn ) {
796 if ( $conn === $candidateConn ) {
797 $conn->close();
798 unset( $this->mConns[$i1][$i2][$i3] );
799 $done = true;
800 break;
801 }
802 }
803 }
804 }
805 if ( !$done ) {
806 $conn->close();
807 }
808 }
809
810 /**
811 * Commit transactions on all open connections
812 */
813 function commitAll() {
814 foreach ( $this->mConns as $conns2 ) {
815 foreach ( $conns2 as $conns3 ) {
816 foreach ( $conns3 as $conn ) {
817 $conn->commit();
818 }
819 }
820 }
821 }
822
823 /* Issue COMMIT only on master, only if queries were done on connection */
824 function commitMasterChanges() {
825 // Always 0, but who knows.. :)
826 $masterIndex = $this->getWriterIndex();
827 foreach ( $this->mConns as $conns2 ) {
828 if ( empty( $conns2[$masterIndex] ) ) {
829 continue;
830 }
831 foreach ( $conns2[$masterIndex] as $conn ) {
832 if ( $conn->doneWrites() ) {
833 $conn->commit();
834 }
835 }
836 }
837 }
838
839 function waitTimeout( $value = null ) {
840 return wfSetVar( $this->mWaitTimeout, $value );
841 }
842
843 function getLaggedSlaveMode() {
844 return $this->mLaggedSlaveMode;
845 }
846
847 /* Disables/enables lag checks */
848 function allowLagged($mode=null) {
849 if ($mode===null)
850 return $this->mAllowLagged;
851 $this->mAllowLagged=$mode;
852 }
853
854 function pingAll() {
855 $success = true;
856 foreach ( $this->mConns as $conns2 ) {
857 foreach ( $conns2 as $conns3 ) {
858 foreach ( $conns3 as $conn ) {
859 if ( !$conn->ping() ) {
860 $success = false;
861 }
862 }
863 }
864 }
865 return $success;
866 }
867
868 /**
869 * Call a function with each open connection object
870 */
871 function forEachOpenConnection( $callback, $params = array() ) {
872 foreach ( $this->mConns as $conns2 ) {
873 foreach ( $conns2 as $conns3 ) {
874 foreach ( $conns3 as $conn ) {
875 $mergedParams = array_merge( array( $conn ), $params );
876 call_user_func_array( $callback, $mergedParams );
877 }
878 }
879 }
880 }
881
882 /**
883 * Get the hostname and lag time of the most-lagged slave.
884 * This is useful for maintenance scripts that need to throttle their updates.
885 * May attempt to open connections to slaves on the default DB.
886 * @param $wiki string Wiki ID, or false for the default database
887 */
888 function getMaxLag( $wiki = false ) {
889 $maxLag = -1;
890 $host = '';
891 foreach ( $this->mServers as $i => $conn ) {
892 $conn = false;
893 if ( $wiki === false ) {
894 $conn = $this->getAnyOpenConnection( $i );
895 }
896 if ( !$conn ) {
897 $conn = $this->openConnection( $i, $wiki );
898 }
899 if ( !$conn ) {
900 continue;
901 }
902 $lag = $conn->getLag();
903 if ( $lag > $maxLag ) {
904 $maxLag = $lag;
905 $host = $this->mServers[$i]['host'];
906 }
907 }
908 return array( $host, $maxLag );
909 }
910
911 /**
912 * Get lag time for each server
913 * Results are cached for a short time in memcached, and indefinitely in the process cache
914 */
915 function getLagTimes( $wiki = false ) {
916 # Try process cache
917 if ( isset( $this->mLagTimes ) ) {
918 return $this->mLagTimes;
919 }
920 # No, send the request to the load monitor
921 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
922 return $this->mLagTimes;
923 }
924
925 /**
926 * Clear the cache for getLagTimes
927 */
928 function clearLagTimeCache() {
929 $this->mLagTimes = null;
930 }
931 }