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