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