* Appllied patch for bug 1686, image metadata cache by Andrius Ramanauskas.
[mediawiki.git] / includes / LoadBalancer.php
blobf5fdf6175e2e800fe7c09eb1eb49d4a180fcd2a7
1 <?php
2 /**
4 * @package MediaWiki
5 */
7 /**
8 * Depends on the database object
9 */
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
18 # Obsolete aliases
19 define( 'DB_READ', -1 );
20 define( 'DB_WRITE', -2 );
22 # Task-based indexes
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 /**
34 * Database load balancing object
36 * @todo document
37 * @package MediaWiki
39 class LoadBalancer {
40 /* private */ var $mServers, $mConnections, $mLoads;
41 /* private */ var $mFailFunction;
42 /* private */ var $mForce, $mReadIndex, $mLastIndex;
43 /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
44 /* private */ var $mLaggedSlaveMode;
46 function LoadBalancer()
48 $this->mServers = array();
49 $this->mConnections = array();
50 $this->mFailFunction = false;
51 $this->mReadIndex = -1;
52 $this->mForce = -1;
53 $this->mLastIndex = -1;
56 function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
58 $lb = new LoadBalancer;
59 $lb->initialise( $servers, $failFunction = false );
60 return $lb;
63 function initialise( $servers, $failFunction = false, $waitTimeout = 10 )
65 $this->mServers = $servers;
66 $this->mFailFunction = $failFunction;
67 $this->mReadIndex = -1;
68 $this->mWriteIndex = -1;
69 $this->mForce = -1;
70 $this->mConnections = array();
71 $this->mLastIndex = 1;
72 $this->mLoads = array();
73 $this->mWaitForFile = false;
74 $this->mWaitForPos = false;
75 $this->mWaitTimeout = $waitTimeout;
76 $this->mLaggedSlaveMode = false;
78 foreach( $servers as $i => $server ) {
79 $this->mLoads[$i] = $server['load'];
83 /**
84 * Given an array of non-normalised probabilities, this function will select
85 * an element and return the appropriate key
87 function pickRandom( $weights )
89 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
90 return false;
93 $sum = 0;
94 foreach ( $weights as $w ) {
95 $sum += $w;
97 $max = mt_getrandmax();
98 $rand = mt_rand(0, $max) / $max * $sum;
100 $sum = 0;
101 foreach ( $weights as $i => $w ) {
102 $sum += $w;
103 if ( $sum >= $rand ) {
104 break;
107 return $i;
110 function getReaderIndex()
112 $fname = 'LoadBalancer::getReaderIndex';
113 wfProfileIn( $fname );
115 $i = false;
116 if ( $this->mForce >= 0 ) {
117 $i = $this->mForce;
118 } else {
119 if ( $this->mReadIndex >= 0 ) {
120 $i = $this->mReadIndex;
121 } else {
122 # $loads is $this->mLoads except with elements knocked out if they
123 # don't work
124 $loads = $this->mLoads;
125 do {
126 $i = $this->pickRandom( $loads );
127 if ( $i !== false ) {
128 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
130 $this->openConnection( $i );
132 if ( !$this->isOpen( $i ) ) {
133 unset( $loads[$i] );
136 } while ( $i !== false && !$this->isOpen( $i ) );
138 if ( $this->isOpen( $i ) ) {
139 $this->mReadIndex = $i;
140 } else {
141 $i = false;
145 wfProfileOut( $fname );
146 return $i;
150 * Set the master wait position
151 * If a DB_SLAVE connection has been opened already, waits
152 * Otherwise sets a variable telling it to wait if such a connection is opened
154 function waitFor( $file, $pos ) {
155 $fname = 'LoadBalancer::waitFor';
156 wfProfileIn( $fname );
158 wfDebug( "User master pos: $file $pos\n" );
159 $this->mWaitForFile = false;
160 $this->mWaitForPos = false;
162 if ( count( $this->mServers ) > 1 ) {
163 $this->mWaitForFile = $file;
164 $this->mWaitForPos = $pos;
166 if ( $this->mReadIndex > 0 ) {
167 if ( !$this->doWait( $this->mReadIndex ) ) {
168 $this->mLaggedSlaveMode = true;
172 wfProfileOut( $fname );
176 * Wait for a given slave to catch up to the master pos stored in $this
178 function doWait( $index ) {
179 global $wgMemc;
181 $retVal = false;
183 $key = 'masterpos:' . $index;
184 $memcPos = $wgMemc->get( $key );
185 if ( $memcPos ) {
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 ) {
189 $retVal = true;
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, $this->mWaitTimeout );
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" );
201 $retVal = false;
202 } else {
203 $retVal = true;
204 wfDebug( "Done\n" );
207 return $retVal;
211 * Get a connection by index
213 function &getConnection( $i, $fail = true )
215 $fname = 'LoadBalancer::getConnection';
216 wfProfileIn( $fname );
218 # Task-based index
219 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
220 if ( $i % 2 ) {
221 # Odd index use writer
222 $i = DB_MASTER;
223 } else {
224 # Even index use reader
225 $i = DB_SLAVE;
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;
237 if ( $i === -1 ) {
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
252 * @private
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;
265 $i = 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" );
275 if ( $fail ) {
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
286 * @private
288 function isOpen( $index ) {
289 if( !is_integer( $index ) ) {
290 return false;
292 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
293 $this->mConnections[$index]->isOpen() )
295 return true;
296 } else {
297 return false;
302 * Really opens a connection
303 * @private
305 function reallyOpenConnection( &$server ) {
306 if( !is_array( $server ) ) {
307 wfDebugDieBacktrace( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
310 extract( $server );
311 # Get class for this database type
312 $class = 'Database' . ucfirst( $type );
313 if ( !class_exists( $class ) ) {
314 require_once( "$class.php" );
317 # Create object
318 return new $class( $host, $user, $password, $dbname, 1, $flags );
321 function reportConnectionError( &$conn )
323 $fname = 'LoadBalancer::reportConnectionError';
324 wfProfileIn( $fname );
325 # Prevent infinite recursion
327 static $reporting = false;
328 if ( !$reporting ) {
329 $reporting = true;
330 if ( !is_object( $conn ) ) {
331 $conn = new Database;
333 if ( $this->mFailFunction ) {
334 $conn->failFunction( $this->mFailFunction );
335 } else {
336 $conn->failFunction( 'wfEmergencyAbort' );
338 $conn->reportConnectionError();
339 $reporting = false;
341 wfProfileOut( $fname );
344 function getWriterIndex()
346 return 0;
349 function force( $i )
351 $this->mForce = $i;
354 function haveIndex( $i )
356 return array_key_exists( $i, $this->mServers );
360 * Get the number of defined servers (not the number of open connections)
362 function getServerCount() {
363 return count( $this->mServers );
367 * Save master pos to the session and to memcached, if the session exists
369 function saveMasterPos() {
370 global $wgSessionStarted;
371 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
372 # If this entire request was served from a slave without opening a connection to the
373 # master (however unlikely that may be), then we can fetch the position from the slave.
374 if ( empty( $this->mConnections[0] ) ) {
375 $conn =& $this->getConnection( DB_SLAVE );
376 list( $file, $pos ) = $conn->getSlavePos();
377 wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
378 } else {
379 $conn =& $this->getConnection( 0 );
380 list( $file, $pos ) = $conn->getMasterPos();
381 wfDebug( "Saving master pos: $file $pos\n" );
383 if ( $file !== false ) {
384 $_SESSION['master_log_file'] = $file;
385 $_SESSION['master_pos'] = $pos;
391 * Loads the master pos from the session, waits for it if necessary
393 function loadMasterPos() {
394 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
395 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
400 * Close all open connections
402 function closeAll() {
403 foreach( $this->mConnections as $i => $conn ) {
404 if ( $this->isOpen( $i ) ) {
405 $conn->close();
410 function commitAll() {
411 foreach( $this->mConnections as $i => $conn ) {
412 if ( $this->isOpen( $i ) ) {
413 $conn->immediateCommit();
418 function waitTimeout( $value = NULL ) {
419 return wfSetVar( $this->mWaitTimeout, $value );
422 function getLaggedSlaveMode() {
423 return $this->mLaggedSlaveMode;