8 * Depends on the database object
10 require_once( 'Database.php' );
12 # Valid database indexes
13 # Operation-based indexes
14 define( 'DB_SLAVE', -1 ); # Read from the slave (or only server)
15 define( 'DB_MASTER', -2 ); # Write to master (or only server)
16 define( 'DB_LAST', -3 ); # Whatever database was used last
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
23 # ***NOT USED YET, EXPERIMENTAL***
24 # These may be defined in $wgDBservers. If they aren't, the default reader or writer will be used
25 # Even numbers are always readers, odd numbers are writers
26 define( 'DB_TASK_FIRST', 1000 ); # First in list
27 define( 'DB_SEARCH_R', 1000 ); # Search read
28 define( 'DB_SEARCH_W', 1001 ); # Search write
29 define( 'DB_ASKSQL_R', 1002 ); # Special:Asksql read
30 define( 'DB_WATCHLIST_R', 1004 ); # Watchlist read
31 define( 'DB_TASK_LAST', 1004) ; # Last in list
33 define( 'MASTER_WAIT_TIMEOUT', 15 ); # Time to wait for a slave to synchronise
36 * Database load balancing object
42 /* private */ var $mServers, $mConnections, $mLoads;
43 /* private */ var $mFailFunction;
44 /* private */ var $mForce, $mReadIndex, $mLastIndex;
45 /* private */ var $mWaitForFile, $mWaitForPos;
47 function LoadBalancer()
49 $this->mServers
= array();
50 $this->mConnections
= array();
51 $this->mFailFunction
= false;
52 $this->mReadIndex
= -1;
54 $this->mLastIndex
= -1;
57 function newFromParams( $servers, $failFunction = false )
59 $lb = new LoadBalancer
;
60 $lb->initialise( $servers, $failFunction = false );
64 function initialise( $servers, $failFunction = false )
66 $this->mServers
= $servers;
67 $this->mFailFunction
= $failFunction;
68 $this->mReadIndex
= -1;
69 $this->mWriteIndex
= -1;
71 $this->mConnections
= array();
72 $this->mLastIndex
= 1;
73 $this->mLoads
= array();
74 $this->mWaitForFile
= false;
75 $this->mWaitForPos
= false;
77 foreach( $servers as $i => $server ) {
78 $this->mLoads
[$i] = $server['load'];
83 * Given an array of non-normalised probabilities, this function will select
84 * an element and return the appropriate key
86 function pickRandom( $weights )
88 if ( !is_array( $weights ) ||
count( $weights ) == 0 ) {
93 foreach ( $weights as $w ) {
96 $max = mt_getrandmax();
97 $rand = mt_rand(0, $max) / $max * $sum;
100 foreach ( $weights as $i => $w ) {
102 if ( $sum >= $rand ) {
109 function getReaderIndex()
111 $fname = 'LoadBalancer::getReaderIndex';
112 wfProfileIn( $fname );
115 if ( $this->mForce
>= 0 ) {
118 if ( $this->mReadIndex
>= 0 ) {
119 $i = $this->mReadIndex
;
121 # $loads is $this->mLoads except with elements knocked out if they
123 $loads = $this->mLoads
;
125 $i = $this->pickRandom( $loads );
126 if ( $i !== false ) {
127 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
129 $this->openConnection( $i );
131 if ( !$this->isOpen( $i ) ) {
135 } while ( $i !== false && !$this->isOpen( $i ) );
137 if ( $this->isOpen( $i ) ) {
138 $this->mReadIndex
= $i;
144 wfProfileOut( $fname );
149 * Set the master wait position
150 * If a DB_SLAVE connection has been opened already, waits
151 * Otherwise sets a variable telling it to wait if such a connection is opened
153 function waitFor( $file, $pos ) {
154 $fname = 'LoadBalancer::waitFor';
155 wfProfileIn( $fname );
157 wfDebug( "User master pos: $file $pos\n" );
158 $this->mWaitForFile
= false;
159 $this->mWaitForPos
= false;
161 if ( count( $this->mServers
) > 1 ) {
162 $this->mWaitForFile
= $file;
163 $this->mWaitForPos
= $pos;
165 if ( $this->mReadIndex
> 0 ) {
166 if ( !$this->doWait( $this->mReadIndex
) ) {
168 $this->mReadIndex
= 0;
172 wfProfileOut( $fname );
176 * Wait for a given slave to catch up to the master pos stored in $this
178 function doWait( $index ) {
183 $key = 'masterpos:' . $index;
184 $memcPos = $wgMemc->get( $key );
186 list( $file, $pos ) = explode( ' ', $memcPos );
187 # If the saved position is later than the requested position, return now
188 if ( $file == $this->mWaitForFile
&& $this->mWaitForPos
<= $pos ) {
193 if ( !$retVal && $this->isOpen( $index ) ) {
194 $conn =& $this->mConnections( $index );
195 wfDebug( "Waiting for slave #$index to catch up...\n" );
196 $result = $conn->masterPosWait( $this->mWaitForFile
, $this->mWaitForPos
, MASTER_WAIT_TIMEOUT
);
198 if ( $result == -1 ||
is_null( $result ) ) {
199 # Timed out waiting for slave, use master instead
200 wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
211 * Get a connection by index
213 function &getConnection( $i, $fail = true )
215 $fname = 'LoadBalancer::getConnection';
216 wfProfileIn( $fname );
219 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
221 # Odd index use writer
224 # Even index use reader
229 # Operation-based index
230 if ( $i == DB_SLAVE
) {
231 $i = $this->getReaderIndex();
232 } elseif ( $i == DB_MASTER
) {
233 $i = $this->getWriterIndex();
234 } elseif ( $i == DB_LAST
) {
235 # Just use $this->mLastIndex, which should already be set
236 $i = $this->mLastIndex
;
238 # Oh dear, not set, best to use the writer for safety
239 wfDebug( "Warning: DB_LAST used when there was no previous index\n" );
240 $i = $this->getWriterIndex();
243 # Now we have an explicit index into the servers array
244 $this->openConnection( $i, $fail );
245 wfProfileOut( $fname );
246 return $this->mConnections
[$i];
250 * Open a connection to the server given by the specified index
251 * Index must be an actual index into the array
254 function openConnection( $i, $fail = false ) {
255 $fname = 'LoadBalancer::openConnection';
256 wfProfileIn( $fname );
258 if ( !$this->isOpen( $i ) ) {
259 $this->mConnections
[$i] = $this->reallyOpenConnection( $this->mServers
[$i] );
261 if ( $i != 0 && $this->mWaitForFile
) {
262 if ( !$this->doWait( $i ) ) {
263 # Error waiting for this slave, use master instead
264 $this->mReadIndex
= 0;
266 if ( !$this->isOpen( 0 ) ) {
267 $this->mConnections
[0] = $this->reallyOpenConnection( $this->mServers
[0] );
269 wfDebug( "Failed over to {$this->mConnections[0]->mServer}\n" );
273 if ( !$this->isOpen( $i ) ) {
274 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
276 $this->reportConnectionError( $this->mConnections
[$i] );
278 $this->mConnections
[$i] = false;
280 $this->mLastIndex
= $i;
281 wfProfileOut( $fname );
285 * Test if the specified index represents an open connection
288 function isOpen( $index ) {
289 if( !is_integer( $index ) ) {
292 if ( array_key_exists( $index, $this->mConnections
) && is_object( $this->mConnections
[$index] ) &&
293 $this->mConnections
[$index]->isOpen() )
302 * Really opens a connection
305 function reallyOpenConnection( &$server ) {
307 # Get class for this database type
308 $class = 'Database' . ucfirst( $type );
309 if ( !class_exists( $class ) ) {
310 require_once( "$class.php" );
314 return new $class( $host, $user, $password, $dbname, 1, $flags );
317 function reportConnectionError( &$conn )
319 $fname = 'LoadBalancer::reportConnectionError';
320 wfProfileIn( $fname );
321 # Prevent infinite recursion
323 static $reporting = false;
326 if ( !is_object( $conn ) ) {
327 $conn = new Database
;
329 if ( $this->mFailFunction
) {
330 $conn->failFunction( $this->mFailFunction
);
332 $conn->failFunction( 'wfEmergencyAbort' );
334 $conn->reportConnectionError();
337 wfProfileOut( $fname );
340 function getWriterIndex()
350 function haveIndex( $i )
352 return array_key_exists( $i, $this->mServers
);
356 * Get the number of defined servers (not the number of open connections)
358 function getServerCount() {
359 return count( $this->mServers
);
363 * Save master pos to the session and to memcached, if the session exists
365 function saveMasterPos() {
366 global $wgSessionStarted;
367 if ( $wgSessionStarted && count( $this->mServers
) > 1 ) {
368 # If this entire request was served from a slave without opening a connection to the
369 # master (however unlikely that may be), then we can fetch the position from the slave.
370 if ( empty( $this->mConnections
[0] ) ) {
371 $conn =& $this->getConnection( DB_SLAVE
);
372 list( $file, $pos ) = $conn->getSlavePos();
373 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
375 $conn =& $this->getConnection( 0 );
376 list( $file, $pos ) = $conn->getMasterPos();
377 wfDebug( "Saving master pos: $file $pos\n" );
379 if ( $file !== false ) {
380 $_SESSION['master_log_file'] = $file;
381 $_SESSION['master_pos'] = $pos;
387 * Loads the master pos from the session, waits for it if necessary
389 function loadMasterPos() {
390 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
391 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
396 * Close all open connections
398 function closeAll() {
399 foreach( $this->mConnections
as $i => $conn ) {
400 if ( $this->isOpen( $i ) ) {
406 function commitAll() {
407 foreach( $this->mConnections
as $i => $conn ) {
408 if ( $this->isOpen( $i ) ) {
409 $conn->immediateCommit();