Switch jquery.sortable to use mw-sortable and mw-unsortable classes, to be in line...
[lhc/web/wiklou.git] / includes / db / LoadBalancer.php
index d0a7343..069b8e1 100644 (file)
@@ -1,5 +1,7 @@
 <?php
 /**
+ * Database load balancing
+ *
  * @file
  * @ingroup Database
  */
  * @ingroup Database
  */
 class LoadBalancer {
-       /* private */ var $mServers, $mConns, $mLoads, $mGroupLoads;
-       /* private */ var $mFailFunction, $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 array $params Array with keys:
+        * @param $params Array with keys:
         *    servers           Required. Array of server info structures.
-        *    failFunction          Deprecated, use exceptions instead.
         *    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' );
                }
                $this->mServers = $params['servers'];
 
-               if ( isset( $params['failFunction'] ) ) {
-                       $this->mFailFunction = $params['failFunction'];
-               } else {
-                       $this->mFailFunction = false;
-               }
                if ( isset( $params['waitTimeout'] ) ) {
                        $this->mWaitTimeout = $params['waitTimeout'];
                } else {
@@ -54,9 +49,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'];
@@ -71,13 +75,10 @@ class LoadBalancer {
                }
        }
 
-       static function newFromParams( $servers, $failFunction = false, $waitTimeout = 10 )
-       {
-               return new LoadBalancer( $servers, $failFunction, $waitTimeout );
-       }
-
        /**
         * Get a LoadMonitor instance
+        *
+        * @return LoadMonitor
         */
        function getLoadMonitor() {
                if ( !isset( $this->mLoadMonitor ) ) {
@@ -97,9 +98,12 @@ class LoadBalancer {
        /**
         * Given an array of non-normalised probabilities, this function will select
         * an element and return the appropriate key
+        *
+        * @param $weights
+        *
+        * @return int
         */
-       function pickRandom( $weights )
-       {
+       function pickRandom( $weights ) {
                if ( !is_array( $weights ) || count( $weights ) == 0 ) {
                        return false;
                }
@@ -125,15 +129,20 @@ class LoadBalancer {
                return $i;
        }
 
+       /**
+        * @param $loads
+        * @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" );
                                        unset( $loads[$i] );
-                               } elseif ( $lag > $this->mServers[$i]['max lag'] ) {
+                               } elseif ( isset( $this->mServers[$i]['max lag'] ) && $lag > $this->mServers[$i]['max lag'] ) {
                                        wfDebug( "Server #$i is excessively lagged ($lag seconds)\n" );
                                        unset( $loads[$i] );
                                }
@@ -169,11 +178,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();
                }
@@ -214,8 +226,6 @@ class LoadBalancer {
                # Scale the configured load ratios according to the dynamic load (if the load monitor supports it)
                $this->getLoadMonitor()->scaleLoads( $nonErrorLoads, $group, $wiki );
 
-               $i = false;
-               $found = false;
                $laggedSlaveMode = false;
 
                # First try quickly looking through the available servers for a server that
@@ -231,7 +241,7 @@ 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' );
+                                               $wgReadOnly = wfMessage( 'readonly_lag' )->useDatabase( false )->plain();
                                                $i = $this->pickRandom( $currentLoads );
                                                $laggedSlaveMode = true;
                                        }
@@ -239,7 +249,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__ );
@@ -257,7 +267,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 );
 
@@ -266,7 +276,7 @@ class LoadBalancer {
                                if ( $wiki !== false ) {
                                        $this->reuseConnection( $conn );
                                }
-                               
+
                                if ( $backoff ) {
                                        # Post-connection overload, don't use this server for now
                                        $totalThreadsConnected += $backoff;
@@ -331,14 +341,6 @@ 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
@@ -358,12 +360,26 @@ class LoadBalancer {
                wfProfileOut( __METHOD__ );
        }
 
+       /**
+        * Set the master wait position and wait for ALL slaves to catch up to it
+        */
+       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
+        *
+        * @return DatabaseBase
         */
        function getAnyOpenConnection( $i ) {
-               foreach ( $this->mConns as $type => $conns ) {
+               foreach ( $this->mConns as $conns ) {
                        if ( !empty( $conns[$i] ) ) {
                                return reset( $conns[$i] );
                        }
@@ -374,12 +390,20 @@ class LoadBalancer {
        /**
         * Wait for a given slave to catch up to the master pos stored in $this
         */
-       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" );
@@ -398,14 +422,22 @@ class LoadBalancer {
        /**
         * Get a connection by index
         * This is the main entry point for this class.
-        * @param int $i Database
-        * @param array $groups Query groups
-        * @param string $wiki Wiki ID
+        *
+        * @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 ) {
-               global $wgDBtype;
                wfProfileIn( __METHOD__ );
 
+               if ( $i == DB_LAST ) {
+                       throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
+               } elseif ( $i === null || $i === false ) {
+                       throw new MWException( 'Attempt to call ' . __METHOD__ . ' with invalid server index' );
+               }
+
                if ( $wiki === wfWikiID() ) {
                        $wiki = false;
                }
@@ -435,12 +467,13 @@ class LoadBalancer {
                # Operation-based index
                if ( $i == DB_SLAVE ) {
                        $i = $this->getReaderIndex( false, $wiki );
-               } elseif ( $i == DB_LAST ) {
-                       throw new MWException( 'Attempt to call ' . __METHOD__ . ' with deprecated server index DB_LAST' );
-               }
-               # Couldn't find a working server in getReaderIndex()?
-               if ( $i === false ) {
-                       $this->reportConnectionError( $this->mErrorConnection );
+                       # Couldn't find a working server in getReaderIndex()?
+                       if ( $i === false ) {
+                               $this->mLastError = 'No working slave server: ' . $this->mLastError;
+                               $this->reportConnectionError( $this->mErrorConnection );
+                               wfProfileOut( __METHOD__ );
+                               return false;
+                       }
                }
 
                # Now we have an explicit index into the servers array
@@ -457,6 +490,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');
@@ -503,9 +538,9 @@ class LoadBalancer {
         * 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
+        * @param $i Integer server index
+        * @param $wiki String wiki ID to open
+        * @return DatabaseBase
         *
         * @access private
         */
@@ -548,9 +583,9 @@ class LoadBalancer {
         * 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
+        * @param $i Integer: server index
+        * @param $wiki String: wiki ID to open
+        * @return DatabaseBase
         */
        function openForeignConnection( $i, $wiki ) {
                wfProfileIn(__METHOD__);
@@ -571,9 +606,8 @@ class LoadBalancer {
                        $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";
+                                       $conn->getServer() . " from client host " . wfHostname() . "\n";
                                $this->mErrorConnection = $conn;
                                $conn = false;
                        } else {
@@ -593,6 +627,7 @@ class LoadBalancer {
                                $this->mErrorConnection = $conn;
                                $conn = false;
                        } else {
+                               $conn->tablePrefix( $prefix );
                                $this->mConns['foreignUsed'][$i][$wiki] = $conn;
                                wfDebug( __METHOD__.": opened new connection for $i/$wiki\n" );
                        }
@@ -609,7 +644,10 @@ class LoadBalancer {
 
        /**
         * Test if the specified index represents an open connection
+        *
+        * @param $index Integer: server index
         * @access private
+        * @return bool
         */
        function isOpen( $index ) {
                if( !is_integer( $index ) ) {
@@ -622,27 +660,29 @@ class LoadBalancer {
         * Really opens a connection. Uncached.
         * Returns a Database object whether or not the connection was successful.
         * @access private
+        *
+        * @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, 1, $flags );
+               $db = DatabaseBase::factory( $server['type'], $server );
                if ( $db->isOpen() ) {
-                       wfDebug( "Connected\n" );
+                       wfDebug( "Connected to $host $dbname.\n" );
                } else {
-                       wfDebug( "Failed\n" );
+                       wfDebug( "Connection failed to $host $dbname.\n" );
                }
                $db->setLBInfo( $server );
                if ( isset( $server['fakeSlaveLag'] ) ) {
@@ -656,33 +696,17 @@ class LoadBalancer {
 
        function reportConnectionError( &$conn ) {
                wfProfileIn( __METHOD__ );
-               # Prevent infinite recursion
-
-               static $reporting = false;
-               if ( !$reporting ) {
-                       $reporting = true;
-                       if ( !is_object( $conn ) ) {
-                               // No last connection, probably due to all servers being too busy
-                               wfLogDBError( "LB failure with no last connection\n" );
-                               $conn = new Database;
-                               if ( $this->mFailFunction ) {
-                                       $conn->failFunction( $this->mFailFunction );
-                                       $conn->reportConnectionError( $this->mLastError );
-                               } else {
-                                       // If all servers were busy, mLastError will contain something sensible
-                                       throw new DBConnectionError( $conn, $this->mLastError );
-                               }
-                       } else {
-                               if ( $this->mFailFunction ) {
-                                       $conn->failFunction( $this->mFailFunction );
-                               } else {
-                                       $conn->failFunction( false );
-                               }
-                               $server = $conn->getProperty( 'mServer' );
-                               wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
-                               $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
-                       }
-                       $reporting = false;
+
+               if ( !is_object( $conn ) ) {
+                       // No last connection, probably due to all servers being too busy
+                       wfLogDBError( "LB failure with no last connection\n" );
+                       $conn = new Database;
+                       // If all servers were busy, mLastError will contain something sensible
+                       throw new DBConnectionError( $conn, $this->mLastError );
+               } else {
+                       $server = $conn->getProperty( 'mServer' );
+                       wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
+                       $conn->reportConnectionError( "{$this->mLastError} ({$server})" );
                }
                wfProfileOut( __METHOD__ );
        }
@@ -693,6 +717,8 @@ class LoadBalancer {
 
        /**
         * Returns true if the specified index is a valid server index
+        *
+        * @return bool
         */
        function haveIndex( $i ) {
                return array_key_exists( $i, $this->mServers );
@@ -700,6 +726,8 @@ class LoadBalancer {
 
        /**
         * Returns true if the specified index is valid and has non-zero load
+        *
+        * @return bool
         */
        function isNonZeroLoad( $i ) {
                return array_key_exists( $i, $this->mServers ) && $this->mLoads[$i] != 0;
@@ -707,6 +735,8 @@ class LoadBalancer {
 
        /**
         * Get the number of defined servers (not the number of open connections)
+        *
+        * @return int
         */
        function getServerCount() {
                return count( $this->mServers );
@@ -737,6 +767,13 @@ class LoadBalancer {
                }
        }
 
+       /**
+        * Sets the server info structure for the given index. Entry at index $i is created if it doesn't exist
+        */
+       function setServerInfo( $i, $serverInfo ) {
+               $this->mServers[$i] = $serverInfo;
+       }
+
        /**
         * Get the current master position for chronology control purposes
         * @return mixed
@@ -778,12 +815,23 @@ class LoadBalancer {
                );
        }
 
+       /**
+        * Deprecated function, typo in function name
+        *
+        * @deprecated in 1.18
+        */
+       function closeConnecton( $conn ) {
+               $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
+        * @return void
         */
-       function closeConnecton( $conn ) {
+       function closeConnection( $conn ) {
                $done = false;
                foreach ( $this->mConns as $i1 => $conns2 ) {
                        foreach ( $conns2 as $i2 => $conns3 ) {
@@ -809,29 +857,31 @@ class LoadBalancer {
                foreach ( $this->mConns as $conns2 ) {
                        foreach ( $conns2 as $conns3 ) {
                                foreach ( $conns3 as $conn ) {
-                                       $conn->immediateCommit();
+                                       $conn->commit();
                                }
                        }
                }
        }
 
-       /* 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();
-               foreach ( $this->mConns as $type => $conns2 ) {
+               foreach ( $this->mConns as $conns2 ) {
                        if ( empty( $conns2[$masterIndex] ) ) {
                                continue;
                        }
                        foreach ( $conns2[$masterIndex] as $conn ) {
-                               if ( $conn->lastQuery() != '' ) {
+                               if ( $conn->doneWrites() ) {
                                        $conn->commit();
                                }
                        }
                }
        }
 
-       function waitTimeout( $value = NULL ) {
+       function waitTimeout( $value = null ) {
                return wfSetVar( $this->mWaitTimeout, $value );
        }
 
@@ -840,10 +890,11 @@ class LoadBalancer {
        }
 
        /* Disables/enables lag checks */
-       function allowLagged($mode=null) {
-               if ($mode===null)
+       function allowLagged( $mode = null ) {
+               if ( $mode === null) {
                        return $this->mAllowLagged;
-               $this->mAllowLagged=$mode;
+               }
+               $this->mAllowLagged = $mode;
        }
 
        function pingAll() {
@@ -878,14 +929,21 @@ 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.
+        * @param $wiki string Wiki ID, or false for the default database
+        *
+        * @return array ( host, max lag, index of max lagged host )
         */
-       function getMaxLag() {
+       function getMaxLag( $wiki = false ) {
                $maxLag = -1;
                $host = '';
+               $maxIndex = 0;
                foreach ( $this->mServers as $i => $conn ) {
-                       $conn = $this->getAnyOpenConnection( $i );
+                       $conn = false;
+                       if ( $wiki === false ) {
+                               $conn = $this->getAnyOpenConnection( $i );
+                       }
                        if ( !$conn ) {
-                               $conn = $this->openConnection( $i );
+                               $conn = $this->openConnection( $i, $wiki );
                        }
                        if ( !$conn ) {
                                continue;
@@ -894,14 +952,19 @@ class LoadBalancer {
                        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
@@ -912,4 +975,11 @@ class LoadBalancer {
                $this->mLagTimes = $this->getLoadMonitor()->getLagTimes( array_keys( $this->mServers ), $wiki );
                return $this->mLagTimes;
        }
+
+       /**
+        * Clear the cache for getLagTimes
+        */
+       function clearLagTimeCache() {
+               $this->mLagTimes = null;
+       }
 }