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