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