Merge "[FileRepo] Added hook to let us copy thumbnails into additional places as...
[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 $this->reportConnectionError( $this->mErrorConnection );
501 wfProfileOut( __METHOD__ );
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 $this->reportConnectionError( $this->mErrorConnection );
510 }
511
512 wfProfileOut( __METHOD__ );
513 return $conn;
514 }
515
516 /**
517 * Mark a foreign connection as being available for reuse under a different
518 * DB name or prefix. This mechanism is reference-counted, and must be called
519 * the same number of times as getConnection() to work.
520 *
521 * @param DatabaseBase $conn
522 */
523 public function reuseConnection( $conn ) {
524 $serverIndex = $conn->getLBInfo('serverIndex');
525 $refCount = $conn->getLBInfo('foreignPoolRefCount');
526 $dbName = $conn->getDBname();
527 $prefix = $conn->tablePrefix();
528 if ( strval( $prefix ) !== '' ) {
529 $wiki = "$dbName-$prefix";
530 } else {
531 $wiki = $dbName;
532 }
533 if ( $serverIndex === null || $refCount === null ) {
534 wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
535 /**
536 * This can happen in code like:
537 * foreach ( $dbs as $db ) {
538 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
539 * ...
540 * $lb->reuseConnection( $conn );
541 * }
542 * When a connection to the local DB is opened in this way, reuseConnection()
543 * should be ignored
544 */
545 return;
546 }
547 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
548 throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
549 }
550 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
551 if ( $refCount <= 0 ) {
552 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
553 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
554 wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
555 } else {
556 wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
557 }
558 }
559
560 /**
561 * Open a connection to the server given by the specified index
562 * Index must be an actual index into the array.
563 * If the server is already open, returns it.
564 *
565 * On error, returns false, and the connection which caused the
566 * error will be available via $this->mErrorConnection.
567 *
568 * @param $i Integer server index
569 * @param $wiki String wiki ID to open
570 * @return DatabaseBase
571 *
572 * @access private
573 */
574 function openConnection( $i, $wiki = false ) {
575 wfProfileIn( __METHOD__ );
576 if ( $wiki !== false ) {
577 $conn = $this->openForeignConnection( $i, $wiki );
578 wfProfileOut( __METHOD__);
579 return $conn;
580 }
581 if ( isset( $this->mConns['local'][$i][0] ) ) {
582 $conn = $this->mConns['local'][$i][0];
583 } else {
584 $server = $this->mServers[$i];
585 $server['serverIndex'] = $i;
586 $conn = $this->reallyOpenConnection( $server, false );
587 if ( $conn->isOpen() ) {
588 $this->mConns['local'][$i][0] = $conn;
589 } else {
590 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
591 $this->mErrorConnection = $conn;
592 $conn = false;
593 }
594 }
595 wfProfileOut( __METHOD__ );
596 return $conn;
597 }
598
599 /**
600 * Open a connection to a foreign DB, or return one if it is already open.
601 *
602 * Increments a reference count on the returned connection which locks the
603 * connection to the requested wiki. This reference count can be
604 * decremented by calling reuseConnection().
605 *
606 * If a connection is open to the appropriate server already, but with the wrong
607 * database, it will be switched to the right database and returned, as long as
608 * it has been freed first with reuseConnection().
609 *
610 * On error, returns false, and the connection which caused the
611 * error will be available via $this->mErrorConnection.
612 *
613 * @param $i Integer: server index
614 * @param $wiki String: wiki ID to open
615 * @return DatabaseBase
616 */
617 function openForeignConnection( $i, $wiki ) {
618 wfProfileIn(__METHOD__);
619 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
620 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
621 // Reuse an already-used connection
622 $conn = $this->mConns['foreignUsed'][$i][$wiki];
623 wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
624 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
625 // Reuse a free connection for the same wiki
626 $conn = $this->mConns['foreignFree'][$i][$wiki];
627 unset( $this->mConns['foreignFree'][$i][$wiki] );
628 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
629 wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
630 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
631 // Reuse a connection from another wiki
632 $conn = reset( $this->mConns['foreignFree'][$i] );
633 $oldWiki = key( $this->mConns['foreignFree'][$i] );
634
635 if ( !$conn->selectDB( $dbName ) ) {
636 $this->mLastError = "Error selecting database $dbName on server " .
637 $conn->getServer() . " from client host " . wfHostname() . "\n";
638 $this->mErrorConnection = $conn;
639 $conn = false;
640 } else {
641 $conn->tablePrefix( $prefix );
642 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
643 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
644 wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
645 }
646 } else {
647 // Open a new connection
648 $server = $this->mServers[$i];
649 $server['serverIndex'] = $i;
650 $server['foreignPoolRefCount'] = 0;
651 $conn = $this->reallyOpenConnection( $server, $dbName );
652 if ( !$conn->isOpen() ) {
653 wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
654 $this->mErrorConnection = $conn;
655 $conn = false;
656 } else {
657 $conn->tablePrefix( $prefix );
658 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
659 wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
660 }
661 }
662
663 // Increment reference count
664 if ( $conn ) {
665 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
666 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
667 }
668 wfProfileOut(__METHOD__);
669 return $conn;
670 }
671
672 /**
673 * Test if the specified index represents an open connection
674 *
675 * @param $index Integer: server index
676 * @access private
677 * @return bool
678 */
679 function isOpen( $index ) {
680 if( !is_integer( $index ) ) {
681 return false;
682 }
683 return (bool)$this->getAnyOpenConnection( $index );
684 }
685
686 /**
687 * Really opens a connection. Uncached.
688 * Returns a Database object whether or not the connection was successful.
689 * @access private
690 *
691 * @param $server
692 * @param $dbNameOverride bool
693 * @return DatabaseBase
694 */
695 function reallyOpenConnection( $server, $dbNameOverride = false ) {
696 if( !is_array( $server ) ) {
697 throw new MWException( 'You must update your load-balancing configuration. ' .
698 'See DefaultSettings.php entry for $wgDBservers.' );
699 }
700
701 $host = $server['host'];
702 $dbname = $server['dbname'];
703
704 if ( $dbNameOverride !== false ) {
705 $server['dbname'] = $dbname = $dbNameOverride;
706 }
707
708 # Create object
709 wfDebug( "Connecting to $host $dbname...\n" );
710 try {
711 $db = DatabaseBase::factory( $server['type'], $server );
712 } catch ( DBConnectionError $e ) {
713 // FIXME: This is probably the ugliest thing I have ever done to
714 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
715 $db = $e->db;
716 }
717
718 if ( $db->isOpen() ) {
719 wfDebug( "Connected to $host $dbname.\n" );
720 } else {
721 wfDebug( "Connection failed to $host $dbname.\n" );
722 }
723 $db->setLBInfo( $server );
724 if ( isset( $server['fakeSlaveLag'] ) ) {
725 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
726 }
727 if ( isset( $server['fakeMaster'] ) ) {
728 $db->setFakeMaster( true );
729 }
730 return $db;
731 }
732
733 /**
734 * @param $conn
735 * @throws DBConnectionError
736 */
737 function reportConnectionError( &$conn ) {
738 wfProfileIn( __METHOD__ );
739
740 if ( !is_object( $conn ) ) {
741 // No last connection, probably due to all servers being too busy
742 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
743 $conn = new Database;
744 // If all servers were busy, mLastError will contain something sensible
745 throw new DBConnectionError( $conn, $this->mLastError );
746 } else {
747 $server = $conn->getProperty( 'mServer' );
748 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
749 $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
750 }
751 wfProfileOut( __METHOD__ );
752 }
753
754 /**
755 * @return int
756 */
757 function getWriterIndex() {
758 return 0;
759 }
760
761 /**
762 * Returns true if the specified index is a valid server index
763 *
764 * @param $i
765 * @return bool
766 */
767 function haveIndex( $i ) {
768 return array_key_exists( $i, $this->mServers );
769 }
770
771 /**
772 * Returns true if the specified index is valid and has non-zero load
773 *
774 * @param $i
775 * @return bool
776 */
777 function isNonZeroLoad( $i ) {
778 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
779 }
780
781 /**
782 * Get the number of defined servers (not the number of open connections)
783 *
784 * @return int
785 */
786 function getServerCount() {
787 return count( $this->mServers );
788 }
789
790 /**
791 * Get the host name or IP address of the server with the specified index
792 * Prefer a readable name if available.
793 * @param $i
794 * @return string
795 */
796 function getServerName( $i ) {
797 if ( isset( $this->mServers[$i]['hostName'] ) ) {
798 return $this->mServers[$i]['hostName'];
799 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
800 return $this->mServers[$i]['host'];
801 } else {
802 return '';
803 }
804 }
805
806 /**
807 * Return the server info structure for a given index, or false if the index is invalid.
808 * @param $i
809 * @return bool
810 */
811 function getServerInfo( $i ) {
812 if ( isset( $this->mServers[$i] ) ) {
813 return $this->mServers[$i];
814 } else {
815 return false;
816 }
817 }
818
819 /**
820 * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
821 * @param $i
822 * @param $serverInfo
823 */
824 function setServerInfo( $i, $serverInfo ) {
825 $this->mServers[$i] = $serverInfo;
826 }
827
828 /**
829 * Get the current master position for chronology control purposes
830 * @return mixed
831 */
832 function getMasterPos() {
833 # If this entire request was served from a slave without opening a connection to the
834 # master (however unlikely that may be), then we can fetch the position from the slave.
835 $masterConn = $this->getAnyOpenConnection( 0 );
836 if ( !$masterConn ) {
837 for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
838 $conn = $this->getAnyOpenConnection( $i );
839 if ( $conn ) {
840 wfDebug( "Master pos fetched from slave\n" );
841 return $conn->getSlavePos();
842 }
843 }
844 } else {
845 wfDebug( "Master pos fetched from master\n" );
846 return $masterConn->getMasterPos();
847 }
848 return false;
849 }
850
851 /**
852 * Close all open connections
853 */
854 function closeAll() {
855 foreach ( $this->mConns as $conns2 ) {
856 foreach ( $conns2 as $conns3 ) {
857 foreach ( $conns3 as $conn ) {
858 $conn->close();
859 }
860 }
861 }
862 $this->mConns = array(
863 'local' => array(),
864 'foreignFree' => array(),
865 'foreignUsed' => array(),
866 );
867 }
868
869 /**
870 * Deprecated function, typo in function name
871 *
872 * @deprecated in 1.18
873 * @param $conn
874 */
875 function closeConnecton( $conn ) {
876 wfDeprecated( __METHOD__, '1.18' );
877 $this->closeConnection( $conn );
878 }
879
880 /**
881 * Close a connection
882 * Using this function makes sure the LoadBalancer knows the connection is closed.
883 * If you use $conn->close() directly, the load balancer won't update its state.
884 * @param $conn DatabaseBase
885 */
886 function closeConnection( $conn ) {
887 $done = false;
888 foreach ( $this->mConns as $i1 => $conns2 ) {
889 foreach ( $conns2 as $i2 => $conns3 ) {
890 foreach ( $conns3 as $i3 => $candidateConn ) {
891 if ( $conn === $candidateConn ) {
892 $conn->close();
893 unset( $this->mConns[$i1][$i2][$i3] );
894 $done = true;
895 break;
896 }
897 }
898 }
899 }
900 if ( !$done ) {
901 $conn->close();
902 }
903 }
904
905 /**
906 * Commit transactions on all open connections
907 */
908 function commitAll() {
909 foreach ( $this->mConns as $conns2 ) {
910 foreach ( $conns2 as $conns3 ) {
911 foreach ( $conns3 as $conn ) {
912 $conn->commit( __METHOD__ );
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->doneWrites() ) {
930 $conn->commit( __METHOD__ );
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 }