mark ApiEditPageTest as being slow tests
[lhc/web/wiklou.git] / includes / db / LoadBalancer.php
1 <?php
2 /**
3 * Database load balancing.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database load balancing object
26 *
27 * @todo document
28 * @ingroup Database
29 */
30 class LoadBalancer {
31 private $mServers, $mConns, $mLoads, $mGroupLoads;
32 private $mErrorConnection;
33 private $mReadIndex, $mAllowLagged;
34 private $mWaitForPos, $mWaitTimeout;
35 private $mLaggedSlaveMode, $mLastError = 'Unknown error';
36 private $mParentInfo, $mLagTimes;
37 private $mLoadMonitorClass, $mLoadMonitor;
38
39 /**
40 * @param $params Array with keys:
41 * servers Required. Array of server info structures.
42 * masterWaitTimeout Replication lag wait timeout
43 * loadMonitor Name of a class used to fetch server lag and load.
44 * @throws MWException
45 */
46 function __construct( $params ) {
47 if ( !isset( $params['servers'] ) ) {
48 throw new MWException( __CLASS__.': missing servers parameter' );
49 }
50 $this->mServers = $params['servers'];
51
52 if ( isset( $params['waitTimeout'] ) ) {
53 $this->mWaitTimeout = $params['waitTimeout'];
54 } else {
55 $this->mWaitTimeout = 10;
56 }
57
58 $this->mReadIndex = -1;
59 $this->mWriteIndex = -1;
60 $this->mConns = array(
61 'local' => array(),
62 'foreignUsed' => array(),
63 'foreignFree' => array() );
64 $this->mLoads = array();
65 $this->mWaitForPos = false;
66 $this->mLaggedSlaveMode = false;
67 $this->mErrorConnection = false;
68 $this->mAllowLagged = false;
69
70 if ( isset( $params['loadMonitor'] ) ) {
71 $this->mLoadMonitorClass = $params['loadMonitor'];
72 } else {
73 $master = reset( $params['servers'] );
74 if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
75 $this->mLoadMonitorClass = 'LoadMonitor_MySQL';
76 } else {
77 $this->mLoadMonitorClass = 'LoadMonitor_Null';
78 }
79 }
80
81 foreach( $params['servers'] as $i => $server ) {
82 $this->mLoads[$i] = $server['load'];
83 if ( isset( $server['groupLoads'] ) ) {
84 foreach ( $server['groupLoads'] as $group => $ratio ) {
85 if ( !isset( $this->mGroupLoads[$group] ) ) {
86 $this->mGroupLoads[$group] = array();
87 }
88 $this->mGroupLoads[$group][$i] = $ratio;
89 }
90 }
91 }
92 }
93
94 /**
95 * Get a LoadMonitor instance
96 *
97 * @return LoadMonitor
98 */
99 function getLoadMonitor() {
100 if ( !isset( $this->mLoadMonitor ) ) {
101 $class = $this->mLoadMonitorClass;
102 $this->mLoadMonitor = new $class( $this );
103 }
104 return $this->mLoadMonitor;
105 }
106
107 /**
108 * Get or set arbitrary data used by the parent object, usually an LBFactory
109 * @param $x
110 * @return Mixed
111 */
112 function parentInfo( $x = null ) {
113 return wfSetVar( $this->mParentInfo, $x );
114 }
115
116 /**
117 * Given an array of non-normalised probabilities, this function will select
118 * an element and return the appropriate key
119 *
120 * @param $weights array
121 *
122 * @return int
123 */
124 function pickRandom( $weights ) {
125 if ( !is_array( $weights ) || count( $weights ) == 0 ) {
126 return false;
127 }
128
129 $sum = array_sum( $weights );
130 if ( $sum == 0 ) {
131 # No loads on any of them
132 # In previous versions, this triggered an unweighted random selection,
133 # but this feature has been removed as of April 2006 to allow for strict
134 # separation of query groups.
135 return false;
136 }
137 $max = mt_getrandmax();
138 $rand = mt_rand( 0, $max ) / $max * $sum;
139
140 $sum = 0;
141 foreach ( $weights as $i => $w ) {
142 $sum += $w;
143 if ( $sum >= $rand ) {
144 break;
145 }
146 }
147 return $i;
148 }
149
150 /**
151 * @param $loads array
152 * @param $wiki bool
153 * @return bool|int|string
154 */
155 function getRandomNonLagged( $loads, $wiki = false ) {
156 # Unset excessively lagged servers
157 $lags = $this->getLagTimes( $wiki );
158 foreach ( $lags as $i => $lag ) {
159 if ( $i != 0 ) {
160 if ( $lag === false ) {
161 wfDebugLog( 'replication', "Server #$i is not replicating\n" );
162 unset( $loads[$i] );
163 } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
164 wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
165 unset( $loads[$i] );
166 }
167 }
168 }
169
170 # Find out if all the slaves with non-zero load are lagged
171 $sum = 0;
172 foreach ( $loads as $load ) {
173 $sum += $load;
174 }
175 if ( $sum == 0 ) {
176 # No appropriate DB servers except maybe the master and some slaves with zero load
177 # Do NOT use the master
178 # Instead, this function will return false, triggering read-only mode,
179 # and a lagged slave will be used instead.
180 return false;
181 }
182
183 if ( count( $loads ) == 0 ) {
184 return false;
185 }
186
187 #wfDebugLog( 'connect', var_export( $loads, true ) );
188
189 # Return a random representative of the remainder
190 return $this->pickRandom( $loads );
191 }
192
193 /**
194 * Get the index of the reader connection, which may be a slave
195 * This takes into account load ratios and lag times. It should
196 * always return a consistent index during a given invocation
197 *
198 * Side effect: opens connections to databases
199 * @param $group bool
200 * @param $wiki bool
201 * @throws MWException
202 * @return bool|int|string
203 */
204 function getReaderIndex( $group = false, $wiki = false ) {
205 global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
206
207 # @todo FIXME: For now, only go through all this for mysql databases
208 if ($wgDBtype != 'mysql') {
209 return $this->getWriterIndex();
210 }
211
212 if ( count( $this->mServers ) == 1 ) {
213 # Skip the load balancing if there's only one server
214 return 0;
215 } elseif ( $group === false and $this->mReadIndex >= 0 ) {
216 # Shortcut if generic reader exists already
217 return $this->mReadIndex;
218 }
219
220 wfProfileIn( __METHOD__ );
221
222 $totalElapsed = 0;
223
224 # convert from seconds to microseconds
225 $timeout = $wgDBClusterTimeout * 1e6;
226
227 # Find the relevant load array
228 if ( $group !== false ) {
229 if ( isset( $this->mGroupLoads[$group] ) ) {
230 $nonErrorLoads = $this->mGroupLoads[$group];
231 } else {
232 # No loads for this group, return false and the caller can use some other group
233 wfDebug( __METHOD__.": no loads for group $group\n" );
234 wfProfileOut( __METHOD__ );
235 return false;
236 }
237 } else {
238 $nonErrorLoads = $this->mLoads;
239 }
240
241 if ( !$nonErrorLoads ) {
242 throw new MWException( "Empty server array given to LoadBalancer" );
243 }
244
245 # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
246 $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
247
248 $laggedSlaveMode = false;
249
250 # First try quickly looking through the available servers for a server that
251 # meets our criteria
252 do {
253 $totalThreadsConnected = 0;
254 $overloadedServers = 0;
255 $currentLoads = $nonErrorLoads;
256 while ( count( $currentLoads ) ) {
257 if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
258 $i = $this->pickRandom( $currentLoads );
259 } else {
260 $i = $this->getRandomNonLagged( $currentLoads, $wiki );
261 if ( $i === false && count( $currentLoads ) != 0 ) {
262 # All slaves lagged. Switch to read-only mode
263 wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
264 $wgReadOnly = 'The database has been automatically locked ' .
265 'while the slave database servers catch up to the master';
266 $i = $this->pickRandom( $currentLoads );
267 $laggedSlaveMode = true;
268 }
269 }
270
271 if ( $i === false ) {
272 # pickRandom() returned false
273 # This is permanent and means the configuration or the load monitor
274 # wants us to return false.
275 wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
276 wfProfileOut( __METHOD__ );
277 return false;
278 }
279
280 wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
281 $conn = $this->openConnection( $i, $wiki );
282
283 if ( !$conn ) {
284 wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
285 unset( $nonErrorLoads[$i] );
286 unset( $currentLoads[$i] );
287 continue;
288 }
289
290 // Perform post-connection backoff
291 $threshold = isset( $this->mServers[$i]['max threads'] )
292 ? $this->mServers[$i]['max threads'] : false;
293 $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
294
295 // Decrement reference counter, we are finished with this connection.
296 // It will be incremented for the caller later.
297 if ( $wiki !== false ) {
298 $this->reuseConnection( $conn );
299 }
300
301 if ( $backoff ) {
302 # Post-connection overload, don't use this server for now
303 $totalThreadsConnected += $backoff;
304 $overloadedServers++;
305 unset( $currentLoads[$i] );
306 } else {
307 # Return this server
308 break 2;
309 }
310 }
311
312 # No server found yet
313 $i = false;
314
315 # If all servers were down, quit now
316 if ( !count( $nonErrorLoads ) ) {
317 wfDebugLog( 'connect', "All servers down\n" );
318 break;
319 }
320
321 # Some servers must have been overloaded
322 if ( $overloadedServers == 0 ) {
323 throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
324 }
325 # Back off for a while
326 # Scale the sleep time by the number of connected threads, to produce a
327 # roughly constant global poll rate
328 $avgThreads = $totalThreadsConnected / $overloadedServers;
329 $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
330 } while ( $totalElapsed < $timeout );
331
332 if ( $totalElapsed >= $timeout ) {
333 wfDebugLog( 'connect', "All servers busy\n" );
334 $this->mErrorConnection = false;
335 $this->mLastError = 'All servers busy';
336 }
337
338 if ( $i !== false ) {
339 # Slave connection successful
340 # Wait for the session master pos for a short time
341 if ( $this->mWaitForPos && $i > 0 ) {
342 if ( !$this->doWait( $i ) ) {
343 $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
344 }
345 }
346 if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
347 $this->mReadIndex = $i;
348 }
349 }
350 wfProfileOut( __METHOD__ );
351 return $i;
352 }
353
354 /**
355 * Wait for a specified number of microseconds, and return the period waited
356 * @param $t int
357 * @return int
358 */
359 function sleep( $t ) {
360 wfProfileIn( __METHOD__ );
361 wfDebug( __METHOD__.": waiting $t us\n" );
362 usleep( $t );
363 wfProfileOut( __METHOD__ );
364 return $t;
365 }
366
367 /**
368 * Set the master wait position
369 * If a DB_SLAVE connection has been opened already, waits
370 * Otherwise sets a variable telling it to wait if such a connection is opened
371 * @param $pos int
372 */
373 public function waitFor( $pos ) {
374 wfProfileIn( __METHOD__ );
375 $this->mWaitForPos = $pos;
376 $i = $this->mReadIndex;
377
378 if ( $i > 0 ) {
379 if ( !$this->doWait( $i ) ) {
380 $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
381 $this->mLaggedSlaveMode = true;
382 }
383 }
384 wfProfileOut( __METHOD__ );
385 }
386
387 /**
388 * Set the master wait position and wait for ALL slaves to catch up to it
389 * @param $pos int
390 */
391 public function waitForAll( $pos ) {
392 wfProfileIn( __METHOD__ );
393 $this->mWaitForPos = $pos;
394 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
395 $this->doWait( $i , true );
396 }
397 wfProfileOut( __METHOD__ );
398 }
399
400 /**
401 * Get any open connection to a given server index, local or foreign
402 * Returns false if there is no connection open
403 *
404 * @param $i int
405 * @return DatabaseBase|bool False on failure
406 */
407 function getAnyOpenConnection( $i ) {
408 foreach ( $this->mConns as $conns ) {
409 if ( !empty( $conns[$i] ) ) {
410 return reset( $conns[$i] );
411 }
412 }
413 return false;
414 }
415
416 /**
417 * Wait for a given slave to catch up to the master pos stored in $this
418 * @param $index
419 * @param $open bool
420 * @return bool
421 */
422 function doWait( $index, $open = false ) {
423 # Find a connection to wait on
424 $conn = $this->getAnyOpenConnection( $index );
425 if ( !$conn ) {
426 if ( !$open ) {
427 wfDebug( __METHOD__ . ": no connection open\n" );
428 return false;
429 } else {
430 $conn = $this->openConnection( $index );
431 if ( !$conn ) {
432 wfDebug( __METHOD__ . ": failed to open connection\n" );
433 return false;
434 }
435 }
436 }
437
438 wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
439 $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
440
441 if ( $result == -1 || is_null( $result ) ) {
442 # Timed out waiting for slave, use master instead
443 wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
444 return false;
445 } else {
446 wfDebug( __METHOD__.": Done\n" );
447 return true;
448 }
449 }
450
451 /**
452 * Get a connection by index
453 * This is the main entry point for this class.
454 *
455 * @param $i Integer: server index
456 * @param $groups Array: query groups
457 * @param bool|string $wiki Wiki ID
458 *
459 * @throws MWException
460 * @return DatabaseBase
461 */
462 public function &getConnection( $i, $groups = array(), $wiki = false ) {
463 wfProfileIn( __METHOD__ );
464
465 if ( $i == DB_LAST ) {
466 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
467 } elseif ( $i === null || $i === false ) {
468 throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
469 }
470
471 if ( $wiki === wfWikiID() ) {
472 $wiki = false;
473 }
474
475 # Query groups
476 if ( $i == DB_MASTER ) {
477 $i = $this->getWriterIndex();
478 } elseif ( !is_array( $groups ) ) {
479 $groupIndex = $this->getReaderIndex( $groups, $wiki );
480 if ( $groupIndex !== false ) {
481 $serverName = $this->getServerName( $groupIndex );
482 wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
483 $i = $groupIndex;
484 }
485 } else {
486 foreach ( $groups as $group ) {
487 $groupIndex = $this->getReaderIndex( $group, $wiki );
488 if ( $groupIndex !== false ) {
489 $serverName = $this->getServerName( $groupIndex );
490 wfDebug( __METHOD__.": using server $serverName for group $group\n" );
491 $i = $groupIndex;
492 break;
493 }
494 }
495 }
496
497 # Operation-based index
498 if ( $i == DB_SLAVE ) {
499 $i = $this->getReaderIndex( false, $wiki );
500 # Couldn't find a working server in getReaderIndex()?
501 if ( $i === false ) {
502 $this->mLastError = 'No working slave server: ' . $this->mLastError;
503 wfProfileOut( __METHOD__ );
504 $this->reportConnectionError( $this->mErrorConnection );
505 return false;
506 }
507 }
508
509 # Now we have an explicit index into the servers array
510 $conn = $this->openConnection( $i, $wiki );
511 if ( !$conn ) {
512 wfProfileOut( __METHOD__ );
513 $this->reportConnectionError( $this->mErrorConnection );
514 }
515
516 wfProfileOut( __METHOD__ );
517 return $conn;
518 }
519
520 /**
521 * Mark a foreign connection as being available for reuse under a different
522 * DB name or prefix. This mechanism is reference-counted, and must be called
523 * the same number of times as getConnection() to work.
524 *
525 * @param DatabaseBase $conn
526 * @throws MWException
527 */
528 public function reuseConnection( $conn ) {
529 $serverIndex = $conn->getLBInfo('serverIndex');
530 $refCount = $conn->getLBInfo('foreignPoolRefCount');
531 $dbName = $conn->getDBname();
532 $prefix = $conn->tablePrefix();
533 if ( strval( $prefix ) !== '' ) {
534 $wiki = "$dbName-$prefix";
535 } else {
536 $wiki = $dbName;
537 }
538 if ( $serverIndex === null || $refCount === null ) {
539 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
540 /**
541 * This can happen in code like:
542 * foreach ( $dbs as $db ) {
543 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
544 * ...
545 * $lb->reuseConnection( $conn );
546 * }
547 * When a connection to the local DB is opened in this way, reuseConnection()
548 * should be ignored
549 */
550 return;
551 }
552 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
553 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
554 }
555 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
556 if ( $refCount <= 0 ) {
557 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
558 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
559 wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
560 } else {
561 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
562 }
563 }
564
565 /**
566 * Open a connection to the server given by the specified index
567 * Index must be an actual index into the array.
568 * If the server is already open, returns it.
569 *
570 * On error, returns false, and the connection which caused the
571 * error will be available via $this->mErrorConnection.
572 *
573 * @param $i Integer server index
574 * @param $wiki String wiki ID to open
575 * @return DatabaseBase
576 *
577 * @access private
578 */
579 function openConnection( $i, $wiki = false ) {
580 wfProfileIn( __METHOD__ );
581 if ( $wiki !== false ) {
582 $conn = $this->openForeignConnection( $i, $wiki );
583 wfProfileOut( __METHOD__);
584 return $conn;
585 }
586 if ( isset( $this->mConns['local'][$i][0] ) ) {
587 $conn = $this->mConns['local'][$i][0];
588 } else {
589 $server = $this->mServers[$i];
590 $server['serverIndex'] = $i;
591 $conn = $this->reallyOpenConnection( $server, false );
592 if ( $conn->isOpen() ) {
593 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
594 $this->mConns['local'][$i][0] = $conn;
595 } else {
596 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
597 $this->mErrorConnection = $conn;
598 $conn = false;
599 }
600 }
601 wfProfileOut( __METHOD__ );
602 return $conn;
603 }
604
605 /**
606 * Open a connection to a foreign DB, or return one if it is already open.
607 *
608 * Increments a reference count on the returned connection which locks the
609 * connection to the requested wiki. This reference count can be
610 * decremented by calling reuseConnection().
611 *
612 * If a connection is open to the appropriate server already, but with the wrong
613 * database, it will be switched to the right database and returned, as long as
614 * it has been freed first with reuseConnection().
615 *
616 * On error, returns false, and the connection which caused the
617 * error will be available via $this->mErrorConnection.
618 *
619 * @param $i Integer: server index
620 * @param $wiki String: wiki ID to open
621 * @return DatabaseBase
622 */
623 function openForeignConnection( $i, $wiki ) {
624 wfProfileIn(__METHOD__);
625 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
626 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
627 // Reuse an already-used connection
628 $conn = $this->mConns['foreignUsed'][$i][$wiki];
629 wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
630 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
631 // Reuse a free connection for the same wiki
632 $conn = $this->mConns['foreignFree'][$i][$wiki];
633 unset( $this->mConns['foreignFree'][$i][$wiki] );
634 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
635 wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
636 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
637 // Reuse a connection from another wiki
638 $conn = reset( $this->mConns['foreignFree'][$i] );
639 $oldWiki = key( $this->mConns['foreignFree'][$i] );
640
641 if ( !$conn->selectDB( $dbName ) ) {
642 $this->mLastError = "Error selecting database $dbName on server " .
643 $conn->getServer() . " from client host " . wfHostname() . "\n";
644 $this->mErrorConnection = $conn;
645 $conn = false;
646 } else {
647 $conn->tablePrefix( $prefix );
648 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
649 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
650 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
651 }
652 } else {
653 // Open a new connection
654 $server = $this->mServers[$i];
655 $server['serverIndex'] = $i;
656 $server['foreignPoolRefCount'] = 0;
657 $conn = $this->reallyOpenConnection( $server, $dbName );
658 if ( !$conn->isOpen() ) {
659 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
660 $this->mErrorConnection = $conn;
661 $conn = false;
662 } else {
663 $conn->tablePrefix( $prefix );
664 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
665 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
666 }
667 }
668
669 // Increment reference count
670 if ( $conn ) {
671 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
672 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
673 }
674 wfProfileOut(__METHOD__);
675 return $conn;
676 }
677
678 /**
679 * Test if the specified index represents an open connection
680 *
681 * @param $index Integer: server index
682 * @access private
683 * @return bool
684 */
685 function isOpen( $index ) {
686 if( !is_integer( $index ) ) {
687 return false;
688 }
689 return (bool)$this->getAnyOpenConnection( $index );
690 }
691
692 /**
693 * Really opens a connection. Uncached.
694 * Returns a Database object whether or not the connection was successful.
695 * @access private
696 *
697 * @param $server
698 * @param $dbNameOverride bool
699 * @throws MWException
700 * @return DatabaseBase
701 */
702 function reallyOpenConnection( $server, $dbNameOverride = false ) {
703 if( !is_array( $server ) ) {
704 throw new MWException( 'You must update your load-balancing configuration. ' .
705 'See DefaultSettings.php entry for $wgDBservers.' );
706 }
707
708 $host = $server['host'];
709 $dbname = $server['dbname'];
710
711 if ( $dbNameOverride !== false ) {
712 $server['dbname'] = $dbname = $dbNameOverride;
713 }
714
715 # Create object
716 try {
717 $db = DatabaseBase::factory( $server['type'], $server );
718 } catch ( DBConnectionError $e ) {
719 // FIXME: This is probably the ugliest thing I have ever done to
720 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
721 $db = $e->db;
722 }
723
724 $db->setLBInfo( $server );
725 if ( isset( $server['fakeSlaveLag'] ) ) {
726 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
727 }
728 if ( isset( $server['fakeMaster'] ) ) {
729 $db->setFakeMaster( true );
730 }
731 return $db;
732 }
733
734 /**
735 * @param $conn
736 * @throws DBConnectionError
737 */
738 function reportConnectionError( &$conn ) {
739 if ( !is_object( $conn ) ) {
740 // No last connection, probably due to all servers being too busy
741 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
742 $conn = new Database;
743 // If all servers were busy, mLastError will contain something sensible
744 throw new DBConnectionError( $conn, $this->mLastError );
745 } else {
746 $server = $conn->getProperty( 'mServer' );
747 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
748 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
749 }
750 }
751
752 /**
753 * @return int
754 */
755 function getWriterIndex() {
756 return 0;
757 }
758
759 /**
760 * Returns true if the specified index is a valid server index
761 *
762 * @param $i
763 * @return bool
764 */
765 function haveIndex( $i ) {
766 return array_key_exists( $i, $this->mServers );
767 }
768
769 /**
770 * Returns true if the specified index is valid and has non-zero load
771 *
772 * @param $i
773 * @return bool
774 */
775 function isNonZeroLoad( $i ) {
776 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
777 }
778
779 /**
780 * Get the number of defined servers (not the number of open connections)
781 *
782 * @return int
783 */
784 function getServerCount() {
785 return count( $this->mServers );
786 }
787
788 /**
789 * Get the host name or IP address of the server with the specified index
790 * Prefer a readable name if available.
791 * @param $i
792 * @return string
793 */
794 function getServerName( $i ) {
795 if ( isset( $this->mServers[$i]['hostName'] ) ) {
796 return $this->mServers[$i]['hostName'];
797 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
798 return $this->mServers[$i]['host'];
799 } else {
800 return '';
801 }
802 }
803
804 /**
805 * Return the server info structure for a given index, or false if the index is invalid.
806 * @param $i
807 * @return bool
808 */
809 function getServerInfo( $i ) {
810 if ( isset( $this->mServers[$i] ) ) {
811 return $this->mServers[$i];
812 } else {
813 return false;
814 }
815 }
816
817 /**
818 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
819 * @param $i
820 * @param $serverInfo
821 */
822 function setServerInfo( $i, $serverInfo ) {
823 $this->mServers[$i] = $serverInfo;
824 }
825
826 /**
827 * Get the current master position for chronology control purposes
828 * @return mixed
829 */
830 function getMasterPos() {
831 # If this entire request was served from a slave without opening a connection to the
832 # master (however unlikely that may be), then we can fetch the position from the slave.
833 $masterConn = $this->getAnyOpenConnection( 0 );
834 if ( !$masterConn ) {
835 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
836 $conn = $this->getAnyOpenConnection( $i );
837 if ( $conn ) {
838 wfDebug( "Master pos fetched from slave\n" );
839 return $conn->getSlavePos();
840 }
841 }
842 } else {
843 wfDebug( "Master pos fetched from master\n" );
844 return $masterConn->getMasterPos();
845 }
846 return false;
847 }
848
849 /**
850 * Close all open connections
851 */
852 function closeAll() {
853 foreach ( $this->mConns as $conns2 ) {
854 foreach ( $conns2 as $conns3 ) {
855 foreach ( $conns3 as $conn ) {
856 $conn->close();
857 }
858 }
859 }
860 $this->mConns = array(
861 'local' => array(),
862 'foreignFree' => array(),
863 'foreignUsed' => array(),
864 );
865 }
866
867 /**
868 * Deprecated function, typo in function name
869 *
870 * @deprecated in 1.18
871 * @param $conn
872 */
873 function closeConnecton( $conn ) {
874 wfDeprecated( __METHOD__, '1.18' );
875 $this->closeConnection( $conn );
876 }
877
878 /**
879 * Close a connection
880 * Using this function makes sure the LoadBalancer knows the connection is closed.
881 * If you use $conn->close() directly, the load balancer won't update its state.
882 * @param $conn DatabaseBase
883 */
884 function closeConnection( $conn ) {
885 $done = false;
886 foreach ( $this->mConns as $i1 => $conns2 ) {
887 foreach ( $conns2 as $i2 => $conns3 ) {
888 foreach ( $conns3 as $i3 => $candidateConn ) {
889 if ( $conn === $candidateConn ) {
890 $conn->close();
891 unset( $this->mConns[$i1][$i2][$i3] );
892 $done = true;
893 break;
894 }
895 }
896 }
897 }
898 if ( !$done ) {
899 $conn->close();
900 }
901 }
902
903 /**
904 * Commit transactions on all open connections
905 */
906 function commitAll() {
907 foreach ( $this->mConns as $conns2 ) {
908 foreach ( $conns2 as $conns3 ) {
909 foreach ( $conns3 as $conn ) {
910 if ( $conn->trxLevel() ) {
911 $conn->commit( __METHOD__, 'flush' );
912 }
913 }
914 }
915 }
916 }
917
918 /**
919 * Issue COMMIT only on master, only if queries were done on connection
920 */
921 function commitMasterChanges() {
922 // Always 0, but who knows.. :)
923 $masterIndex = $this->getWriterIndex();
924 foreach ( $this->mConns as $conns2 ) {
925 if ( empty( $conns2[$masterIndex] ) ) {
926 continue;
927 }
928 foreach ( $conns2[$masterIndex] as $conn ) {
929 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
930 $conn->commit( __METHOD__, 'flush' );
931 }
932 }
933 }
934 }
935
936 /**
937 * @param $value null
938 * @return Mixed
939 */
940 function waitTimeout( $value = null ) {
941 return wfSetVar( $this->mWaitTimeout, $value );
942 }
943
944 /**
945 * @return bool
946 */
947 function getLaggedSlaveMode() {
948 return $this->mLaggedSlaveMode;
949 }
950
951 /**
952 * Disables/enables lag checks
953 * @param $mode null
954 * @return bool
955 */
956 function allowLagged( $mode = null ) {
957 if ( $mode === null) {
958 return $this->mAllowLagged;
959 }
960 $this->mAllowLagged = $mode;
961 }
962
963 /**
964 * @return bool
965 */
966 function pingAll() {
967 $success = true;
968 foreach ( $this->mConns as $conns2 ) {
969 foreach ( $conns2 as $conns3 ) {
970 foreach ( $conns3 as $conn ) {
971 if ( !$conn->ping() ) {
972 $success = false;
973 }
974 }
975 }
976 }
977 return $success;
978 }
979
980 /**
981 * Call a function with each open connection object
982 * @param $callback
983 * @param array $params
984 */
985 function forEachOpenConnection( $callback, $params = array() ) {
986 foreach ( $this->mConns as $conns2 ) {
987 foreach ( $conns2 as $conns3 ) {
988 foreach ( $conns3 as $conn ) {
989 $mergedParams = array_merge( array( $conn ), $params );
990 call_user_func_array( $callback, $mergedParams );
991 }
992 }
993 }
994 }
995
996 /**
997 * Get the hostname and lag time of the most-lagged slave.
998 * This is useful for maintenance scripts that need to throttle their updates.
999 * May attempt to open connections to slaves on the default DB. If there is
1000 * no lag, the maximum lag will be reported as -1.
1001 *
1002 * @param $wiki string Wiki ID, or false for the default database
1003 *
1004 * @return array ( host, max lag, index of max lagged host )
1005 */
1006 function getMaxLag( $wiki = false ) {
1007 $maxLag = -1;
1008 $host = '';
1009 $maxIndex = 0;
1010 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1011 foreach ( $this->mServers as $i => $conn ) {
1012 $conn = false;
1013 if ( $wiki === false ) {
1014 $conn = $this->getAnyOpenConnection( $i );
1015 }
1016 if ( !$conn ) {
1017 $conn = $this->openConnection( $i, $wiki );
1018 }
1019 if ( !$conn ) {
1020 continue;
1021 }
1022 $lag = $conn->getLag();
1023 if ( $lag > $maxLag ) {
1024 $maxLag = $lag;
1025 $host = $this->mServers[$i]['host'];
1026 $maxIndex = $i;
1027 }
1028 }
1029 }
1030 return array( $host, $maxLag, $maxIndex );
1031 }
1032
1033 /**
1034 * Get lag time for each server
1035 * Results are cached for a short time in memcached, and indefinitely in the process cache
1036 *
1037 * @param $wiki
1038 *
1039 * @return array
1040 */
1041 function getLagTimes( $wiki = false ) {
1042 # Try process cache
1043 if ( isset( $this->mLagTimes ) ) {
1044 return $this->mLagTimes;
1045 }
1046 if ( $this->getServerCount() == 1 ) {
1047 # No replication
1048 $this->mLagTimes = array( 0 => 0 );
1049 } else {
1050 # Send the request to the load monitor
1051 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
1052 array_keys( $this->mServers ), $wiki );
1053 }
1054 return $this->mLagTimes;
1055 }
1056
1057 /**
1058 * Get the lag in seconds for a given connection, or zero if this load
1059 * balancer does not have replication enabled.
1060 *
1061 * This should be used in preference to Database::getLag() in cases where
1062 * replication may not be in use, since there is no way to determine if
1063 * replication is in use at the connection level without running
1064 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1065 * function instead of Database::getLag() avoids a fatal error in this
1066 * case on many installations.
1067 *
1068 * @param $conn DatabaseBase
1069 *
1070 * @return int
1071 */
1072 function safeGetLag( $conn ) {
1073 if ( $this->getServerCount() == 1 ) {
1074 return 0;
1075 } else {
1076 return $conn->getLag();
1077 }
1078 }
1079
1080 /**
1081 * Clear the cache for getLagTimes
1082 */
1083 function clearLagTimeCache() {
1084 $this->mLagTimes = null;
1085 }
1086 }