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