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