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