69b5cd3a91e7be80ca1e0dd9f1b467660aace175
[lhc/web/wiklou.git] / includes / LoadBalancer.php
1 <?php
2 /**
3 *
4 */
5
6 /**
7 * Depends on the database object
8 */
9 require_once( 'Database.php' );
10
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
16
17 # Obsolete aliases
18 define( 'DB_READ', -1 );
19 define( 'DB_WRITE', -2 );
20
21 # Task-based indexes
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
31
32 define( 'MASTER_WAIT_TIMEOUT', 15 ); # Time to wait for a slave to synchronise
33
34 /**
35 * Database load balancing object
36 * @todo document
37 */
38 class LoadBalancer {
39 /* private */ var $mServers, $mConnections, $mLoads;
40 /* private */ var $mFailFunction;
41 /* private */ var $mForce, $mReadIndex, $mLastIndex;
42 /* private */ var $mWaitForFile, $mWaitForPos;
43
44 function LoadBalancer()
45 {
46 $this->mServers = array();
47 $this->mConnections = array();
48 $this->mFailFunction = false;
49 $this->mReadIndex = -1;
50 $this->mForce = -1;
51 $this->mLastIndex = -1;
52 }
53
54 function newFromParams( $servers, $failFunction = false )
55 {
56 $lb = new LoadBalancer;
57 $lb->initialise( $servers, $failFunction = false );
58 return $lb;
59 }
60
61 function initialise( $servers, $failFunction = false )
62 {
63 $this->mServers = $servers;
64 $this->mFailFunction = $failFunction;
65 $this->mReadIndex = -1;
66 $this->mWriteIndex = -1;
67 $this->mForce = -1;
68 $this->mConnections = array();
69 $this->mLastIndex = 1;
70 $this->mLoads = array();
71 $this->mWaitForFile = false;
72 $this->mWaitForPos = false;
73
74 foreach( $servers as $i => $server ) {
75 $this->mLoads[$i] = $server['load'];
76 }
77 }
78
79 /**
80 * Given an array of non-normalised probabilities, this function will select
81 * an element and return the appropriate key
82 */
83 function pickRandom( $weights )
84 {
85 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
86 return false;
87 }
88
89 $sum = 0;
90 foreach ( $weights as $w ) {
91 $sum += $w;
92 }
93 $max = mt_getrandmax();
94 $rand = mt_rand(0, $max) / $max * $sum;
95
96 $sum = 0;
97 foreach ( $weights as $i => $w ) {
98 $sum += $w;
99 if ( $sum >= $rand ) {
100 break;
101 }
102 }
103 return $i;
104 }
105
106 function getReaderIndex()
107 {
108 $fname = 'LoadBalancer::getReaderIndex';
109 wfProfileIn( $fname );
110
111 $i = false;
112 if ( $this->mForce >= 0 ) {
113 $i = $this->mForce;
114 } else {
115 if ( $this->mReadIndex >= 0 ) {
116 $i = $this->mReadIndex;
117 } else {
118 # $loads is $this->mLoads except with elements knocked out if they
119 # don't work
120 $loads = $this->mLoads;
121 do {
122 $i = $this->pickRandom( $loads );
123 if ( $i !== false ) {
124 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
125
126 $this->openConnection( $i );
127
128 if ( !$this->isOpen( $i ) ) {
129 unset( $loads[$i] );
130 }
131 }
132 } while ( $i !== false && !$this->isOpen( $i ) );
133
134 if ( $this->isOpen( $i ) ) {
135 $this->mReadIndex = $i;
136 } else {
137 $i = false;
138 }
139 }
140 }
141 wfProfileOut( $fname );
142 return $i;
143 }
144
145 /**
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
149 */
150 function waitFor( $file, $pos ) {
151 $fname = 'LoadBalancer::waitFor';
152 wfProfileIn( $fname );
153
154 wfDebug( "User master pos: $file $pos\n" );
155 $this->mWaitForFile = false;
156 $this->mWaitForPos = false;
157
158 if ( count( $this->mServers ) > 1 ) {
159 $this->mWaitForFile = $file;
160 $this->mWaitForPos = $pos;
161
162 if ( $this->mReadIndex > 0 ) {
163 if ( !$this->doWait( $this->mReadIndex ) ) {
164 # Use master instead
165 $this->mReadIndex = 0;
166 }
167 }
168 }
169 wfProfileOut( $fname );
170 }
171
172 /**
173 * Wait for a given slave to catch up to the master pos stored in $this
174 */
175 function doWait( $index ) {
176 global $wgMemc;
177
178 $retVal = false;
179
180 $key = 'masterpos:' . $index;
181 $memcPos = $wgMemc->get( $key );
182 if ( $memcPos ) {
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 ) {
186 $retVal = true;
187 }
188 }
189
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 );
194
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" );
198 $retVal = false;
199 } else {
200 $retVal = true;
201 wfDebug( "Done\n" );
202 }
203 }
204 return $retVal;
205 }
206
207 /**
208 * Get a connection by index
209 */
210 function &getConnection( $i, $fail = true )
211 {
212 $fname = 'LoadBalancer::getConnection';
213 wfProfileIn( $fname );
214 /*
215 # Task-based index
216 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
217 if ( $i % 2 ) {
218 # Odd index use writer
219 $i = DB_MASTER;
220 } else {
221 # Even index use reader
222 $i = DB_SLAVE;
223 }
224 }*/
225
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;
234 if ( $i === -1 ) {
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();
238 }
239 }
240 # Now we have an explicit index into the servers array
241 $this->openConnection( $i, $fail );
242 wfProfileOut( $fname );
243 return $this->mConnections[$i];
244 }
245
246 /**
247 * Open a connection to the server given by the specified index
248 * Index must be an actual index into the array
249 * @private
250 */
251 function openConnection( $i, $fail = false ) {
252 $fname = 'LoadBalancer::openConnection';
253 wfProfileIn( $fname );
254
255 if ( !$this->isOpen( $i ) ) {
256 $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
257
258 if ( $i != 0 && $this->mWaitForFile ) {
259 if ( !$this->doWait( $i ) ) {
260 # Error waiting for this slave, use master instead
261 $this->mReadIndex = 0;
262 $i = 0;
263 if ( !$this->isOpen( 0 ) ) {
264 $this->mConnections[0] = $this->reallyOpenConnection( $this->mServers[0] );
265 }
266 wfDebug( "Failed over to {$this->mConnections[0]->mServer}\n" );
267 }
268 }
269 }
270 if ( !$this->isOpen( $i ) ) {
271 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
272 if ( $fail ) {
273 $this->reportConnectionError( $this->mConnections[$i] );
274 }
275 $this->mConnections[$i] = false;
276 }
277 $this->mLastIndex = $i;
278 wfProfileOut( $fname );
279 }
280
281 /**
282 * Test if the specified index represents an open connection
283 * @private
284 */
285 function isOpen( $index ) {
286 if( !is_integer( $index ) ) {
287 return false;
288 }
289 if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
290 $this->mConnections[$index]->isOpen() )
291 {
292 return true;
293 } else {
294 return false;
295 }
296 }
297
298 /**
299 * Really opens a connection
300 * @private
301 */
302 function reallyOpenConnection( &$server ) {
303 extract( $server );
304 # Get class for this database type
305 $class = 'Database' . ucfirst( $type );
306 if ( !class_exists( $class ) ) {
307 require_once( "$class.php" );
308 }
309
310 # Create object
311 return new $class( $host, $user, $password, $dbname, 1, $flags );
312 }
313
314 function reportConnectionError( &$conn )
315 {
316 $fname = 'LoadBalancer::reportConnectionError';
317 wfProfileIn( $fname );
318 # Prevent infinite recursion
319
320 static $reporting = false;
321 if ( !$reporting ) {
322 $reporting = true;
323 if ( !is_object( $conn ) ) {
324 $conn = new Database;
325 }
326 if ( $this->mFailFunction ) {
327 $conn->failFunction( $this->mFailFunction );
328 } else {
329 $conn->failFunction( 'wfEmergencyAbort' );
330 }
331 $conn->reportConnectionError();
332 $reporting = false;
333 }
334 wfProfileOut( $fname );
335 }
336
337 function getWriterIndex()
338 {
339 return 0;
340 }
341
342 function force( $i )
343 {
344 $this->mForce = $i;
345 }
346
347 function haveIndex( $i )
348 {
349 return array_key_exists( $i, $this->mServers );
350 }
351
352 /**
353 * Get the number of defined servers (not the number of open connections)
354 */
355 function getServerCount() {
356 return count( $this->mServers );
357 }
358
359 /**
360 * Save master pos to the session and to memcached, if the session exists
361 */
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" );
371 } else {
372 $conn =& $this->getConnection( 0 );
373 list( $file, $pos ) = $conn->getMasterPos();
374 wfDebug( "Saving master pos: $file $pos\n" );
375 }
376 if ( $file !== false ) {
377 $_SESSION['master_log_file'] = $file;
378 $_SESSION['master_pos'] = $pos;
379 }
380 }
381 }
382
383 /**
384 * Loads the master pos from the session, waits for it if necessary
385 */
386 function loadMasterPos() {
387 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
388 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
389 }
390 }
391
392 /**
393 * Close all open connections
394 */
395 function closeAll() {
396 foreach( $this->mConnections as $i => $conn ) {
397 if ( $this->isOpen( $i ) ) {
398 $conn->close();
399 }
400 }
401 }
402
403 function commitAll() {
404 foreach( $this->mConnections as $i => $conn ) {
405 if ( $this->isOpen( $i ) ) {
406 $conn->immediateCommit();
407 }
408 }
409 }
410 }