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