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