Fixed syntax error, added missing comma
[mediawiki.git] / includes / LoadBalancer.php
blob00d2c1d48396fd800e1a392b9867aae3134ab4a4
1 <?php
2 # Database load balancing object
4 require_once( "Database.php" );
6 # Valid database indexes
7 # Operation-based indexes
8 define( "DB_SLAVE", -1 ); # Read from the slave (or only server)
9 define( "DB_MASTER", -2 ); # Write to master (or only server)
10 define( "DB_LAST", -3 ); # Whatever database was used last
12 # Obsolete aliases
13 define( "DB_READ", -1 );
14 define( "DB_WRITE", -2 );
16 # Task-based indexes
17 # ***NOT USED YET, EXPERIMENTAL***
18 # These may be defined in $wgDBservers. If they aren't, the default reader or writer will be used
19 # Even numbers are always readers, odd numbers are writers
20 define( "DB_TASK_FIRST", 1000 ); # First in list
21 define( "DB_SEARCH_R", 1000 ); # Search read
22 define( "DB_SEARCH_W", 1001 ); # Search write
23 define( "DB_ASKSQL_R", 1002 ); # Special:Asksql read
24 define( "DB_WATCHLIST_R", 1004 ); # Watchlist read
25 define( "DB_TASK_LAST", 1004) ; # Last in list
27 define( "MASTER_WAIT_TIMEOUT", 15 ); # Time to wait for a slave to synchronise
29 class LoadBalancer {
30 /* private */ var $mServers, $mConnections, $mLoads;
31 /* private */ var $mFailFunction;
32 /* private */ var $mForce, $mReadIndex, $mLastConn;
33 /* private */ var $mWaitForFile, $mWaitForPos;
35 function LoadBalancer()
37 $this->mServers = array();
38 $this->mConnections = array();
39 $this->mFailFunction = false;
40 $this->mReadIndex = -1;
41 $this->mForce = -1;
42 $this->mLastConn = false;
45 function newFromParams( $servers, $failFunction = false )
47 $lb = new LoadBalancer;
48 $lb->initialise( $servers, $failFunction = false );
49 return $lb;
52 function initialise( $servers, $failFunction = false )
54 $this->mServers = $servers;
55 $this->mFailFunction = $failFunction;
56 $this->mReadIndex = -1;
57 $this->mWriteIndex = -1;
58 $this->mForce = -1;
59 $this->mConnections = array();
60 $this->mLastConn = false;
61 $this->mLoads = array();
62 $this->mWaitForFile = false;
63 $this->mWaitForPos = false;
65 foreach( $servers as $i => $server ) {
66 $this->mLoads[$i] = $server['load'];
70 # Given an array of non-normalised probabilities, this function will select
71 # an element and return the appropriate key
72 function pickRandom( $weights )
74 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
75 return false;
78 $sum = 0;
79 foreach ( $weights as $w ) {
80 $sum += $w;
82 $max = mt_getrandmax();
83 $rand = mt_rand(0, $max) / $max * $sum;
85 $sum = 0;
86 foreach ( $weights as $i => $w ) {
87 $sum += $w;
88 if ( $sum >= $rand ) {
89 break;
92 return $i;
95 function &getReader()
97 if ( $this->mForce >= 0 ) {
98 $conn =& $this->getConnection( $this->mForce );
99 } else {
100 if ( $this->mReadIndex >= 0 ) {
101 $conn =& $this->getConnection( $this->mReadIndex );
102 } else {
103 # $loads is $this->mLoads except with elements knocked out if they
104 # don't work
105 $loads = $this->mLoads;
106 do {
107 $i = $this->pickRandom( $loads );
108 if ( $i !== false ) {
109 wfDebug( "Using reader #$i: {$this->mServers[$i]['host']}\n" );
111 $conn =& $this->getConnection( $i );
112 if ( !$conn->isOpen() ) {
113 unset( $loads[$i] );
116 } while ( $i !== false && !$conn->isOpen() );
117 if ( $conn->isOpen() ) {
118 $this->mReadIndex = $i;
122 if ( $conn === false || !$conn->isOpen() ) {
123 $this->reportConnectionError( $conn );
124 $conn = false;
126 return $conn;
129 # Set the master wait position
130 # If a DB_SLAVE connection has been opened already, waits
131 # Otherwise sets a variable telling it to wait if such a connection is opened
132 function waitFor( $file, $pos ) {
133 $this->mWaitForFile = false;
134 $this->mWaitForPos = false;
136 if ( count( $this->mServers ) == 1 ) {
137 return;
140 $this->mWaitForFile = $file;
141 $this->mWaitForPos = $pos;
143 if ( $this->mReadIndex > 0 ) {
144 $this->doWait( $this->mReadIndex );
148 # Wait for a given slave to catch up to the master pos stored in $this
149 function doWait( $index ) {
150 global $wgMemc;
152 $key = "masterpos:" . $index;
153 $memcPos = $wgMemc->get( $key );
154 if ( $memcPos ) {
155 list( $file, $pos ) = explode( ' ', $memcPos );
156 # If the saved position is later than the requested position, return now
157 if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
158 return;
162 $conn =& $this->getConnection( $index );
163 $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, MASTER_WAIT_TIMEOUT );
164 if ( $result == -1 ) {
165 # Timed out waiting for slave, use master instead
166 # This is not the ideal solution. If there are a large number of slaves, a slow
167 # replicated write query will cause the master to be swamped with reads. However
168 # that's a relatively graceful failure mode, so it will do for now.
169 $this->mReadIndex = 0;
173 function &getConnection( $i, $fail = false )
176 # Task-based index
177 if ( $i >= DB_TASK_FIRST && $i < DB_TASK_LAST ) {
178 if ( $i % 2 ) {
179 # Odd index use writer
180 $i = DB_MASTER;
181 } else {
182 # Even index use reader
183 $i = DB_SLAVE;
187 # Operation-based index
188 # Note, getReader() and getWriter() will re-enter this function
189 if ( $i == DB_SLAVE ) {
190 $this->mLastConn =& $this->getReader();
191 } elseif ( $i == DB_MASTER ) {
192 $this->mLastConn =& $this->getWriter();
193 } elseif ( $i == DB_LAST ) {
194 # Just use $this->mLastConn, which should already be set
195 if ( $this->mLastConn === false ) {
196 # Oh dear, not set, best to use the writer for safety
197 $this->mLastConn =& $this->getWriter();
199 } else {
200 # Explicit index
201 if ( !array_key_exists( $i, $this->mConnections ) || !$this->mConnections[$i]->isOpen() ) {
202 $this->mConnections[$i] = $this->makeConnection( $this->mServers[$i] );
203 if ( $i != 0 && $this->mWaitForFile ) {
204 $this->doWait( $i );
207 if ( !$this->mConnections[$i]->isOpen() ) {
208 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
209 if ( $fail ) {
210 $this->reportConnectionError( $this->mConnections[$i] );
212 $this->mConnections[$i] = false;
214 $this->mLastConn =& $this->mConnections[$i];
216 return $this->mLastConn;
219 /* private */ function makeConnection( &$server ) {
220 extract( $server );
221 # Get class for this database type
222 $class = 'Database' . ucfirst( $type );
223 if ( !class_exists( $class ) ) {
224 require_once( "$class.php" );
227 # Create object
228 return new $class( $host, $user, $password, $dbname, 1 );
231 function reportConnectionError( &$conn )
233 if ( !is_object( $conn ) ) {
234 $conn = new Database;
236 if ( $this->mFailFunction ) {
237 $conn->setFailFunction( $this->mFailFunction );
238 } else {
239 $conn->setFailFunction( "wfEmergencyAbort" );
241 $conn->reportConnectionError();
244 function &getWriter()
246 $c =& $this->getConnection( 0 );
247 if ( $c === false || !$c->isOpen() ) {
248 $this->reportConnectionError( $c );
249 $c = false;
251 return $c;
254 function force( $i )
256 $this->mForce = $i;
259 function haveIndex( $i )
261 return array_key_exists( $i, $this->mServers );
264 # Get the number of defined servers (not the number of open connections)
265 function getServerCount() {
266 return count( $this->mServers );
269 # Save master pos to the session and to memcached, if the session exists
270 function saveMasterPos() {
271 global $wgSessionStarted;
272 if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
273 # If this entire request was served from a slave without opening a connection to the
274 # master (however unlikely that may be), then we can fetch the position from the slave.
275 if ( empty( $this->mConnections[0] ) ) {
276 $conn =& $this->getConnection( DB_SLAVE );
277 list( $file, $pos ) = $conn->getSlavePos();
278 } else {
279 $conn =& $this->getConnection( 0 );
280 list( $file, $pos ) = $conn->getMasterPos();
282 if ( $file !== false ) {
283 $_SESSION['master_log_file'] = $file;
284 $_SESSION['master_pos'] = $pos;
289 # Loads the master pos from the session, waits for it if necessary
290 function loadMasterPos() {
291 if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
292 $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );