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