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