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