Merge "Revert "jquery.byteLimit: Partial rewrite to fix logic errors""
[lhc/web/wiklou.git] / includes / db / LoadBalancer.php
index b0dc483..c40ac0c 100644 (file)
@@ -1,6 +1,21 @@
 <?php
 /**
- * Database load balancing
+ * Database load balancing.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ * http://www.gnu.org/copyleft/gpl.html
  *
  * @file
  * @ingroup Database
  * @ingroup Database
  */
 class LoadBalancer {
-       /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
-       /* private */ var $mErrorConnection;
-       /* private */ var $mReadIndex, $mAllowLagged;
-       /* private */ var $mWaitForPos, $mWaitTimeout;
-       /* private */ var $mLaggedSlaveMode, $mLastError = 'Unknown error';
-       /* private */ var $mParentInfo, $mLagTimes;
-       /* private */ var $mLoadMonitorClass, $mLoadMonitor;
+       private $mServers, $mConns, $mLoads, $mGroupLoads;
+       private $mErrorConnection;
+       private $mReadIndex, $mAllowLagged;
+       private $mWaitForPos, $mWaitTimeout;
+       private $mLaggedSlaveMode, $mLastError = 'Unknown error';
+       private $mParentInfo, $mLagTimes;
+       private $mLoadMonitorClass, $mLoadMonitor;
 
        /**
         * @param $params Array with keys:
@@ -27,8 +42,7 @@ class LoadBalancer {
         *    masterWaitTimeout Replication lag wait timeout
         *    loadMonitor       Name of a class used to fetch server lag and load.
         */
-       function __construct( $params )
-       {
+       function __construct( $params ) {
                if ( !isset( $params['servers'] ) ) {
                        throw new MWException( __CLASS__.': missing servers parameter' );
                }
@@ -50,9 +64,18 @@ class LoadBalancer {
                $this->mWaitForPos = false;
                $this->mLaggedSlaveMode = false;
                $this->mErrorConnection = false;
-               $this->mAllowLag = false;
-               $this->mLoadMonitorClass = isset( $params['loadMonitor'] ) 
-                       ? $params['loadMonitor'] : 'LoadMonitor_MySQL';
+               $this->mAllowLagged = false;
+
+               if ( isset( $params['loadMonitor'] ) ) {
+                       $this->mLoadMonitorClass = $params['loadMonitor'];
+               } else {
+                       $master = reset( $params['servers'] );
+                       if ( isset( $master['type'] ) && $master['type'] === 'mysql' ) {
+                               $this->mLoadMonitorClass = 'LoadMonitor_MySQL';
+                       } else {
+                               $this->mLoadMonitorClass = 'LoadMonitor_Null';
+                       }
+               }
 
                foreach( $params['servers'] as $i => $server ) {
                        $this->mLoads[$i] = $server['load'];
@@ -67,12 +90,10 @@ class LoadBalancer {
                }
        }
 
-       static function newFromParams( $servers, $waitTimeout = 10 ) {
-               return new LoadBalancer( $servers, $waitTimeout );
-       }
-
        /**
         * Get a LoadMonitor instance
+        *
+        * @return LoadMonitor
         */
        function getLoadMonitor() {
                if ( !isset( $this->mLoadMonitor ) ) {
@@ -84,6 +105,8 @@ class LoadBalancer {
 
        /**
         * Get or set arbitrary data used by the parent object, usually an LBFactory
+        * @param $x
+        * @return Mixed
         */
        function parentInfo( $x = null ) {
                return wfSetVar( $this->mParentInfo, $x );
@@ -92,9 +115,12 @@ class LoadBalancer {
        /**
         * Given an array of non-normalised probabilities, this function will select
         * an element and return the appropriate key
+        *
+        * @param $weights array
+        *
+        * @return int
         */
-       function pickRandom( $weights )
-       {
+       function pickRandom( $weights ) {
                if ( !is_array( $weights ) || count( $weights ) == 0 ) {
                        return false;
                }
@@ -108,7 +134,7 @@ class LoadBalancer {
                        return false;
                }
                $max = mt_getrandmax();
-               $rand = mt_rand(0, $max) / $max * $sum;
+               $rand = mt_rand( 0, $max ) / $max * $sum;
 
                $sum = 0;
                foreach ( $weights as $i => $w ) {
@@ -120,16 +146,21 @@ class LoadBalancer {
                return $i;
        }
 
+       /**
+        * @param $loads array
+        * @param $wiki bool
+        * @return bool|int|string
+        */
        function getRandomNonLagged( $loads, $wiki = false ) {
                # Unset excessively lagged servers
                $lags = $this->getLagTimes( $wiki );
                foreach ( $lags as $i => $lag ) {
-                       if ( $i != 0 && isset( $this->mServers[$i]['max lag'] ) ) {
+                       if ( $i != 0 ) {
                                if ( $lag === false ) {
-                                       wfDebug( "Server #$i is not replicating\n" );
+                                       wfDebugLog( 'replication', "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" );
+                               } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
+                                       wfDebugLog( 'replication', "Server #$i is excessively lagged ($lag seconds)\n" );
                                        unset( $loads[$i] );
                                }
                        }
@@ -164,11 +195,14 @@ class LoadBalancer {
         * always return a consistent index during a given invocation
         *
         * Side effect: opens connections to databases
+        * @param $group bool
+        * @param $wiki bool
+        * @return bool|int|string
         */
        function getReaderIndex( $group = false, $wiki = false ) {
                global $wgReadOnly, $wgDBClusterTimeout, $wgDBAvgStatusPoll, $wgDBtype;
 
-               # FIXME: For now, only go through all this for mysql databases
+               # @todo FIXME: For now, only go through all this for mysql databases
                if ($wgDBtype != 'mysql') {
                        return $this->getWriterIndex();
                }
@@ -224,7 +258,9 @@ class LoadBalancer {
                                        $i = $this->getRandomNonLagged( $currentLoads, $wiki );
                                        if ( $i === false && count( $currentLoads ) != 0 )  {
                                                # All slaves lagged. Switch to read-only mode
-                                               $wgReadOnly = wfMsgNoDBForContent( 'readonly_lag' );
+                                               wfDebugLog( 'replication', "All slaves lagged. Switch to read-only mode\n" );
+                                               $wgReadOnly = 'The database has been automatically locked ' .
+                                                       'while the slave database servers catch up to the master';
                                                $i = $this->pickRandom( $currentLoads );
                                                $laggedSlaveMode = true;
                                        }
@@ -232,7 +268,7 @@ class LoadBalancer {
 
                                if ( $i === false ) {
                                        # pickRandom() returned false
-                                       # This is permanent and means the configuration or the load monitor 
+                                       # This is permanent and means the configuration or the load monitor
                                        # wants us to return false.
                                        wfDebugLog( 'connect', __METHOD__.": pickRandom() returned false\n" );
                                        wfProfileOut( __METHOD__ );
@@ -250,7 +286,7 @@ class LoadBalancer {
                                }
 
                                // Perform post-connection backoff
-                               $threshold = isset( $this->mServers[$i]['max threads'] ) 
+                               $threshold = isset( $this->mServers[$i]['max threads'] )
                                        ? $this->mServers[$i]['max threads'] : false;
                                $backoff = $this->getLoadMonitor()->postConnectionBackoff( $conn, $threshold );
 
@@ -259,7 +295,7 @@ class LoadBalancer {
                                if ( $wiki !== false ) {
                                        $this->reuseConnection( $conn );
                                }
-                               
+
                                if ( $backoff ) {
                                        # Post-connection overload, don't use this server for now
                                        $totalThreadsConnected += $backoff;
@@ -315,6 +351,8 @@ class LoadBalancer {
 
        /**
         * Wait for a specified number of microseconds, and return the period waited
+        * @param $t int
+        * @return int
         */
        function sleep( $t ) {
                wfProfileIn( __METHOD__ );
@@ -324,18 +362,11 @@ class LoadBalancer {
                return $t;
        }
 
-       /**
-        * Get a random server to use in a query group
-        * @deprecated use getReaderIndex
-        */
-       function getGroupIndex( $group ) {
-               return $this->getReaderIndex( $group );
-       }
-
        /**
         * Set the master wait position
         * If a DB_SLAVE connection has been opened already, waits
         * Otherwise sets a variable telling it to wait if such a connection is opened
+        * @param $pos int
         */
        public function waitFor( $pos ) {
                wfProfileIn( __METHOD__ );
@@ -351,9 +382,25 @@ class LoadBalancer {
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * Set the master wait position and wait for ALL slaves to catch up to it
+        * @param $pos int
+        */
+       public function waitForAll( $pos ) {
+               wfProfileIn( __METHOD__ );
+               $this->mWaitForPos = $pos;
+               for ( $i = 1; $i < count( $this->mServers ); $i++ ) {
+                       $this->doWait( $i , true );
+               }
+               wfProfileOut( __METHOD__ );
+       }
+
        /**
         * Get any open connection to a given server index, local or foreign
         * Returns false if there is no connection open
+        *
+        * @param $i int
+        * @return DatabaseBase|bool False on failure
         */
        function getAnyOpenConnection( $i ) {
                foreach ( $this->mConns as $conns ) {
@@ -366,13 +413,24 @@ class LoadBalancer {
 
        /**
         * Wait for a given slave to catch up to the master pos stored in $this
+        * @param $index
+        * @param $open bool
+        * @return bool
         */
-       function doWait( $index ) {
+       function doWait( $index, $open = false ) {
                # Find a connection to wait on
                $conn = $this->getAnyOpenConnection( $index );
                if ( !$conn ) {
-                       wfDebug( __METHOD__ . ": no connection open\n" );
-                       return false;
+                       if ( !$open ) {
+                               wfDebug( __METHOD__ . ": no connection open\n" );
+                               return false;
+                       } else {
+                               $conn = $this->openConnection( $index );
+                               if ( !$conn ) {
+                                       wfDebug( __METHOD__ . ": failed to open connection\n" );
+                                       return false;
+                               }
+                       }
                }
 
                wfDebug( __METHOD__.": Waiting for slave #$index to catch up...\n" );
@@ -391,11 +449,11 @@ class LoadBalancer {
        /**
         * Get a connection by index
         * This is the main entry point for this class.
-        * 
+        *
         * @param $i Integer: server index
         * @param $groups Array: query groups
         * @param $wiki String: wiki ID
-        * 
+        *
         * @return DatabaseBase
         */
        public function &getConnection( $i, $groups = array(), $wiki = false ) {
@@ -440,6 +498,7 @@ class LoadBalancer {
                        if ( $i === false ) {
                                $this->mLastError = 'No working slave server: ' . $this->mLastError;
                                $this->reportConnectionError( $this->mErrorConnection );
+                               wfProfileOut( __METHOD__ );
                                return false;
                        }
                }
@@ -458,6 +517,8 @@ class LoadBalancer {
         * 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.
+        *
+        * @param DatabaseBase $conn
         */
        public function reuseConnection( $conn ) {
                $serverIndex = $conn->getLBInfo('serverIndex');
@@ -504,8 +565,8 @@ class LoadBalancer {
         * On error, returns false, and the connection which caused the
         * error will be available via $this->mErrorConnection.
         *
-        * @param $i Integer: server index
-        * @param $wiki String: wiki ID to open
+        * @param $i Integer server index
+        * @param $wiki String wiki ID to open
         * @return DatabaseBase
         *
         * @access private
@@ -613,6 +674,7 @@ class LoadBalancer {
         *
         * @param $index Integer: server index
         * @access private
+        * @return bool
         */
        function isOpen( $index ) {
                if( !is_integer( $index ) ) {
@@ -625,23 +687,34 @@ class LoadBalancer {
         * Really opens a connection. Uncached.
         * Returns a Database object whether or not the connection was successful.
         * @access private
+        *
+        * @param $server
+        * @param $dbNameOverride bool
+        * @return DatabaseBase
         */
        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.' );
+                       throw new MWException( 'You must update your load-balancing configuration. ' .
+                               'See DefaultSettings.php entry for $wgDBservers.' );
                }
 
-               extract( $server );
+               $host = $server['host'];
+               $dbname = $server['dbname'];
+
                if ( $dbNameOverride !== false ) {
-                       $dbname = $dbNameOverride;
+                       $server['dbname'] = $dbname = $dbNameOverride;
                }
 
-               # Get class for this database type
-               $class = 'Database' . ucfirst( $type );
-
                # Create object
                wfDebug( "Connecting to $host $dbname...\n" );
-               $db = new $class( $host, $user, $password, $dbname, $flags );
+               try {
+                       $db = DatabaseBase::factory( $server['type'], $server );
+               } catch ( DBConnectionError $e ) {
+                       // FIXME: This is probably the ugliest thing I have ever done to
+                       // PHP. I'm half-expecting it to segfault, just out of disgust. -- TS
+                       $db = $e->db;
+               }
+
                if ( $db->isOpen() ) {
                        wfDebug( "Connected to $host $dbname.\n" );
                } else {
@@ -657,12 +730,16 @@ class LoadBalancer {
                return $db;
        }
 
+       /**
+        * @param $conn
+        * @throws DBConnectionError
+        */
        function reportConnectionError( &$conn ) {
                wfProfileIn( __METHOD__ );
 
                if ( !is_object( $conn ) ) {
                        // No last connection, probably due to all servers being too busy
-                       wfLogDBError( "LB failure with no last connection\n" );
+                       wfLogDBError( "LB failure with no last connection. Connection error: {$this->mLastError}\n" );
                        $conn = new Database;
                        // If all servers were busy, mLastError will contain something sensible
                        throw new DBConnectionError( $conn, $this->mLastError );
@@ -674,12 +751,18 @@ class LoadBalancer {
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * @return int
+        */
        function getWriterIndex() {
                return 0;
        }
 
        /**
         * Returns true if the specified index is a valid server index
+        *
+        * @param $i
+        * @return bool
         */
        function haveIndex( $i ) {
                return array_key_exists( $i, $this->mServers );
@@ -687,6 +770,9 @@ class LoadBalancer {
 
        /**
         * Returns true if the specified index is valid and has non-zero load
+        *
+        * @param $i
+        * @return bool
         */
        function isNonZeroLoad( $i ) {
                return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
@@ -694,6 +780,8 @@ class LoadBalancer {
 
        /**
         * Get the number of defined servers (not the number of open connections)
+        *
+        * @return int
         */
        function getServerCount() {
                return count( $this->mServers );
@@ -702,6 +790,8 @@ class LoadBalancer {
        /**
         * Get the host name or IP address of the server with the specified index
         * Prefer a readable name if available.
+        * @param $i
+        * @return string
         */
        function getServerName( $i ) {
                if ( isset( $this->mServers[$i]['hostName'] ) ) {
@@ -715,6 +805,8 @@ class LoadBalancer {
 
        /**
         * Return the server info structure for a given index, or false if the index is invalid.
+        * @param $i
+        * @return bool
         */
        function getServerInfo( $i ) {
                if ( isset( $this->mServers[$i] ) ) {
@@ -724,6 +816,15 @@ class LoadBalancer {
                }
        }
 
+       /**
+        * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
+        * @param $i
+        * @param $serverInfo
+        */
+       function setServerInfo( $i, $serverInfo ) {
+               $this->mServers[$i] = $serverInfo;
+       }
+
        /**
         * Get the current master position for chronology control purposes
         * @return mixed
@@ -765,12 +866,24 @@ class LoadBalancer {
                );
        }
 
+       /**
+        * Deprecated function, typo in function name
+        *
+        * @deprecated in 1.18
+        * @param $conn
+        */
+       function closeConnecton( $conn ) {
+               wfDeprecated( __METHOD__, '1.18' );
+               $this->closeConnection( $conn );
+       }
+
        /**
         * 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.
+        * @param $conn DatabaseBase
         */
-       function closeConnecton( $conn ) {
+       function closeConnection( $conn ) {
                $done = false;
                foreach ( $this->mConns as $i1 => $conns2 ) {
                        foreach ( $conns2 as $i2 => $conns3 ) {
@@ -796,13 +909,15 @@ class LoadBalancer {
                foreach ( $this->mConns as $conns2 ) {
                        foreach ( $conns2 as $conns3 ) {
                                foreach ( $conns3 as $conn ) {
-                                       $conn->commit();
+                                       $conn->commit( __METHOD__ );
                                }
                        }
                }
        }
 
-       /* Issue COMMIT only on master, only if queries were done on connection */
+       /**
+        *  Issue COMMIT only on master, only if queries were done on connection
+        */
        function commitMasterChanges() {
                // Always 0, but who knows.. :)
                $masterIndex = $this->getWriterIndex();
@@ -812,27 +927,42 @@ class LoadBalancer {
                        }
                        foreach ( $conns2[$masterIndex] as $conn ) {
                                if ( $conn->doneWrites() ) {
-                                       $conn->commit();
+                                       $conn->commit( __METHOD__ );
                                }
                        }
                }
        }
 
+       /**
+        * @param $value null
+        * @return Mixed
+        */
        function waitTimeout( $value = null ) {
                return wfSetVar( $this->mWaitTimeout, $value );
        }
 
+       /**
+        * @return bool
+        */
        function getLaggedSlaveMode() {
                return $this->mLaggedSlaveMode;
        }
 
-       /* Disables/enables lag checks */
-       function allowLagged($mode=null) {
-               if ($mode===null)
+       /**
+        * Disables/enables lag checks
+        * @param $mode null
+        * @return bool
+        */
+       function allowLagged( $mode = null ) {
+               if ( $mode === null) {
                        return $this->mAllowLagged;
-               $this->mAllowLagged=$mode;
+               }
+               $this->mAllowLagged = $mode;
        }
 
+       /**
+        * @return bool
+        */
        function pingAll() {
                $success = true;
                foreach ( $this->mConns as $conns2 ) {
@@ -849,6 +979,8 @@ class LoadBalancer {
 
        /**
         * Call a function with each open connection object
+        * @param $callback
+        * @param array $params
         */
        function forEachOpenConnection( $callback, $params = array() ) {
                foreach ( $this->mConns as $conns2 ) {
@@ -864,46 +996,87 @@ 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.
-        * May attempt to open connections to slaves on the default DB.
+        * May attempt to open connections to slaves on the default DB. If there is
+        * no lag, the maximum lag will be reported as -1.
+        *
         * @param $wiki string Wiki ID, or false for the default database
+        *
+        * @return array ( host, max lag, index of max lagged host )
         */
        function getMaxLag( $wiki = false ) {
                $maxLag = -1;
                $host = '';
-               foreach ( $this->mServers as $i => $conn ) {
-                       $conn = false;
-                       if ( $wiki === false ) {
-                               $conn = $this->getAnyOpenConnection( $i );
-                       }
-                       if ( !$conn ) {
-                               $conn = $this->openConnection( $i, $wiki );
-                       }
-                       if ( !$conn ) {
-                               continue;
-                       }
-                       $lag = $conn->getLag();
-                       if ( $lag > $maxLag ) {
-                               $maxLag = $lag;
-                               $host = $this->mServers[$i]['host'];
+               $maxIndex = 0;
+               if ( $this->getServerCount() > 1 ) { // no replication = no lag
+                       foreach ( $this->mServers as $i => $conn ) {
+                               $conn = false;
+                               if ( $wiki === false ) {
+                                       $conn = $this->getAnyOpenConnection( $i );
+                               }
+                               if ( !$conn ) {
+                                       $conn = $this->openConnection( $i, $wiki );
+                               }
+                               if ( !$conn ) {
+                                       continue;
+                               }
+                               $lag = $conn->getLag();
+                               if ( $lag > $maxLag ) {
+                                       $maxLag = $lag;
+                                       $host = $this->mServers[$i]['host'];
+                                       $maxIndex = $i;
+                               }
                        }
                }
-               return array( $host, $maxLag );
+               return array( $host, $maxLag, $maxIndex );
        }
 
        /**
         * Get lag time for each server
         * Results are cached for a short time in memcached, and indefinitely in the process cache
+        *
+        * @param $wiki
+        *
+        * @return array
         */
        function getLagTimes( $wiki = false ) {
                # Try process cache
                if ( isset( $this->mLagTimes ) ) {
                        return $this->mLagTimes;
                }
-               # No, send the request to the load monitor
-               $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
+               if ( $this->getServerCount() == 1 ) {
+                       # No replication
+                       $this->mLagTimes = array( 0 => 0 );
+               } else {
+                       # Send the request to the load monitor
+                       $this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
+                               array_keys( $this->mServers ), $wiki );
+               }
                return $this->mLagTimes;
        }
 
+       /**
+        * Get the lag in seconds for a given connection, or zero if this load
+        * balancer does not have replication enabled.
+        *
+        * This should be used in preference to Database::getLag() in cases where
+        * replication may not be in use, since there is no way to determine if
+        * replication is in use at the connection level without running
+        * potentially restricted queries such as SHOW SLAVE STATUS. Using this
+        * function instead of Database::getLag() avoids a fatal error in this
+        * case on many installations.
+        *
+        * @param $conn DatabaseBase
+        *
+        * @return int
+        */
+       function safeGetLag( $conn ) {
+               if ( $this->getServerCount() == 1 ) {
+                       return 0;
+               } else {
+                       return $conn->getLag();
+               }
+       }
+
        /**
         * Clear the cache for getLagTimes
         */