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