Handle multiple warnings correctly in ApiBase::setWarning(). Calling this function...
[lhc/web/wiklou.git] / includes / LoadBalancer.php
index 33c23bb..4280713 100644 (file)
@@ -1,44 +1,35 @@
 <?php
 /**
- *
- * @package MediaWiki
- */
-
-/**
- * Depends on the database object
+ * @file
+ * @ingroup Database
  */
-require_once( 'Database.php' );
-
-
-# Scale polling time so that under overload conditions, the database server
-# receives a SHOW STATUS query at an average interval of this many microseconds
-define( 'AVG_STATUS_POLL', 2000 );
-
 
 /**
  * Database load balancing object
  *
  * @todo document
- * @package MediaWiki
+ * @ingroup Database
  */
 class LoadBalancer {
-       /* private */ var $mServers, $mConnections, $mLoads, $mGroupLoads;
+       /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
        /* private */ var $mFailFunction, $mErrorConnection;
-       /* private */ var $mForce, $mReadIndex, $mLastIndex, $mAllowLagged;
-       /* private */ var $mWaitForFile, $mWaitForPos, $mWaitTimeout;
+       /* private */ var $mReadIndex, $mLastIndex, $mAllowLagged;
+       /* private */ var $mWaitForPos, $mWaitTimeout;
        /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
+       /* private */ var $mParentInfo, $mLagTimes;
 
-       function LoadBalancer( $servers, $failFunction = false, $waitTimeout = 10, $waitForMasterNow = false )
+       function __construct( $servers, $failFunction = false, $waitTimeout = 10, $unused = false )
        {
                $this->mServers = $servers;
                $this->mFailFunction = $failFunction;
                $this->mReadIndex = -1;
                $this->mWriteIndex = -1;
-               $this->mForce = -1;
-               $this->mConnections = array();
-               $this->mLastIndex = 1;
+               $this->mConns = array(
+                       'local' => array(),
+                       'foreignUsed' => array(),
+                       'foreignFree' => array() );
+               $this->mLastIndex = -1;
                $this->mLoads = array();
-               $this->mWaitForFile = false;
                $this->mWaitForPos = false;
                $this->mWaitTimeout = $waitTimeout;
                $this->mLaggedSlaveMode = false;
@@ -56,9 +47,6 @@ class LoadBalancer {
                                }
                        }
                }
-               if ( $waitForMasterNow ) {
-                       $this->loadMasterPos();
-               }
        }
 
        static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
@@ -66,6 +54,13 @@ class LoadBalancer {
                return new LoadBalancer( $servers, $failFunction, $waitTimeout );
        }
 
+       /**
+        * Get or set arbitrary data used by the parent object, usually an LBFactory
+        */
+       function parentInfo( $x = null ) {
+               return wfSetVar( $this->mParentInfo, $x );
+       }
+
        /**
         * Given an array of non-normalised probabilities, this function will select
         * an element and return the appropriate key
@@ -80,8 +75,8 @@ class LoadBalancer {
                if ( $sum == 0 ) {
                        # No loads on any of them
                        # In previous versions, this triggered an unweighted random selection,
-                       # but this feature has been removed as of April 2006 to allow for strict 
-                       # separation of query groups. 
+                       # but this feature has been removed as of April 2006 to allow for strict
+                       # separation of query groups.
                        return false;
                }
                $max = mt_getrandmax();
@@ -97,12 +92,18 @@ class LoadBalancer {
                return $i;
        }
 
-       function getRandomNonLagged( $loads ) {
+       function getRandomNonLagged( $loads, $wiki = false ) {
                # Unset excessively lagged servers
-               $lags = $this->getLagTimes();
+               $lags = $this->getLagTimes( $wiki );
                foreach ( $lags as $i => $lag ) {
-                       if ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
-                               unset( $loads[$i] );
+                       if ( $i != 0 && isset( $this->mServers[$i]['max lag'] ) ) {
+                               if ( $lag === false ) {
+                                       wfDebug( "Server #$i is not replicating\n" );
+                                       unset( $loads[$i] );
+                               } elseif ( $lag > $this->mServers[$i]['max lag'] ) {
+                                       wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
+                                       unset( $loads[$i] );
+                               }
                        }
                }
 
@@ -136,108 +137,169 @@ class LoadBalancer {
         *
         * Side effect: opens connections to databases
         */
-       function getReaderIndex() {
-               global $wgReadOnly, $wgDBClusterTimeout;
+       function getReaderIndex( $group = false, $wiki = false ) {
+               global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
 
-               $fname = 'LoadBalancer::getReaderIndex';
-               wfProfileIn( $fname );
+               # FIXME: For now, only go through all this for mysql databases
+               if ($wgDBtype != 'mysql') {
+                       return $this->getWriterIndex();
+               }
 
-               $i = false;
-               if ( $this->mForce >= 0 ) {
-                       $i = $this->mForce;
-               } else {
-                       if ( $this->mReadIndex >= 0 ) {
-                               $i = $this->mReadIndex;
+               if ( count( $this->mServers ) == 1 )  {
+                       # Skip the load balancing if there's only one server
+                       return 0;
+               } elseif ( $group === false and $this->mReadIndex >= 0 ) {
+                       # Shortcut if generic reader exists already
+                       return $this->mReadIndex;
+               }
+
+               wfProfileIn( __METHOD__ );
+
+               $totalElapsed = 0;
+
+               # convert from seconds to microseconds
+               $timeout = $wgDBClusterTimeout * 1e6;
+
+               # Find the relevant load array
+               if ( $group !== false ) {
+                       if ( isset( $this->mGroupLoads[$group] ) ) {
+                               $nonErrorLoads = $this->mGroupLoads[$group];
                        } else {
-                               # $loads is $this->mLoads except with elements knocked out if they
-                               # don't work
-                               $loads = $this->mLoads;
-                               $done = false;
-                               $totalElapsed = 0;
-                               do {
-                                       if ( $wgReadOnly or $this->mAllowLagged ) {
-                                               $i = $this->pickRandom( $loads );
-                                       } else {
-                                               $i = $this->getRandomNonLagged( $loads );
-                                               if ( $i === false && count( $loads ) != 0 )  {
-                                                       # All slaves lagged. Switch to read-only mode
-                                                       $wgReadOnly = wfMsgNoDB( 'readonly_lag' );
-                                                       $i = $this->pickRandom( $loads );
-                                               }
-                                       }
-                                       $serverIndex = $i;
-                                       if ( $i !== false ) {
-                                               wfDebugLog( 'connect', "$fname: Using reader #$i: {$this->mServers[$i]['host']}...\n" );
-                                               $this->openConnection( $i );
-
-                                               if ( !$this->isOpen( $i ) ) {
-                                                       wfDebug( "$fname: Failed\n" );
-                                                       unset( $loads[$i] );
-                                                       $sleepTime = 0;
-                                               } else {
-                                                       $status = $this->mConnections[$i]->getStatus("Thread%");
-                                                       if ( isset( $this->mServers[$i]['max threads'] ) &&
-                                                         $status['Threads_running'] > $this->mServers[$i]['max threads'] )
-                                                       {
-                                                               # Too much load, back off and wait for a while.
-                                                               # The sleep time is scaled by the number of threads connected,
-                                                               # to produce a roughly constant global poll rate.
-                                                               $sleepTime = AVG_STATUS_POLL * $status['Threads_connected'];
-
-                                                               # If we reach the timeout and exit the loop, don't use it
-                                                               $i = false;
-                                                       } else {
-                                                               $done = true;
-                                                               $sleepTime = 0;
-                                                       }
-                                               }
-                                       } else {
-                                               $sleepTime = 500000;
-                                       }
-                                       if ( $sleepTime ) {
-                                                       $totalElapsed += $sleepTime;
-                                                       $x = "{$this->mServers[$serverIndex]['host']} [$serverIndex]";
-                                                       wfProfileIn( "$fname-sleep $x" );
-                                                       usleep( $sleepTime );
-                                                       wfProfileOut( "$fname-sleep $x" );
+                               # No loads for this group, return false and the caller can use some other group
+                               wfDebug( __METHOD__.": no loads for group $group\n" );
+                               wfProfileOut( __METHOD__ );
+                               return false;
+                       }
+               } else {
+                       $nonErrorLoads = $this->mLoads;
+               }
+
+               if ( !$nonErrorLoads ) {
+                       throw new MWException( "Empty server array given to LoadBalancer" );
+               }
+
+               $i = false;
+               $found = false;
+               $laggedSlaveMode = false;
+
+               # First try quickly looking through the available servers for a server that
+               # meets our criteria
+               do {
+                       $totalThreadsConnected = 0;
+                       $overloadedServers = 0;
+                       $currentLoads = $nonErrorLoads;
+                       while ( count( $currentLoads ) ) {
+                               if ( $wgReadOnly || $this->mAllowLagged || $laggedSlaveMode ) {
+                                       $i = $this->pickRandom( $currentLoads );
+                               } else {
+                                       $i = $this->getRandomNonLagged( $currentLoads, $wiki );
+                                       if ( $i === false && count( $currentLoads ) != 0 )  {
+                                               # All slaves lagged. Switch to read-only mode
+                                               $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
+                                               $i = $this->pickRandom( $currentLoads );
+                                               $laggedSlaveMode = true;
                                        }
-                               } while ( count( $loads ) && !$done && $totalElapsed / 1e6 < $wgDBClusterTimeout );
+                               }
+
+                               if ( $i === false ) {
+                                       # pickRandom() returned false
+                                       # This is permanent and means the configuration wants us to return false
+                                       wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
+                                       wfProfileOut( __METHOD__ );
+                                       return false;
+                               }
 
-                               if ( $totalElapsed / 1e6 >= $wgDBClusterTimeout ) {
-                                       $this->mErrorConnection = false;
-                                       $this->mLastError = 'All servers busy';
+                               wfDebugLog( 'connect', __METHOD__.": Using reader #$i: {$this->mServers[$i]['host']}...\n" );
+                               $conn = $this->openConnection( $i, $wiki );
+
+                               if ( !$conn ) {
+                                       wfDebugLog( 'connect', __METHOD__.": Failed connecting to $i/$wiki\n" );
+                                       unset( $nonErrorLoads[$i] );
+                                       unset( $currentLoads[$i] );
+                                       continue;
                                }
 
-                               if ( $i !== false && $this->isOpen( $i ) ) {
-                                       # Wait for the session master pos for a short time
-                                       if ( $this->mWaitForFile ) {
-                                               if ( !$this->doWait( $i ) ) {
-                                                       $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
-                                               }
+                               if ( isset( $this->mServers[$i]['max threads'] ) ) {
+                                       $status = $conn->getStatus("Thread%");
+                                       if ( $wiki !== false ) {
+                                               $this->reuseConnection( $conn );
                                        }
-                                       if ( $i !== false ) {
-                                               $this->mReadIndex = $i;
+                                       if ( $status['Threads_running'] > $this->mServers[$i]['max threads'] ) {
+                                               $totalThreadsConnected += $status['Threads_connected'];
+                                               $overloadedServers++;
+                                               unset( $currentLoads[$i] );
+                                       } else {
+                                               # Max threads satisfied, return this server
+                                               break 2;
                                        }
                                } else {
-                                       $i = false;
+                                       # No maximum, return this server
+                                       if ( $wiki !== false ) {
+                                               $this->reuseConnection( $conn );
+                                       }
+                                       $found = true;
+                                       break 2;
+                               }
+                       }
+
+                       # No server found yet
+                       $i = false;
+
+                       # If all servers were down, quit now
+                       if ( !count( $nonErrorLoads ) ) {
+                               wfDebugLog( 'connect', "All servers down\n" );
+                               break;
+                       }
+
+                       # Some servers must have been overloaded
+                       if ( $overloadedServers == 0 ) {
+                               throw new MWException( __METHOD__.": unexpectedly found no overloaded servers" );
+                       }
+                       # Back off for a while
+                       # Scale the sleep time by the number of connected threads, to produce a
+                       # roughly constant global poll rate
+                       $avgThreads = $totalThreadsConnected / $overloadedServers;
+                       $totalElapsed += $this->sleep( $wgDBAvgStatusPoll * $avgThreads );
+               } while ( $totalElapsed < $timeout );
+
+               if ( $totalElapsed >= $timeout ) {
+                       wfDebugLog( 'connect', "All servers busy\n" );
+                       $this->mErrorConnection = false;
+                       $this->mLastError = 'All servers busy';
+               }
+
+               if ( $i !== false ) {
+                       # Wait for the session master pos for a short time
+                       if ( $this->mWaitForPos && $i > 0 ) {
+                               if ( !$this->doWait( $i ) ) {
+                                       $this->mServers[$i]['slave pos'] = $conn->getSlavePos();
                                }
                        }
+                       if ( $this->mReadIndex <=0 && $this->mLoads[$i]>0 && $i !== false ) {
+                               $this->mReadIndex = $i;
+                       }
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $i;
        }
 
+       /**
+        * Wait for a specified number of microseconds, and return the period waited
+        */
+       function sleep( $t ) {
+               wfProfileIn( __METHOD__ );
+               wfDebug( __METHOD__.": waiting $t us\n" );
+               usleep( $t );
+               wfProfileOut( __METHOD__ );
+               return $t;
+       }
+
        /**
         * Get a random server to use in a query group
+        * @deprecated use getReaderIndex
         */
        function getGroupIndex( $group ) {
-               if ( isset( $this->mGroupLoads[$group] ) ) {
-                       $i = $this->pickRandom( $this->mGroupLoads[$group] );
-               } else {
-                       $i = false;
-               }
-               wfDebug( "Query group $group => $i\n" );
-               return $i;
+               return $this->getReaderIndex( $group );
        }
 
        /**
@@ -245,106 +307,94 @@ class LoadBalancer {
         * If a DB_SLAVE connection has been opened already, waits
         * Otherwise sets a variable telling it to wait if such a connection is opened
         */
-       function waitFor( $file, $pos ) {
-               $fname = 'LoadBalancer::waitFor';
-               wfProfileIn( $fname );
-
-               wfDebug( "User master pos: $file $pos\n" );
-               $this->mWaitForFile = false;
-               $this->mWaitForPos = false;
+       public function waitFor( $pos ) {
+               wfProfileIn( __METHOD__ );
+               $this->mWaitForPos = $pos;
+               $i = $this->mReadIndex;
 
-               if ( count( $this->mServers ) > 1 ) {
-                       $this->mWaitForFile = $file;
-                       $this->mWaitForPos = $pos;
-                       $i = $this->mReadIndex;
+               if ( $i > 0 ) {
+                       if ( !$this->doWait( $i ) ) {
+                               $this->mServers[$i]['slave pos'] = $this->getAnyOpenConnection( $i )->getSlavePos();
+                               $this->mLaggedSlaveMode = true;
+                       }
+               }
+               wfProfileOut( __METHOD__ );
+       }
 
-                       if ( $i > 0 ) {
-                               if ( !$this->doWait( $i ) ) {
-                                       $this->mServers[$i]['slave pos'] = $this->mConnections[$i]->getSlavePos();
-                                       $this->mLaggedSlaveMode = true;
-                               }
+       /**
+        * Get any open connection to a given server index, local or foreign
+        * Returns false if there is no connection open
+        */
+       function getAnyOpenConnection( $i ) {
+               foreach ( $this->mConns as $type => $conns ) {
+                       if ( !empty( $conns[$i] ) ) {
+                               return reset( $conns[$i] );
                        }
                }
-               wfProfileOut( $fname );
+               return false;
        }
 
        /**
         * Wait for a given slave to catch up to the master pos stored in $this
         */
        function doWait( $index ) {
-               global $wgMemc;
-
-               $retVal = false;
-
-               # Debugging hacks
-               if ( isset( $this->mServers[$index]['lagged slave'] ) ) {
+               # Find a connection to wait on
+               $conn = $this->getAnyOpenConnection( $index );
+               if ( !$conn ) {
+                       wfDebug( __METHOD__ . ": no connection open\n" );
                        return false;
-               } elseif ( isset( $this->mServers[$index]['fake slave'] ) ) {
-                       return true;
                }
 
-               $key = 'masterpos:' . $index;
-               $memcPos = $wgMemc->get( $key );
-               if ( $memcPos ) {
-                       list( $file, $pos ) = explode( ' ', $memcPos );
-                       # If the saved position is later than the requested position, return now
-                       if ( $file == $this->mWaitForFile && $this->mWaitForPos <= $pos ) {
-                               $retVal = true;
-                       }
-               }
-
-               if ( !$retVal && $this->isOpen( $index ) ) {
-                       $conn =& $this->mConnections[$index];
-                       wfDebug( "Waiting for slave #$index to catch up...\n" );
-                       $result = $conn->masterPosWait( $this->mWaitForFile, $this->mWaitForPos, $this->mWaitTimeout );
+               wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
+               $result = $conn->masterPosWait( $this->mWaitForPos, $this->mWaitTimeout );
 
-                       if ( $result == -1 || is_null( $result ) ) {
-                               # Timed out waiting for slave, use master instead
-                               wfDebug( "Timed out waiting for slave #$index pos {$this->mWaitForFile} {$this->mWaitForPos}\n" );
-                               $retVal = false;
-                       } else {
-                               $retVal = true;
-                               wfDebug( "Done\n" );
-                       }
+               if ( $result == -1 || is_null( $result ) ) {
+                       # Timed out waiting for slave, use master instead
+                       wfDebug( __METHOD__.": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
+                       return false;
+               } else {
+                       wfDebug( __METHOD__.": Done\n" );
+                       return true;
                }
-               return $retVal;
        }
 
        /**
         * Get a connection by index
+        * This is the main entry point for this class.
         */
-       function &getConnection( $i, $fail = true, $groups = array() )
-       {
+       public function &getConnection( $i, $groups = array(), $wiki = false ) {
                global $wgDBtype;
-               $fname = 'LoadBalancer::getConnection';
-               wfProfileIn( $fname );
+               wfProfileIn( __METHOD__ );
 
+               if ( $wiki === wfWikiID() ) {
+                       $wiki = false;
+               }
 
                # Query groups
-               if ( !is_array( $groups ) ) {
-                       $groupIndex = $this->getGroupIndex( $groups, $i );
+               if ( $i == DB_MASTER ) {
+                       $i = $this->getWriterIndex();
+               } elseif ( !is_array( $groups ) ) {
+                       $groupIndex = $this->getReaderIndex( $groups, $wiki );
                        if ( $groupIndex !== false ) {
+                               $serverName = $this->getServerName( $groupIndex );
+                               wfDebug( __METHOD__.": using server $serverName for group $groups\n" );
                                $i = $groupIndex;
                        }
                } else {
                        foreach ( $groups as $group ) {
-                               $groupIndex = $this->getGroupIndex( $group, $i );
+                               $groupIndex = $this->getReaderIndex( $group, $wiki );
                                if ( $groupIndex !== false ) {
+                                       $serverName = $this->getServerName( $groupIndex );
+                                       wfDebug( __METHOD__.": using server $serverName for group $group\n" );
                                        $i = $groupIndex;
                                        break;
                                }
                        }
                }
 
-               # For now, only go through all this for mysql databases
-               if ($wgDBtype != 'mysql') {
-                       $i = $this->getWriterIndex();
-               }
                # Operation-based index
-               elseif ( $i == DB_SLAVE ) {
-                       $i = $this->getReaderIndex();
-               } elseif ( $i == DB_MASTER ) {
-                       $i = $this->getWriterIndex();
+               if ( $i == DB_SLAVE ) {
+                       $i = $this->getReaderIndex( false, $wiki );
                } elseif ( $i == DB_LAST ) {
                        # Just use $this->mLastIndex, which should already be set
                        $i = $this->mLastIndex;
@@ -358,40 +408,170 @@ class LoadBalancer {
                if ( $i === false ) {
                        $this->reportConnectionError( $this->mErrorConnection );
                }
+
                # Now we have an explicit index into the servers array
-               $this->openConnection( $i, $fail );
+               $conn = $this->openConnection( $i, $wiki );
+               if ( !$conn ) {
+                       $this->reportConnectionError( $this->mErrorConnection );
+               }
+
+               wfProfileOut( __METHOD__ );
+               return $conn;
+       }
 
-               wfProfileOut( $fname );
-               return $this->mConnections[$i];
+       /**
+        * Mark a foreign connection as being available for reuse under a different
+        * DB name or prefix. This mechanism is reference-counted, and must be called
+        * the same number of times as getConnection() to work.
+        */
+       public function reuseConnection( $conn ) {
+               $serverIndex = $conn->getLBInfo('serverIndex');
+               $refCount = $conn->getLBInfo('foreignPoolRefCount');
+               $dbName = $conn->getDBname();
+               $prefix = $conn->tablePrefix();
+               if ( strval( $prefix ) !== '' ) {
+                       $wiki = "$dbName-$prefix";
+               } else {
+                       $wiki = $dbName;
+               }
+               if ( $serverIndex === null || $refCount === null ) {
+                       wfDebug( __METHOD__.": this connection was not opened as a foreign connection\n" );
+                       /**
+                        * This can happen in code like:
+                        *   foreach ( $dbs as $db ) {
+                        *     $conn = $lb->getConnection( DB_SLAVE, array(), $db );
+                        *     ...
+                        *     $lb->reuseConnection( $conn );
+                        *   }
+                        * When a connection to the local DB is opened in this way, reuseConnection()
+                        * should be ignored
+                        */
+                       return;
+               }
+               if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
+                       throw new MWException( __METHOD__.": connection not found, has the connection been freed already?" );
+               }
+               $conn->setLBInfo( 'foreignPoolRefCount', --$refCount );
+               if ( $refCount <= 0 ) {
+                       $this->mConns['foreignFree'][$serverIndex][$wiki] = $conn;
+                       unset( $this->mConns['foreignUsed'][$serverIndex][$wiki] );
+                       wfDebug( __METHOD__.": freed connection $serverIndex/$wiki\n" );
+               } else {
+                       wfDebug( __METHOD__.": reference count for $serverIndex/$wiki reduced to $refCount\n" );
+               }
        }
 
        /**
         * Open a connection to the server given by the specified index
-        * Index must be an actual index into the array
-        * Returns success
+        * Index must be an actual index into the array.
+        * If the server is already open, returns it.
+        *
+        * On error, returns false, and the connection which caused the
+        * error will be available via $this->mErrorConnection.
+        *
+        * @param integer $i Server index
+        * @param string $wiki Wiki ID to open
+        * @return Database
+        *
         * @access private
         */
-       function openConnection( $i, $fail = false ) {
-               $fname = 'LoadBalancer::openConnection';
-               wfProfileIn( $fname );
-               $success = true;
-
-               if ( !$this->isOpen( $i ) ) {
-                       $this->mConnections[$i] = $this->reallyOpenConnection( $this->mServers[$i] );
+       function openConnection( $i, $wiki = false ) {
+               wfProfileIn( __METHOD__ );
+               if ( $wiki !== false ) {
+                       $conn = $this->openForeignConnection( $i, $wiki );
+                       wfProfileOut( __METHOD__);
+                       return $conn;
                }
-
-               if ( !$this->isOpen( $i ) ) {
-                       wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
-                       if ( $fail ) {
-                               $this->reportConnectionError( $this->mConnections[$i] );
+               if ( isset( $this->mConns['local'][$i][0] ) ) {
+                       $conn = $this->mConns['local'][$i][0];
+               } else {
+                       $server = $this->mServers[$i];
+                       $server['serverIndex'] = $i;
+                       $conn = $this->reallyOpenConnection( $server );
+                       if ( $conn->isOpen() ) {
+                               $this->mConns['local'][$i][0] = $conn;
+                       } else {
+                               wfDebug( "Failed to connect to database $i at {$this->mServers[$i]['host']}\n" );
+                               $this->mErrorConnection = $conn;
+                               $conn = false;
                        }
-                       $this->mErrorConnection = $this->mConnections[$i];
-                       $this->mConnections[$i] = false;
-                       $success = false;
                }
                $this->mLastIndex = $i;
-               wfProfileOut( $fname );
-               return $success;
+               wfProfileOut( __METHOD__ );
+               return $conn;
+       }
+
+       /**
+        * Open a connection to a foreign DB, or return one if it is already open.
+        *
+        * Increments a reference count on the returned connection which locks the
+        * connection to the requested wiki. This reference count can be
+        * decremented by calling reuseConnection().
+        *
+        * If a connection is open to the appropriate server already, but with the wrong
+        * database, it will be switched to the right database and returned, as long as
+        * it has been freed first with reuseConnection().
+        *
+        * On error, returns false, and the connection which caused the
+        * error will be available via $this->mErrorConnection.
+        *
+        * @param integer $i Server index
+        * @param string $wiki Wiki ID to open
+        * @return Database
+        */
+       function openForeignConnection( $i, $wiki ) {
+               wfProfileIn(__METHOD__);
+               list( $dbName, $prefix ) = wfSplitWikiID( $wiki );
+               if ( isset( $this->mConns['foreignUsed'][$i][$wiki] ) ) {
+                       // Reuse an already-used connection
+                       $conn = $this->mConns['foreignUsed'][$i][$wiki];
+                       wfDebug( __METHOD__.": reusing connection $i/$wiki\n" );
+               } elseif ( isset( $this->mConns['foreignFree'][$i][$wiki] ) ) {
+                       // Reuse a free connection for the same wiki
+                       $conn = $this->mConns['foreignFree'][$i][$wiki];
+                       unset( $this->mConns['foreignFree'][$i][$wiki] );
+                       $this->mConns['foreignUsed'][$i][$wiki] = $conn;
+                       wfDebug( __METHOD__.": reusing free connection $i/$wiki\n" );
+               } elseif ( !empty( $this->mConns['foreignFree'][$i] ) ) {
+                       // Reuse a connection from another wiki
+                       $conn = reset( $this->mConns['foreignFree'][$i] );
+                       $oldWiki = key( $this->mConns['foreignFree'][$i] );
+
+                       if ( !$conn->selectDB( $dbName ) ) {
+                               global $wguname;
+                               $this->mLastError = "Error selecting database $dbName on server " .
+                                       $conn->getServer() . " from client host {$wguname['nodename']}\n";
+                               $this->mErrorConnection = $conn;
+                               $conn = false;
+                       } else {
+                               $conn->tablePrefix( $prefix );
+                               unset( $this->mConns['foreignFree'][$i][$oldWiki] );
+                               $this->mConns['foreignUsed'][$i][$wiki] = $conn;
+                               wfDebug( __METHOD__.": reusing free connection from $oldWiki for $wiki\n" );
+                       }
+               } else {
+                       // Open a new connection
+                       $server = $this->mServers[$i];
+                       $server['serverIndex'] = $i;
+                       $server['foreignPoolRefCount'] = 0;
+                       $conn = $this->reallyOpenConnection( $server, $dbName );
+                       if ( !$conn->isOpen() ) {
+                               wfDebug( __METHOD__.": error opening connection for $i/$wiki\n" );
+                               $this->mErrorConnection = $conn;
+                               $conn = false;
+                       } else {
+                               $this->mConns['foreignUsed'][$i][$wiki] = $conn;
+                               wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
+                       }
+               }
+
+               // Increment reference count
+               if ( $conn ) {
+                       $refCount = $conn->getLBInfo( 'foreignPoolRefCount' );
+                       $conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
+               }
+               wfProfileOut(__METHOD__);
+               return $conn;
        }
 
        /**
@@ -402,41 +582,47 @@ class LoadBalancer {
                if( !is_integer( $index ) ) {
                        return false;
                }
-               if ( array_key_exists( $index, $this->mConnections ) && is_object( $this->mConnections[$index] ) &&
-                 $this->mConnections[$index]->isOpen() )
-               {
-                       return true;
-               } else {
-                       return false;
-               }
+               return (bool)$this->getAnyOpenConnection( $index );
        }
 
        /**
-        * Really opens a connection
+        * Really opens a connection. Uncached.
+        * Returns a Database object whether or not the connection was successful.
         * @access private
         */
-       function reallyOpenConnection( &$server ) {
+       function reallyOpenConnection( $server, $dbNameOverride = false ) {
                if( !is_array( $server ) ) {
                        throw new MWException( 'You must update your load-balancing configuration. See DefaultSettings.php entry for $wgDBservers.' );
                }
 
                extract( $server );
+               if ( $dbNameOverride !== false ) {
+                       $dbname = $dbNameOverride;
+               }
+
                # Get class for this database type
                $class = 'Database' . ucfirst( $type );
-               if ( !class_exists( $class ) ) {
-                       require_once( "$class.php" );
-               }
 
                # Create object
+               wfDebug( "Connecting to $host $dbname...\n" );
                $db = new $class( $host, $user, $password, $dbname, 1, $flags );
+               if ( $db->isOpen() ) {
+                       wfDebug( "Connected\n" );
+               } else {
+                       wfDebug( "Failed\n" );
+               }
                $db->setLBInfo( $server );
+               if ( isset( $server['fakeSlaveLag'] ) ) {
+                       $db->setFakeSlaveLag( $server['fakeSlaveLag'] );
+               }
+               if ( isset( $server['fakeMaster'] ) ) {
+                       $db->setFakeMaster( true );
+               }
                return $db;
        }
 
-       function reportConnectionError( &$conn )
-       {
-               $fname = 'LoadBalancer::reportConnectionError';
-               wfProfileIn( $fname );
+       function reportConnectionError( &$conn ) {
+               wfProfileIn( __METHOD__ );
                # Prevent infinite recursion
 
                static $reporting = false;
@@ -463,23 +649,13 @@ class LoadBalancer {
                        }
                        $reporting = false;
                }
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
        }
 
        function getWriterIndex() {
                return 0;
        }
 
-       /**
-        * Force subsequent calls to getConnection(DB_SLAVE) to return the 
-        * given index. Set to -1 to restore the original load balancing
-        * behaviour. I thought this was a good idea when I originally 
-        * wrote this class, but it has never been used.
-        */
-       function force( $i ) {
-               $this->mForce = $i;
-       }
-
        /**
         * Returns true if the specified index is a valid server index
         */
@@ -502,55 +678,108 @@ class LoadBalancer {
        }
 
        /**
-        * Save master pos to the session and to memcached, if the session exists
+        * Get the host name or IP address of the server with the specified index
         */
-       function saveMasterPos() {
-               global $wgSessionStarted;
-               if ( $wgSessionStarted && count( $this->mServers ) > 1 ) {
-                       # If this entire request was served from a slave without opening a connection to the
-                       # master (however unlikely that may be), then we can fetch the position from the slave.
-                       if ( empty( $this->mConnections[0] ) ) {
-                               $conn =& $this->getConnection( DB_SLAVE );
-                               list( $file, $pos ) = $conn->getSlavePos();
-                               wfDebug( "Saving master pos fetched from slave: $file $pos\n" );
-                       } else {
-                               $conn =& $this->getConnection( 0 );
-                               list( $file, $pos ) = $conn->getMasterPos();
-                               wfDebug( "Saving master pos: $file $pos\n" );
-                       }
-                       if ( $file !== false ) {
-                               $_SESSION['master_log_file'] = $file;
-                               $_SESSION['master_pos'] = $pos;
-                       }
+       function getServerName( $i ) {
+               if ( isset( $this->mServers[$i]['hostName'] ) ) {
+                       return $this->mServers[$i]['hostName'];
+               } elseif ( isset( $this->mServers[$i]['host'] ) ) {
+                       return $this->mServers[$i]['host'];
+               } else {
+                       return '';
                }
        }
 
        /**
-        * Loads the master pos from the session, waits for it if necessary
+        * Get the current master position for chronology control purposes
+        * @return mixed
         */
-       function loadMasterPos() {
-               if ( isset( $_SESSION['master_log_file'] ) && isset( $_SESSION['master_pos'] ) ) {
-                       $this->waitFor( $_SESSION['master_log_file'], $_SESSION['master_pos'] );
+       function getMasterPos() {
+               # If this entire request was served from a slave without opening a connection to the
+               # master (however unlikely that may be), then we can fetch the position from the slave.
+               $masterConn = $this->getAnyOpenConnection( 0 );
+               if ( !$masterConn ) {
+                       for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
+                               $conn = $this->getAnyOpenConnection( $i );
+                               if ( $conn ) {
+                                       wfDebug( "Master pos fetched from slave\n" );
+                                       return $conn->getSlavePos();
+                               }
+                       }
+               } else {
+                       wfDebug( "Master pos fetched from master\n" );
+                       return $masterConn->getMasterPos();
                }
+               return false;
        }
 
        /**
         * Close all open connections
         */
        function closeAll() {
-               foreach( $this->mConnections as $i => $conn ) {
-                       if ( $this->isOpen( $i ) ) {
-                               // Need to use this syntax because $conn is a copy not a reference
-                               $this->mConnections[$i]->close();
+               foreach ( $this->mConns as $conns2 ) {
+                       foreach  ( $conns2 as $conns3 ) {
+                               foreach ( $conns3 as $conn ) {
+                                       $conn->close();
+                               }
+                       }
+               }
+               $this->mConns = array(
+                       'local' => array(),
+                       'foreignFree' => array(),
+                       'foreignUsed' => array(),
+               );
+       }
+
+       /**
+        * Close a connection
+        * Using this function makes sure the LoadBalancer knows the connection is closed.
+        * If you use $conn->close() directly, the load balancer won't update its state.
+        */
+       function closeConnecton( $conn ) {
+               $done = false;
+               foreach ( $this->mConns as $i1 => $conns2 ) {
+                       foreach ( $conns2 as $i2 => $conns3 ) {
+                               foreach ( $conns3 as $i3 => $candidateConn ) {
+                                       if ( $conn === $candidateConn ) {
+                                               $conn->close();
+                                               unset( $this->mConns[$i1][$i2][$i3] );
+                                               $done = true;
+                                               break;
+                                       }
+                               }
                        }
                }
+               if ( !$done ) {
+                       $conn->close();
+               }
        }
 
+       /**
+        * Commit transactions on all open connections
+        */
        function commitAll() {
-               foreach( $this->mConnections as $i => $conn ) {
-                       if ( $this->isOpen( $i ) ) {
-                               // Need to use this syntax because $conn is a copy not a reference
-                               $this->mConnections[$i]->immediateCommit();
+               foreach ( $this->mConns as $conns2 ) {
+                       foreach ( $conns2 as $conns3 ) {
+                               foreach ( $conns3 as $conn ) {
+                                       $conn->immediateCommit();
+                               }
+                       }
+               }
+       }
+
+       /* Issue COMMIT only on master, only if queries were done on connection */
+       function commitMasterChanges() {
+               // Always 0, but who knows.. :)
+               $masterIndex = $this->getWriterIndex();
+               foreach ( $this->mConns as $type => $conns2 ) {
+                       if ( empty( $conns2[$masterIndex] ) ) {
+                               continue;
+                       }
+                       foreach ( $conns2[$masterIndex] as $conn ) {
+                               if ( $conn->lastQuery() != '' ) {
+                                       $conn->commit();
+                               }
                        }
                }
        }
@@ -572,10 +801,12 @@ class LoadBalancer {
 
        function pingAll() {
                $success = true;
-               foreach ( $this->mConnections as $i => $conn ) {
-                       if ( $this->isOpen( $i ) ) {
-                               if ( !$this->mConnections[$i]->ping() ) {
-                                       $success = false;
+               foreach ( $this->mConns as $conns2 ) {
+                       foreach ( $conns2 as $conns3 ) {
+                               foreach ( $conns3 as $conn ) {
+                                       if ( !$conn->ping() ) {
+                                               $success = false;
+                                       }
                                }
                        }
                }
@@ -583,71 +814,81 @@ class LoadBalancer {
        }
 
        /**
-        * Get the hostname and lag time of the most-lagged slave
-        * This is useful for maintenance scripts that need to throttle their updates
+        * Get the hostname and lag time of the most-lagged slave.
+        * This is useful for maintenance scripts that need to throttle their updates.
+        * May attempt to open connections to slaves on the default DB.
         */
        function getMaxLag() {
                $maxLag = -1;
                $host = '';
                foreach ( $this->mServers as $i => $conn ) {
-                       if ( $this->openConnection( $i ) ) {
-                               $lag = $this->mConnections[$i]->getLag();
-                               if ( $lag > $maxLag ) {
-                                       $maxLag = $lag;
-                                       $host = $this->mServers[$i]['host'];
-                               }
+                       $conn = $this->getAnyOpenConnection( $i );
+                       if ( !$conn ) {
+                               $conn = $this->openConnection( $i );
+                       }
+                       if ( !$conn ) {
+                               continue;
+                       }
+                       $lag = $conn->getLag();
+                       if ( $lag > $maxLag ) {
+                               $maxLag = $lag;
+                               $host = $this->mServers[$i]['host'];
                        }
                }
                return array( $host, $maxLag );
        }
 
        /**
-        * Get lag time for each DB
-        * Results are cached for a short time in memcached
+        * Get lag time for each server
+        * Results are cached for a short time in memcached, and indefinitely in the process cache
         */
-       function getLagTimes() {
-               global $wgDBname;
-
+       function getLagTimes( $wiki = false ) {
                wfProfileIn( __METHOD__ );
-               $expiry = 5;
-               $requestRate = 10;
-
-               global $wgMemc;
-               $times = $wgMemc->get( "$wgDBname:lag_times" );
-               if ( $times ) {
-                       # Randomly recache with probability rising over $expiry
-                       $elapsed = time() - $times['timestamp'];
-                       $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
-                       if ( mt_rand( 0, $chance ) != 0 ) {
-                               unset( $times['timestamp'] );
-                               wfProfileOut( __METHOD__ );
-                               return $times;
+
+               if ( !isset( $this->mLagTimes ) ) {
+                       $expiry = 5;
+                       $requestRate = 10;
+
+                       global $wgMemc;
+                       $masterName = $this->getServerName( 0 );
+                       $memcKey = wfMemcKey( 'lag_times', $masterName );
+                       $times = $wgMemc->get( $memcKey );
+                       if ( $times ) {
+                               # Randomly recache with probability rising over $expiry
+                               $elapsed = time() - $times['timestamp'];
+                               $chance = max( 0, ( $expiry - $elapsed ) * $requestRate );
+                               if ( mt_rand( 0, $chance ) != 0 ) {
+                                       unset( $times['timestamp'] );
+                                       wfProfileOut( __METHOD__ );
+                                       return $times;
+                               }
+                               wfIncrStats( 'lag_cache_miss_expired' );
+                       } else {
+                               wfIncrStats( 'lag_cache_miss_absent' );
                        }
-                       wfIncrStats( 'lag_cache_miss_expired' );
-               } else {
-                       wfIncrStats( 'lag_cache_miss_absent' );
-               }
 
-               # Cache key missing or expired
+                       # Cache key missing or expired
 
-               $times = array();
-               foreach ( $this->mServers as $i => $conn ) {
-                       if ($i==0) { # Master
-                               $times[$i] = 0;
-                       } elseif ( $this->openConnection( $i ) ) {
-                               $times[$i] = $this->mConnections[$i]->getLag();
+                       $times = array();
+                       foreach ( $this->mServers as $i => $conn ) {
+                               if ($i == 0) { # Master
+                                       $times[$i] = 0;
+                               } elseif ( false !== ( $conn = $this->getAnyOpenConnection( $i ) ) ) {
+                                       $times[$i] = $conn->getLag();
+                               } elseif ( false !== ( $conn = $this->openConnection( $i, $wiki ) ) ) {
+                                       $times[$i] = $conn->getLag();
+                               }
                        }
-               }
 
-               # Add a timestamp key so we know when it was cached
-               $times['timestamp'] = time();
-               $wgMemc->set( "$wgDBname:lag_times", $times, $expiry );
+                       # Add a timestamp key so we know when it was cached
+                       $times['timestamp'] = time();
+                       $wgMemc->set( $memcKey, $times, $expiry );
 
-               # But don't give the timestamp to the caller
-               unset($times['timestamp']);
+                       # But don't give the timestamp to the caller
+                       unset($times['timestamp']);
+                       $this->mLagTimes = $times;
+               }
                wfProfileOut( __METHOD__ );
-               return $times;
+               return $this->mLagTimes;
        }
 }
-
-?>