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