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