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