Merge "Remove user preference "noconvertlink""
[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 $dbName = $conn->getDBname();
497 $prefix = $conn->tablePrefix();
498 if ( strval( $prefix ) !== '' ) {
499 $wiki = "$dbName-$prefix";
500 } else {
501 $wiki = $dbName;
502 }
503 if ( $serverIndex === null || $refCount === null ) {
504 wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
505
506 /**
507 * This can happen in code like:
508 * foreach ( $dbs as $db ) {
509 * $conn = $lb->getConnection( DB_SLAVE, array(), $db );
510 * ...
511 * $lb->reuseConnection( $conn );
512 * }
513 * When a connection to the local DB is opened in this way, reuseConnection()
514 * should be ignored
515 */
516
517 return;
518 }
519 if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
520 throw new MWException( __METHOD__ . ": connection not found, has " .
521 "the connection been freed already?" );
522 }
523 $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
524 if ( $refCount <= 0 ) {
525 $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
526 unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
527 wfDebug( __METHOD__ . ": freed connection $serverIndex/$wiki\n" );
528 } else {
529 wfDebug( __METHOD__ . ": reference count for $serverIndex/$wiki reduced to $refCount\n" );
530 }
531 }
532
533 /**
534 * Get a database connection handle reference
535 *
536 * The handle's methods wrap simply wrap those of a DatabaseBase handle
537 *
538 * @see LoadBalancer::getConnection() for parameter information
539 *
540 * @param integer $db
541 * @param mixed $groups
542 * @param bool|string $wiki
543 * @return DBConnRef
544 */
545 public function getConnectionRef( $db, $groups = array(), $wiki = false ) {
546 return new DBConnRef( $this, $this->getConnection( $db, $groups, $wiki ) );
547 }
548
549 /**
550 * Get a database connection handle reference without connecting yet
551 *
552 * The handle's methods wrap simply wrap those of a DatabaseBase handle
553 *
554 * @see LoadBalancer::getConnection() for parameter information
555 *
556 * @param integer $db
557 * @param mixed $groups
558 * @param bool|string $wiki
559 * @return DBConnRef
560 */
561 public function getLazyConnectionRef( $db, $groups = array(), $wiki = false ) {
562 return new DBConnRef( $this, array( $db, $groups, $wiki ) );
563 }
564
565 /**
566 * Open a connection to the server given by the specified index
567 * Index must be an actual index into the array.
568 * If the server is already open, returns it.
569 *
570 * On error, returns false, and the connection which caused the
571 * error will be available via $this->mErrorConnection.
572 *
573 * @param $i Integer server index
574 * @param bool|string $wiki wiki ID to open
575 * @return DatabaseBase
576 *
577 * @access private
578 */
579 function openConnection( $i, $wiki = false ) {
580 wfProfileIn( __METHOD__ );
581 if ( $wiki !== false ) {
582 $conn = $this->openForeignConnection( $i, $wiki );
583 wfProfileOut( __METHOD__ );
584
585 return $conn;
586 }
587 if ( isset( $this->mConns['local'][$i][0] ) ) {
588 $conn = $this->mConns['local'][$i][0];
589 } else {
590 $server = $this->mServers[$i];
591 $server['serverIndex'] = $i;
592 $conn = $this->reallyOpenConnection( $server, false );
593 if ( $conn->isOpen() ) {
594 wfDebug( "Connected to database $i at {$this->mServers[$i]['host']}\n" );
595 $this->mConns['local'][$i][0] = $conn;
596 } else {
597 wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
598 $this->mErrorConnection = $conn;
599 $conn = false;
600 }
601 }
602 wfProfileOut( __METHOD__ );
603
604 return $conn;
605 }
606
607 /**
608 * Open a connection to a foreign DB, or return one if it is already open.
609 *
610 * Increments a reference count on the returned connection which locks the
611 * connection to the requested wiki. This reference count can be
612 * decremented by calling reuseConnection().
613 *
614 * If a connection is open to the appropriate server already, but with the wrong
615 * database, it will be switched to the right database and returned, as long as
616 * it has been freed first with reuseConnection().
617 *
618 * On error, returns false, and the connection which caused the
619 * error will be available via $this->mErrorConnection.
620 *
621 * @param $i Integer: server index
622 * @param string $wiki wiki ID to open
623 * @return DatabaseBase
624 */
625 function openForeignConnection( $i, $wiki ) {
626 wfProfileIn( __METHOD__ );
627 list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
628 if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
629 // Reuse an already-used connection
630 $conn = $this->mConns['foreignUsed'][$i][$wiki];
631 wfDebug( __METHOD__ . ": reusing connection $i/$wiki\n" );
632 } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
633 // Reuse a free connection for the same wiki
634 $conn = $this->mConns['foreignFree'][$i][$wiki];
635 unset( $this->mConns['foreignFree'][$i][$wiki] );
636 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
637 wfDebug( __METHOD__ . ": reusing free connection $i/$wiki\n" );
638 } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
639 // Reuse a connection from another wiki
640 $conn = reset( $this->mConns['foreignFree'][$i] );
641 $oldWiki = key( $this->mConns['foreignFree'][$i] );
642
643 if ( !$conn->selectDB( $dbName ) ) {
644 $this->mLastError = "Error selecting database $dbName on server " .
645 $conn->getServer() . " from client host " . wfHostname() . "\n";
646 $this->mErrorConnection = $conn;
647 $conn = false;
648 } else {
649 $conn->tablePrefix( $prefix );
650 unset( $this->mConns['foreignFree'][$i][$oldWiki] );
651 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
652 wfDebug( __METHOD__ . ": reusing free connection from $oldWiki for $wiki\n" );
653 }
654 } else {
655 // Open a new connection
656 $server = $this->mServers[$i];
657 $server['serverIndex'] = $i;
658 $server['foreignPoolRefCount'] = 0;
659 $server['foreign'] = true;
660 $conn = $this->reallyOpenConnection( $server, $dbName );
661 if ( !$conn->isOpen() ) {
662 wfDebug( __METHOD__ . ": error opening connection for $i/$wiki\n" );
663 $this->mErrorConnection = $conn;
664 $conn = false;
665 } else {
666 $conn->tablePrefix( $prefix );
667 $this->mConns['foreignUsed'][$i][$wiki] = $conn;
668 wfDebug( __METHOD__ . ": opened new connection for $i/$wiki\n" );
669 }
670 }
671
672 // Increment reference count
673 if ( $conn ) {
674 $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
675 $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
676 }
677 wfProfileOut( __METHOD__ );
678
679 return $conn;
680 }
681
682 /**
683 * Test if the specified index represents an open connection
684 *
685 * @param $index Integer: server index
686 * @access private
687 * @return bool
688 */
689 function isOpen( $index ) {
690 if ( !is_integer( $index ) ) {
691 return false;
692 }
693
694 return (bool)$this->getAnyOpenConnection( $index );
695 }
696
697 /**
698 * Really opens a connection. Uncached.
699 * Returns a Database object whether or not the connection was successful.
700 * @access private
701 *
702 * @param $server
703 * @param $dbNameOverride bool
704 * @throws MWException
705 * @return DatabaseBase
706 */
707 function reallyOpenConnection( $server, $dbNameOverride = false ) {
708 if ( !is_array( $server ) ) {
709 throw new MWException( 'You must update your load-balancing configuration. ' .
710 'See DefaultSettings.php entry for $wgDBservers.' );
711 }
712
713 if ( $dbNameOverride !== false ) {
714 $server['dbname'] = $dbNameOverride;
715 }
716
717 # Create object
718 try {
719 $db = DatabaseBase::factory( $server['type'], $server );
720 } catch ( DBConnectionError $e ) {
721 // FIXME: This is probably the ugliest thing I have ever done to
722 // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
723 $db = $e->db;
724 }
725
726 $db->setLBInfo( $server );
727 if ( isset( $server['fakeSlaveLag'] ) ) {
728 $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
729 }
730 if ( isset( $server['fakeMaster'] ) ) {
731 $db->setFakeMaster( true );
732 }
733
734 return $db;
735 }
736
737 /**
738 * @throws DBConnectionError
739 * @return bool
740 */
741 private function reportConnectionError() {
742 $conn = $this->mErrorConnection; // The connection which caused the error
743
744 if ( !is_object( $conn ) ) {
745 // No last connection, probably due to all servers being too busy
746 wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
747
748 // If all servers were busy, mLastError will contain something sensible
749 throw new DBConnectionError( null, $this->mLastError );
750 } else {
751 $server = $conn->getProperty( 'mServer' );
752 wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
753 $conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
754 }
755
756 return false; /* not reached */
757 }
758
759 /**
760 * @return int
761 */
762 function getWriterIndex() {
763 return 0;
764 }
765
766 /**
767 * Returns true if the specified index is a valid server index
768 *
769 * @param string $i
770 * @return bool
771 */
772 function haveIndex( $i ) {
773 return array_key_exists( $i, $this->mServers );
774 }
775
776 /**
777 * Returns true if the specified index is valid and has non-zero load
778 *
779 * @param string $i
780 * @return bool
781 */
782 function isNonZeroLoad( $i ) {
783 return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
784 }
785
786 /**
787 * Get the number of defined servers (not the number of open connections)
788 *
789 * @return int
790 */
791 function getServerCount() {
792 return count( $this->mServers );
793 }
794
795 /**
796 * Get the host name or IP address of the server with the specified index
797 * Prefer a readable name if available.
798 * @param string $i
799 * @return string
800 */
801 function getServerName( $i ) {
802 if ( isset( $this->mServers[$i]['hostName'] ) ) {
803 return $this->mServers[$i]['hostName'];
804 } elseif ( isset( $this->mServers[$i]['host'] ) ) {
805 return $this->mServers[$i]['host'];
806 } else {
807 return '';
808 }
809 }
810
811 /**
812 * Return the server info structure for a given index, or false if the index is invalid.
813 * @param $i
814 * @return bool
815 */
816 function getServerInfo( $i ) {
817 if ( isset( $this->mServers[$i] ) ) {
818 return $this->mServers[$i];
819 } else {
820 return false;
821 }
822 }
823
824 /**
825 * Sets the server info structure for the given index. Entry at index $i
826 * is created if it doesn't exist
827 * @param $i
828 * @param $serverInfo
829 */
830 function setServerInfo( $i, $serverInfo ) {
831 $this->mServers[$i] = $serverInfo;
832 }
833
834 /**
835 * Get the current master position for chronology control purposes
836 * @return mixed
837 */
838 function getMasterPos() {
839 # If this entire request was served from a slave without opening a connection to the
840 # master (however unlikely that may be), then we can fetch the position from the slave.
841 $masterConn = $this->getAnyOpenConnection( 0 );
842 if ( !$masterConn ) {
843 $serverCount = count( $this->mServers );
844 for ( $i = 1; $i < $serverCount; $i++ ) {
845 $conn = $this->getAnyOpenConnection( $i );
846 if ( $conn ) {
847 wfDebug( "Master pos fetched from slave\n" );
848
849 return $conn->getSlavePos();
850 }
851 }
852 } else {
853 wfDebug( "Master pos fetched from master\n" );
854
855 return $masterConn->getMasterPos();
856 }
857
858 return false;
859 }
860
861 /**
862 * Close all open connections
863 */
864 function closeAll() {
865 foreach ( $this->mConns as $conns2 ) {
866 foreach ( $conns2 as $conns3 ) {
867 /** @var DatabaseBase $conn */
868 foreach ( $conns3 as $conn ) {
869 $conn->close();
870 }
871 }
872 }
873 $this->mConns = array(
874 'local' => array(),
875 'foreignFree' => array(),
876 'foreignUsed' => array(),
877 );
878 }
879
880 /**
881 * Deprecated function, typo in function name
882 *
883 * @deprecated in 1.18
884 * @param DatabaseBase $conn
885 */
886 function closeConnecton( $conn ) {
887 wfDeprecated( __METHOD__, '1.18' );
888 $this->closeConnection( $conn );
889 }
890
891 /**
892 * Close a connection
893 * Using this function makes sure the LoadBalancer knows the connection is closed.
894 * If you use $conn->close() directly, the load balancer won't update its state.
895 * @param DatabaseBase $conn
896 */
897 function closeConnection( $conn ) {
898 $done = false;
899 foreach ( $this->mConns as $i1 => $conns2 ) {
900 foreach ( $conns2 as $i2 => $conns3 ) {
901 foreach ( $conns3 as $i3 => $candidateConn ) {
902 if ( $conn === $candidateConn ) {
903 $conn->close();
904 unset( $this->mConns[$i1][$i2][$i3] );
905 $done = true;
906 break;
907 }
908 }
909 }
910 }
911 if ( !$done ) {
912 $conn->close();
913 }
914 }
915
916 /**
917 * Commit transactions on all open connections
918 */
919 function commitAll() {
920 foreach ( $this->mConns as $conns2 ) {
921 foreach ( $conns2 as $conns3 ) {
922 /** @var DatabaseBase[] $conns3 */
923 foreach ( $conns3 as $conn ) {
924 if ( $conn->trxLevel() ) {
925 $conn->commit( __METHOD__, 'flush' );
926 }
927 }
928 }
929 }
930 }
931
932 /**
933 * Issue COMMIT only on master, only if queries were done on connection
934 */
935 function commitMasterChanges() {
936 // Always 0, but who knows.. :)
937 $masterIndex = $this->getWriterIndex();
938 foreach ( $this->mConns as $conns2 ) {
939 if ( empty( $conns2[$masterIndex] ) ) {
940 continue;
941 }
942 /** @var DatabaseBase $conn */
943 foreach ( $conns2[$masterIndex] as $conn ) {
944 if ( $conn->trxLevel() && $conn->writesOrCallbacksPending() ) {
945 $conn->commit( __METHOD__, 'flush' );
946 }
947 }
948 }
949 }
950
951 /**
952 * @param $value null
953 * @return Mixed
954 */
955 function waitTimeout( $value = null ) {
956 return wfSetVar( $this->mWaitTimeout, $value );
957 }
958
959 /**
960 * @return bool
961 */
962 function getLaggedSlaveMode() {
963 return $this->mLaggedSlaveMode;
964 }
965
966 /**
967 * Disables/enables lag checks
968 * @param null|bool $mode
969 * @return bool
970 */
971 function allowLagged( $mode = null ) {
972 if ( $mode === null ) {
973 return $this->mAllowLagged;
974 }
975 $this->mAllowLagged = $mode;
976
977 return $this->mAllowLagged;
978 }
979
980 /**
981 * @return bool
982 */
983 function pingAll() {
984 $success = true;
985 foreach ( $this->mConns as $conns2 ) {
986 foreach ( $conns2 as $conns3 ) {
987 /** @var DatabaseBase[] $conns3 */
988 foreach ( $conns3 as $conn ) {
989 if ( !$conn->ping() ) {
990 $success = false;
991 }
992 }
993 }
994 }
995
996 return $success;
997 }
998
999 /**
1000 * Call a function with each open connection object
1001 * @param callable $callback
1002 * @param array $params
1003 */
1004 function forEachOpenConnection( $callback, $params = array() ) {
1005 foreach ( $this->mConns as $conns2 ) {
1006 foreach ( $conns2 as $conns3 ) {
1007 foreach ( $conns3 as $conn ) {
1008 $mergedParams = array_merge( array( $conn ), $params );
1009 call_user_func_array( $callback, $mergedParams );
1010 }
1011 }
1012 }
1013 }
1014
1015 /**
1016 * Get the hostname and lag time of the most-lagged slave.
1017 * This is useful for maintenance scripts that need to throttle their updates.
1018 * May attempt to open connections to slaves on the default DB. If there is
1019 * no lag, the maximum lag will be reported as -1.
1020 *
1021 * @param bool|string $wiki Wiki ID, or false for the default database
1022 * @return array ( host, max lag, index of max lagged host )
1023 */
1024 function getMaxLag( $wiki = false ) {
1025 $maxLag = -1;
1026 $host = '';
1027 $maxIndex = 0;
1028 if ( $this->getServerCount() > 1 ) { // no replication = no lag
1029 foreach ( $this->mServers as $i => $conn ) {
1030 $conn = false;
1031 if ( $wiki === false ) {
1032 $conn = $this->getAnyOpenConnection( $i );
1033 }
1034 if ( !$conn ) {
1035 $conn = $this->openConnection( $i, $wiki );
1036 }
1037 if ( !$conn ) {
1038 continue;
1039 }
1040 $lag = $conn->getLag();
1041 if ( $lag > $maxLag ) {
1042 $maxLag = $lag;
1043 $host = $this->mServers[$i]['host'];
1044 $maxIndex = $i;
1045 }
1046 }
1047 }
1048
1049 return array( $host, $maxLag, $maxIndex );
1050 }
1051
1052 /**
1053 * Get lag time for each server
1054 * Results are cached for a short time in memcached, and indefinitely in the process cache
1055 *
1056 * @param string|bool $wiki
1057 * @return array
1058 */
1059 function getLagTimes( $wiki = false ) {
1060 # Try process cache
1061 if ( isset( $this->mLagTimes ) ) {
1062 return $this->mLagTimes;
1063 }
1064 if ( $this->getServerCount() == 1 ) {
1065 # No replication
1066 $this->mLagTimes = array( 0 => 0 );
1067 } else {
1068 # Send the request to the load monitor
1069 $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
1070 array_keys( $this->mServers ), $wiki );
1071 }
1072
1073 return $this->mLagTimes;
1074 }
1075
1076 /**
1077 * Get the lag in seconds for a given connection, or zero if this load
1078 * balancer does not have replication enabled.
1079 *
1080 * This should be used in preference to Database::getLag() in cases where
1081 * replication may not be in use, since there is no way to determine if
1082 * replication is in use at the connection level without running
1083 * potentially restricted queries such as SHOW SLAVE STATUS. Using this
1084 * function instead of Database::getLag() avoids a fatal error in this
1085 * case on many installations.
1086 *
1087 * @param DatabaseBase $conn
1088 * @return int
1089 */
1090 function safeGetLag( $conn ) {
1091 if ( $this->getServerCount() == 1 ) {
1092 return 0;
1093 } else {
1094 return $conn->getLag();
1095 }
1096 }
1097
1098 /**
1099 * Clear the cache for getLagTimes
1100 */
1101 function clearLagTimeCache() {
1102 $this->mLagTimes = null;
1103 }
1104 }
1105
1106 /**
1107 * Helper class to handle automatically marking connectons as reusable (via RAII pattern)
1108 * as well handling deferring the actual network connection until the handle is used
1109 *
1110 * @ingroup Database
1111 * @since 1.22
1112 */
1113 class DBConnRef implements IDatabase {
1114 /** @var LoadBalancer */
1115 protected $lb;
1116
1117 /** @var DatabaseBase|null */
1118 protected $conn;
1119
1120 /** @var array|null */
1121 protected $params;
1122
1123 /**
1124 * @param LoadBalancer $lb
1125 * @param DatabaseBase|array $conn Connection or (server index, group, wiki ID) array
1126 */
1127 public function __construct( LoadBalancer $lb, $conn ) {
1128 $this->lb = $lb;
1129 if ( $conn instanceof DatabaseBase ) {
1130 $this->conn = $conn;
1131 } else {
1132 $this->params = $conn;
1133 }
1134 }
1135
1136 public function __call( $name, $arguments ) {
1137 if ( $this->conn === null ) {
1138 list( $db, $groups, $wiki ) = $this->params;
1139 $this->conn = $this->lb->getConnection( $db, $groups, $wiki );
1140 }
1141
1142 return call_user_func_array( array( $this->conn, $name ), $arguments );
1143 }
1144
1145 function __destruct() {
1146 if ( $this->conn !== null ) {
1147 $this->lb->reuseConnection( $this->conn );
1148 }
1149 }
1150 }