All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sun.grizzly.jruby.RailsAdapter Maven / Gradle / Ivy

/*
 * 
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
 * 
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 * 
 * Contributor(s):
 * 
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 *
 */
package com.sun.grizzly.jruby;

import com.sun.grizzly.http.SelectorThread;
import com.sun.grizzly.jruby.rack.RackAdapter;
import com.sun.grizzly.jruby.rack.RackApplication;
import com.sun.grizzly.jruby.rack.RackApplicationChooser;
import com.sun.grizzly.jruby.rack.RackApplicationFactory;
import com.sun.grizzly.tcp.http11.GrizzlyAdapter;
import com.sun.grizzly.tcp.http11.GrizzlyRequest;
import com.sun.grizzly.tcp.http11.GrizzlyResponse;
import org.jruby.Ruby;
import org.jruby.RubyThread;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;

/**
 * Adapter implementation that bridges JRuby on Rails with Grizzly.
 *
 * @author TAKAI Naoto
 * @author Jean-Francois Arcand
 * @author Pramod Gopinath
 * @author Vivek Pandey
 * @author Peter Williams
 */
public class RailsAdapter extends GrizzlyAdapter {

    private RackAdapter handler;
    private RubyRuntimeAsyncFilter asyncFilter;
    private final String contextRoot;
    private final String appRoot;
    private final int numThreads;
    private final int runtimes;
    private final int minRuntimes;
    private final int maxRuntimes;
    private final boolean asyncExecution;
    private RackApplicationFactory factory;
    private final boolean debugMode;

    public RailsAdapter(String railsRoot, String jrubyLib, int numRt, int minRt, int maxRt, boolean asyncExecution, RubyRuntimeAsyncFilter asyncFilter) {
        this("/", railsRoot, jrubyLib, numRt, minRt, maxRt, asyncExecution);
        this.asyncFilter = asyncFilter;
        //asyncFilter.setRubyRuntimeQueue(pool.getObjectQueue());
    }

    public RailsAdapter(String contextRoot, String appRoot, String jrubyLib, int numRt, int minRuntime, int maxRuntime, boolean asyncExecution) {
        super(appRoot);
        this.setHandleStaticResources(false);
        this.setRootFolder(appRoot + "public");
        this.contextRoot = contextRoot;
        this.appRoot = appRoot;
        //adapter = new RubyAdapter(appRoot, jrubyLib);
        this.runtimes = numRt;
        this.maxRuntimes = maxRuntime;
        this.minRuntimes = minRuntime;
        this.asyncExecution = asyncExecution;
        //JRuby 1.1.4 and below has a bug where multiple runtimes cannot start at the same time due to Servlea static HashSet.
        // It is fixed and will be available in 1.1.5. Until then, we will not attempt to start multiple runtimes at the same time
        JRubyVersion jrubyVersion = new JRubyVersion();
        if (jrubyVersion.compare("1.1.5") < 0)
            numThreads = 1;
        else
            numThreads = Math.min(Runtime.getRuntime().availableProcessors(), numRt);
        handler = RackApplicationChooser.getFactory(appRoot, SelectorThread.logger(), this);       
        factory = handler.getFactory();
        logger.log(Level.INFO, Messages.format(Messages.JRUBY_VERSION, jrubyVersion));
        this.debugMode = (jrubyVersion.compare("1.1.4") < 0);
    }

    public int getRuntimes() {
        return runtimes;
    }

    public int getMinRuntimes() {
        return minRuntimes;
    }

    public int getMaxRuntimes() {
        return maxRuntimes;
    }

    public boolean async() {
        return asyncExecution;
    }

    public int getNumThreads() {
        return numThreads;
    }

    public String getContextRoot(){
        return contextRoot;
    }

    /**
     * JRuby version, assumes the version to be of format major.minor.suffix
     */
    private static class JRubyVersion {

        private final int major, minor, suffix;

        public JRubyVersion() {
            this(org.jruby.runtime.Constants.VERSION);
        }

        private JRubyVersion(String version) {
            int i = version.lastIndexOf('.');
            if (i != -1) {
                suffix = Integer.parseInt(version.substring(i + 1, version.length()));
                int j = version.substring(0, i).lastIndexOf('.');
                if (j != -1) {
                    minor = Integer.parseInt(version.substring(j + 1, i));
                    if (j != 0)
                        major = Integer.parseInt(version.substring(0, j));
                    else
                        major = 0;

                } else {
                    minor = 0;
                    major = 1;
                }
            } else {
                major = minor = suffix = 0;
            }
        }

        /**
         * Returns > 1 if this.version is greater than the given version, <0 is less and 0 if equal.
         *
         * @param version version to be compared to
         * @return if this version is less than, greater, or equal to the provided version
         */
        public int compare(JRubyVersion version) {
            int result = major - version.major;
            if (result == 0) {
                result = minor - version.minor;
                if (result == 0) {
                    result = suffix - version.suffix;
                }
            }
            return result;
        }

        public int compare(String version) {
            return compare(new JRubyVersion(version));
        }

        @Override
        public String toString() {
            return major + "." + minor + "." + suffix;
        }
    }

    /**
     * JavaEmbedUtils.terminate(runtime);
     * Start the runtime pool, using the settings specified at creation
     */
//    void startRubyRuntimePool() {
//        try {
//            SelectorThread.logger().log(Level.INFO, Messages.format(Messages.RAILS_STARTING));
//            //pool.start(numThreads);
//
//        //adapter = new RackApplicationPoolAdapter();
//        GrizzlyContext context = new GrizzlyContext(this, factory.getRuntime(), factory);
//        factory.getRuntime().defineReadonlyVariable("$grizzly_context",
//                    JavaEmbedUtils.javaToRuby(factory.getRuntime(), context));
//        IRubyObject loggerObj = JavaEmbedUtils.javaToRuby(factory.getRuntime(), new Logger(getLogger()));
//            factory.getRuntime().defineReadonlyVariable("$logger", loggerObj);
//        String log_level = getEffectiveLogLevel();
//        IRubyObject GF_log_level = JavaEmbedUtils.javaToRuby(factory.getRuntime(), log_level);
//            factory.getRuntime().defineReadonlyVariable("$glassfish_log_level", GF_log_level);
//        handler.initialize();
//        } catch (RaiseException e) {
//            e.printStackTrace();
//            System.out.println(e.getMessage());
//            // try to put some helpful information in the logs
//            RubyException re = e.getException();
//            String rubyMessage = re.message.asJavaString();
//            String message = Messages.format(Messages.RAILS_LOAD_FAILED, rubyMessage) + "\n";
//            RubyArray backtrace = (RubyArray) re.backtrace();
//            for (Object aBacktrace : backtrace) {
//                String traceLine = (String) aBacktrace;
//                message += "\t" + traceLine + "\n";
//            }
//
//            getLogger().log(Level.SEVERE, message, e);
//            throw e;
//        }
//    }

    void stopRubyRuntimePool() {
        handler.shutdown();
    }

    public java.util.logging.Logger getLogger() {
        return logger;
    }

    /**
     * Logger to pass on to Rails Logger
     */
    private static class Logger {
        private final java.util.logging.Logger logger;

        public Logger(java.util.logging.Logger logger) {
            this.logger = logger;
        }

        // Log all messages at FINE level by default: Rails doesn't have log levels, and will generate at least 8 messages for every request that it serves, which floods everything
        public void log(String msg) {
            logger.fine(msg);
        }
        public void info(String msg) {
            logger.info(msg);
        }
        public void warning(String msg) {
            logger.warning(msg);
        }
        public void severe(String msg) {
            logger.severe(msg);
        }
        public void fine (String msg) {
            logger.fine(msg);
        }
    }

    // This method should be removed when glassfish/java.util.logger actually implements this
    private String getEffectiveLogLevel() {
        Level myLevel = null;
        java.util.logging.Logger pLog = logger;
        myLevel = pLog.getLevel();
        while (myLevel == null) {
            pLog = pLog.getParent();
            myLevel = pLog.getLevel();
        }
        return myLevel.getName();
    }

    public void service(GrizzlyRequest req, GrizzlyResponse res) {
        RackApplication serviceApp = null;
        try {
            // Borrow a Runtime
            serviceApp = handler.getApp();

            if (serviceApp == null) {
                throw new IllegalStateException(Messages.format(Messages.JRUBY_RUNTIME_NOTAVAILABLE));
            }
            // Leave all processing to the runtime
            if (debugMode) {
                //This is only so that NB 6.5 beta works with jruby < 1.1.3.
                //FIX ME: remove after                
                dispatchRailsRequestDebugMode(serviceApp, req, res);
            } else {
                dispatchRailsRequest(serviceApp, req, res);
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (serviceApp != null) {
                handler.returnApp(serviceApp);
                if (asyncFilter != null) {
                    asyncFilter.resume();

                }
            }
        }
    }

    private final Map> threadMaps =
            new HashMap>();

    private RubyThread getContextThread(Ruby runtime) {
        RubyThread contextThread = null;
        synchronized (threadMaps) {
            WeakHashMap threadMap = threadMaps.get(runtime);
            if (threadMap != null) {
                contextThread = threadMap.get(Thread.currentThread());
            } else {
                threadMap = new WeakHashMap();
                threadMaps.put(runtime, threadMap);
            }

            if (contextThread == null) {
                contextThread = RubyThread.adopt(runtime.getThread(), Thread.currentThread());
                threadMap.put(Thread.currentThread(), contextThread);
            }
        }
        return contextThread;
    }

    private void dispatchRailsRequestDebugMode(RackApplication app, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
        RubyThread oldContext = app.getRuntime().getThreadService().getMainThread();
        try {
            RubyThread context = getContextThread(app.getRuntime());
            app.getRuntime().getThreadService().setMainThread(context);
            dispatchRailsRequest(app, req, res);
        } finally {
            app.getRuntime().getThreadService().setMainThread(oldContext);
        }
    }


    private void dispatchRailsRequest(final RackApplication app, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
        try {
            app.call(req).respond(res);
        } catch (Exception e) {
            res.setError();
            e.printStackTrace();
            if (res.isCommitted()) {
                logger.log(Level.WARNING, "Error: Couldn't handle error: response committed", e);
                return;
            }
            res.reset();

            try {
                RackApplication errorApp = factory.getErrorApplication(app.getRuntime());
                req.setAttribute("rack.exception", e);
                logger.log(Level.WARNING, e.getMessage(), e);
                errorApp.call(req).respond(res);
            } catch (Exception ex) {
                logger.log(Level.WARNING, "Error: Couldn't handle error", ex);
                res.sendError(500);
            }
        }
    }

    String getAppRoot(){
        return appRoot;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy