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