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