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