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