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