Moar documentations
[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 function getWriterIndex() {
727 return 0;
728 }
729
730 /**
731 * Returns true if the specified index is a valid server index
732 *
733 * @return bool
734 */
735 function haveIndex( $i ) {
736 return array_key_exists( $i, $this->mServers );
737 }
738
739 /**
740 * Returns true if the specified index is valid and has non-zero load
741 *
742 * @return bool
743 */
744 function isNonZeroLoad( $i ) {
745 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
746 }
747
748 /**
749 * Get the number of defined servers (not the number of open connections)
750 *
751 * @return int
752 */
753 function getServerCount() {
754 return count( $this->mServers );
755 }
756
757 /**
758 * Get the host name or IP address of the server with the specified index
759 * Prefer a readable name if available.
760 */
761 function getServerName( $i ) {
762 if ( isset( $this->mServers[$i]['hostName'] ) ) {
763 return $this->mServers[$i]['hostName'];
764 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
765 return $this->mServers[$i]['host'];
766 } else {
767 return '';
768 }
769 }
770
771 /**
772 * Return the server info structure for a given index, or false if the index is invalid.
773 */
774 function getServerInfo( $i ) {
775 if ( isset( $this->mServers[$i] ) ) {
776 return $this->mServers[$i];
777 } else {
778 return false;
779 }
780 }
781
782 /**
783 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
784 */
785 function setServerInfo( $i, $serverInfo ) {
786 $this->mServers[$i] = $serverInfo;
787 }
788
789 /**
790 * Get the current master position for chronology control purposes
791 * @return mixed
792 */
793 function getMasterPos() {
794 # If this entire request was served from a slave without opening a connection to the
795 # master (however unlikely that may be), then we can fetch the position from the slave.
796 $masterConn = $this->getAnyOpenConnection( 0 );
797 if ( !$masterConn ) {
798 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
799 $conn = $this->getAnyOpenConnection( $i );
800 if ( $conn ) {
801 wfDebug( "Master pos fetched from slave\n" );
802 return $conn->getSlavePos();
803 }
804 }
805 } else {
806 wfDebug( "Master pos fetched from master\n" );
807 return $masterConn->getMasterPos();
808 }
809 return false;
810 }
811
812 /**
813 * Close all open connections
814 */
815 function closeAll() {
816 foreach ( $this->mConns as $conns2 ) {
817 foreach ( $conns2 as $conns3 ) {
818 foreach ( $conns3 as $conn ) {
819 $conn->close();
820 }
821 }
822 }
823 $this->mConns = array(
824 'local' => array(),
825 'foreignFree' => array(),
826 'foreignUsed' => array(),
827 );
828 }
829
830 /**
831 * Deprecated function, typo in function name
832 *
833 * @deprecated in 1.18
834 */
835 function closeConnecton( $conn ) {
836 $this->closeConnection( $conn );
837 }
838
839 /**
840 * Close a connection
841 * Using this function makes sure the LoadBalancer knows the connection is closed.
842 * If you use $conn->close() directly, the load balancer won't update its state.
843 * @param $conn DatabaseBase
844 */
845 function closeConnection( $conn ) {
846 $done = false;
847 foreach ( $this->mConns as $i1 => $conns2 ) {
848 foreach ( $conns2 as $i2 => $conns3 ) {
849 foreach ( $conns3 as $i3 => $candidateConn ) {
850 if ( $conn === $candidateConn ) {
851 $conn->close();
852 unset( $this->mConns[$i1][$i2][$i3] );
853 $done = true;
854 break;
855 }
856 }
857 }
858 }
859 if ( !$done ) {
860 $conn->close();
861 }
862 }
863
864 /**
865 * Commit transactions on all open connections
866 */
867 function commitAll() {
868 foreach ( $this->mConns as $conns2 ) {
869 foreach ( $conns2 as $conns3 ) {
870 foreach ( $conns3 as $conn ) {
871 $conn->commit();
872 }
873 }
874 }
875 }
876
877 /**
878 * Issue COMMIT only on master, only if queries were done on connection
879 */
880 function commitMasterChanges() {
881 // Always 0, but who knows.. :)
882 $masterIndex = $this->getWriterIndex();
883 foreach ( $this->mConns as $conns2 ) {
884 if ( empty( $conns2[$masterIndex] ) ) {
885 continue;
886 }
887 foreach ( $conns2[$masterIndex] as $conn ) {
888 if ( $conn->doneWrites() ) {
889 $conn->commit();
890 }
891 }
892 }
893 }
894
895 /**
896 * @param $value null
897 * @return Mixed
898 */
899 function waitTimeout( $value = null ) {
900 return wfSetVar( $this->mWaitTimeout, $value );
901 }
902
903 /**
904 * @return bool
905 */
906 function getLaggedSlaveMode() {
907 return $this->mLaggedSlaveMode;
908 }
909
910 /* Disables/enables lag checks */
911 function allowLagged( $mode = null ) {
912 if ( $mode === null) {
913 return $this->mAllowLagged;
914 }
915 $this->mAllowLagged = $mode;
916 }
917
918 /**
919 * @return bool
920 */
921 function pingAll() {
922 $success = true;
923 foreach ( $this->mConns as $conns2 ) {
924 foreach ( $conns2 as $conns3 ) {
925 foreach ( $conns3 as $conn ) {
926 if ( !$conn->ping() ) {
927 $success = false;
928 }
929 }
930 }
931 }
932 return $success;
933 }
934
935 /**
936 * Call a function with each open connection object
937 */
938 function forEachOpenConnection( $callback, $params = array() ) {
939 foreach ( $this->mConns as $conns2 ) {
940 foreach ( $conns2 as $conns3 ) {
941 foreach ( $conns3 as $conn ) {
942 $mergedParams = array_merge( array( $conn ), $params );
943 call_user_func_array( $callback, $mergedParams );
944 }
945 }
946 }
947 }
948
949 /**
950 * Get the hostname and lag time of the most-lagged slave.
951 * This is useful for maintenance scripts that need to throttle their updates.
952 * May attempt to open connections to slaves on the default DB. If there is
953 * no lag, the maximum lag will be reported as -1.
954 *
955 * @param $wiki string Wiki ID, or false for the default database
956 *
957 * @return array ( host, max lag, index of max lagged host )
958 */
959 function getMaxLag( $wiki = false ) {
960 $maxLag = -1;
961 $host = '';
962 $maxIndex = 0;
963 if ( $this->getServerCount() > 1 ) { // no replication = no lag
964 foreach ( $this->mServers as $i => $conn ) {
965 $conn = false;
966 if ( $wiki === false ) {
967 $conn = $this->getAnyOpenConnection( $i );
968 }
969 if ( !$conn ) {
970 $conn = $this->openConnection( $i, $wiki );
971 }
972 if ( !$conn ) {
973 continue;
974 }
975 $lag = $conn->getLag();
976 if ( $lag > $maxLag ) {
977 $maxLag = $lag;
978 $host = $this->mServers[$i]['host'];
979 $maxIndex = $i;
980 }
981 }
982 }
983 return array( $host, $maxLag, $maxIndex );
984 }
985
986 /**
987 * Get lag time for each server
988 * Results are cached for a short time in memcached, and indefinitely in the process cache
989 *
990 * @param $wiki
991 *
992 * @return array
993 */
994 function getLagTimes( $wiki = false ) {
995 # Try process cache
996 if ( isset( $this->mLagTimes ) ) {
997 return $this->mLagTimes;
998 }
999 if ( $this->getServerCount() == 1 ) {
1000 # No replication
1001 $this->mLagTimes = array( 0 => 0 );
1002 } else {
1003 # Send the request to the load monitor
1004 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
1005 array_keys( $this->mServers ), $wiki );
1006 }
1007 return $this->mLagTimes;
1008 }
1009
1010 /**
1011 * Get the lag in seconds for a given connection, or zero if this load
1012 * balancer does not have replication enabled.
1013 *
1014 * This should be used in preference to Database::getLag() in cases where
1015 * replication may not be in use, since there is no way to determine if
1016 * replication is in use at the connection level without running
1017 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1018 * function instead of Database::getLag() avoids a fatal error in this
1019 * case on many installations.
1020 *
1021 * @param $conn DatabaseBase
1022 *
1023 * @return int
1024 */
1025 function safeGetLag( $conn ) {
1026 if ( $this->getServerCount() == 1 ) {
1027 return 0;
1028 } else {
1029 return $conn->getLag();
1030 }
1031 }
1032
1033 /**
1034 * Clear the cache for getLagTimes
1035 */
1036 function clearLagTimeCache() {
1037 $this->mLagTimes = null;
1038 }
1039 }