7 * Depends on the database object
9 require_once( 'Database.php' );
11 # Valid database indexes
12 # Operation-based indexes
13 define( 'DB_SLAVE', -1 ); # Read from the slave (or only server)
14 define( 'DB_MASTER', -2 ); # Write to master (or only server)
15 define( 'DB_LAST', -3 ); # Whatever database was used last
18 define( 'DB_READ', -1 );
19 define( 'DB_WRITE', -2 );
22 # ***NOT USED YET, EXPERIMENTAL***
23 # These may be defined in $wgDBservers. If they aren't, the default reader or writer will be used
24 # Even numbers are always readers, odd numbers are writers
25 define( 'DB_TASK_FIRST', 1000 ); # First in list
26 define( 'DB_SEARCH_R', 1000 ); # Search read
27 define( 'DB_SEARCH_W', 1001 ); # Search write
28 define( 'DB_ASKSQL_R', 1002 ); # Special:Asksql read
29 define( 'DB_WATCHLIST_R', 1004 ); # Watchlist read
30 define( 'DB_TASK_LAST', 1004) ; # Last in list
32 define( 'MASTER_WAIT_TIMEOUT', 15 ); # Time to wait for a slave to synchronise
35 * Database load balancing object
39 /* private */ var $mServers, $mConnections, $mLoads;
40 /* private */ var $mFailFunction;
41 /* private */ var $mForce, $mReadIndex, $mLastIndex;
42 /* private */ var $mWaitForFile, $mWaitForPos;
44 function LoadBalancer()
46 $this->mServers
= array();
47 $this->mConnections
= array();
48 $this->mFailFunction
= false;
49 $this->mReadIndex
= -1;
51 $this->mLastIndex
= -1;
54 function newFromParams( $servers, $failFunction = false )
56 $lb = new LoadBalancer
;
57 $lb->initialise( $servers, $failFunction = false );
61 function initialise( $servers, $failFunction = false )
63 $this->mServers
= $servers;
64 $this->mFailFunction
= $failFunction;
65 $this->mReadIndex
= -1;
66 $this->mWriteIndex
= -1;
68 $this->mConnections
= array();
69 $this->mLastIndex
= 1;
70 $this->mLoads
= array();
71 $this->mWaitForFile
= false;
72 $this->mWaitForPos
= false;
74 foreach( $servers as $i => $server ) {
75 $this->mLoads
[$i] = $server['load'];
80 * Given an array of non-normalised probabilities, this function will select
81 * an element and return the appropriate key
83 function pickRandom( $weights )
85 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
90 foreach ( $weights as $w ) {
93 $max = mt_getrandmax();
94 $rand = mt_rand(0, $max) / $max * $sum;
97 foreach ( $weights as $i => $w ) {
99 if ( $sum >= $rand ) {
106 function getReaderIndex()
108 $fname = 'LoadBalancer::getReaderIndex';
109 wfProfileIn( $fname );
112 if ( $this->mForce
>= 0 ) {
115 if ( $this->mReadIndex
>= 0 ) {
116 $i = $this->mReadIndex
;
118 # $loads is $this->mLoads except with elements knocked out if they
120 $loads = $this->mLoads
;
122 $i = $this->pickRandom( $loads );
123 if ( $i !== false ) {
124 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
126 $this->openConnection( $i );
128 if ( !$this->isOpen( $i ) ) {
132 } while ( $i !== false && !$this->isOpen( $i ) );
134 if ( $this->isOpen( $i ) ) {
135 $this->mReadIndex
= $i;
141 wfProfileOut( $fname );
146 * Set the master wait position
147 * If a DB_SLAVE connection has been opened already, waits
148 * Otherwise sets a variable telling it to wait if such a connection is opened
150 function waitFor( $file, $pos ) {
151 $fname = 'LoadBalancer::waitFor';
152 wfProfileIn( $fname );
154 wfDebug( "User master pos: $file $pos\n" );
155 $this->mWaitForFile
= false;
156 $this->mWaitForPos
= false;
158 if ( count( $this->mServers
) > 1 ) {
159 $this->mWaitForFile
= $file;
160 $this->mWaitForPos
= $pos;
162 if ( $this->mReadIndex
> 0 ) {
163 if ( !$this->doWait( $this->mReadIndex
) ) {
165 $this->mReadIndex
= 0;
169 wfProfileOut( $fname );
173 * Wait for a given slave to catch up to the master pos stored in $this
175 function doWait( $index ) {
180 $key = 'masterpos:' . $index;
181 $memcPos = $wgMemc->get( $key );
183 list( $file, $pos ) = explode( ' ', $memcPos );
184 # If the saved position is later than the requested position, return now
185 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
190 if ( !$retVal && $this->isOpen( $index ) ) {
191 $conn =& $this->mConnections( $index );
192 wfDebug( "Waiting for slave #$index to catch up...\n" );
193 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, MASTER_WAIT_TIMEOUT
);
195 if ( $result == -1 ||
is_null( $result ) ) {
196 # Timed out waiting for slave, use master instead
197 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
208 * Get a connection by index
210 function &getConnection( $i, $fail = true )
212 $fname = 'LoadBalancer::getConnection';
213 wfProfileIn( $fname );
216 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
218 # Odd index use writer
221 # Even index use reader
226 # Operation-based index
227 if ( $i == DB_SLAVE
) {
228 $i = $this->getReaderIndex();
229 } elseif ( $i == DB_MASTER
) {
230 $i = $this->getWriterIndex();
231 } elseif ( $i == DB_LAST
) {
232 # Just use $this->mLastIndex, which should already be set
233 $i = $this->mLastIndex
;
235 # Oh dear, not set, best to use the writer for safety
236 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
237 $i = $this->getWriterIndex();
240 # Now we have an explicit index into the servers array
241 $this->openConnection( $i, $fail );
242 wfProfileOut( $fname );
243 return $this->mConnections
[$i];
247 * Open a connection to the server given by the specified index
248 * Index must be an actual index into the array
251 function openConnection( $i, $fail = false ) {
252 $fname = 'LoadBalancer::openConnection';
253 wfProfileIn( $fname );
255 if ( !$this->isOpen( $i ) ) {
256 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
258 if ( $i != 0 && $this->mWaitForFile
) {
259 if ( !$this->doWait( $i ) ) {
260 # Error waiting for this slave, use master instead
261 $this->mReadIndex
= 0;
263 if ( !$this->isOpen( 0 ) ) {
264 $this->mConnections
[0] = $this->reallyOpenConnection( $this->mServers
[0] );
266 wfDebug( "Failed over to {$this->mConnections[0]->mServer}\n" );
270 if ( !$this->isOpen( $i ) ) {
271 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
273 $this->reportConnectionError( $this->mConnections
[$i] );
275 $this->mConnections
[$i] = false;
277 $this->mLastIndex
= $i;
278 wfProfileOut( $fname );
282 * Test if the specified index represents an open connection
285 function isOpen( $index ) {
286 if( !is_integer( $index ) ) {
289 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
290 $this->mConnections
[$index]->isOpen() )
299 * Really opens a connection
302 function reallyOpenConnection( &$server ) {
304 # Get class for this database type
305 $class = 'Database' . ucfirst( $type );
306 if ( !class_exists( $class ) ) {
307 require_once( "$class.php" );
311 return new $class( $host, $user, $password, $dbname, 1, $flags );
314 function reportConnectionError( &$conn )
316 $fname = 'LoadBalancer::reportConnectionError';
317 wfProfileIn( $fname );
318 # Prevent infinite recursion
320 static $reporting = false;
323 if ( !is_object( $conn ) ) {
324 $conn = new Database
;
326 if ( $this->mFailFunction
) {
327 $conn->failFunction( $this->mFailFunction
);
329 $conn->failFunction( 'wfEmergencyAbort' );
331 $conn->reportConnectionError();
334 wfProfileOut( $fname );
337 function getWriterIndex()
347 function haveIndex( $i )
349 return array_key_exists( $i, $this->mServers
);
353 * Get the number of defined servers (not the number of open connections)
355 function getServerCount() {
356 return count( $this->mServers
);
360 * Save master pos to the session and to memcached, if the session exists
362 function saveMasterPos() {
363 global $wgSessionStarted;
364 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
365 # If this entire request was served from a slave without opening a connection to the
366 # master (however unlikely that may be), then we can fetch the position from the slave.
367 if ( empty( $this->mConnections
[0] ) ) {
368 $conn =& $this->getConnection( DB_SLAVE
);
369 list( $file, $pos ) = $conn->getSlavePos();
370 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
372 $conn =& $this->getConnection( 0 );
373 list( $file, $pos ) = $conn->getMasterPos();
374 wfDebug( "Saving master pos: $file $pos\n" );
376 if ( $file !== false ) {
377 $_SESSION['master_log_file'] = $file;
378 $_SESSION['master_pos'] = $pos;
384 * Loads the master pos from the session, waits for it if necessary
386 function loadMasterPos() {
387 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
388 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
393 * Close all open connections
395 function closeAll() {
396 foreach( $this->mConnections
as $i => $conn ) {
397 if ( $this->isOpen( $i ) ) {
403 function commitAll() {
404 foreach( $this->mConnections
as $i => $conn ) {
405 if ( $this->isOpen( $i ) ) {
406 $conn->immediateCommit();