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