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