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