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