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