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