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.pool.DynamicPool;
import com.sun.grizzly.pool.DynamicPoolConfig;
import com.sun.grizzly.tcp.Request;
import com.sun.grizzly.tcp.Response;
import com.sun.grizzly.tcp.http11.GrizzlyAdapter;
import com.sun.grizzly.tcp.http11.GrizzlyRequest;
import com.sun.grizzly.tcp.http11.GrizzlyResponse;
import com.sun.grizzly.util.buf.ByteChunk;
import com.sun.grizzly.util.http.MimeType;
import org.jruby.*;
import org.jruby.exceptions.RaiseException;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.builtin.IRubyObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
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 final DynamicPool pool;
private RubyRuntimeAsyncFilter asyncFilter;
private final String contextRoot;
private final Map environment = new HashMap();
private File webDir = null;
private final ReentrantLock initializedLock = new ReentrantLock();
private final int numThreads;
private ConcurrentHashMap cache = new ConcurrentHashMap();
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 railsRoot, String jrubyLib, int numRt, int minRuntime, int maxRuntime, boolean asyncExecution) {
super(railsRoot);
this.setHandleStaticResources(true);
this.setRootFolder(railsRoot + "/public");
this.contextRoot = contextRoot;
RubyAdapter myAdapter = new RubyAdapter(railsRoot, jrubyLib);
DynamicPoolConfig myConfig = new DynamicPoolConfig(numRt, -1, maxRuntime, minRuntime, -1, -1, -1, -1, asyncExecution, false);
// Using defaults for, in order, maximum generating, upThreshold, downThreshold, queueThreshold, newThreshold
this.pool = new DynamicPool(myAdapter, myConfig);
JRubyVersion jrubyVersion = new JRubyVersion();
logger.log(Level.INFO, Messages.format(Messages.JRUBY_VERSION, jrubyVersion));
this.debugMode = (jrubyVersion.compare("1.1.4") < 0);
//JRuby 1.1.4 and below has a bug where multiple runtimes cannot start at the same time due to a 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
if (jrubyVersion.compare("1.1.5") < 0)
numThreads = 1;
else
numThreads = Math.min(Runtime.getRuntime().availableProcessors(), numRt);
}
/**
* JRuby version, assumes the version to be of format major.minor.suffix
*/
private static class JRubyVersion {
private int major, minor, suffix;
private String qualifier="";
public JRubyVersion() {
this(org.jruby.runtime.Constants.VERSION);
}
private JRubyVersion(String version) {
int i = version.lastIndexOf('.');
if (i != -1) {
String v = version.substring(i + 1, version.length());
try{
suffix = Integer.parseInt(v);
}catch(NumberFormatException e){
int index=0;
//Probably there was ASCII text, such as RC1 or so as suffix
for(char c: v.toCharArray()){
if(!Character.isDigit(c)){
break;
}
index++;
}
suffix = Integer.parseInt(v.substring(0, index));
if(index > 0)
qualifier = v.substring(index, v.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+qualifier;
}
}
/**
* 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);
} 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() {
pool.stop();
}
/**
* The given Ruby runtime might not be configured with the correct context root for this adapter. Check if the
* $root is set correctly else set it now.
*
* @param runtime the runtime to check the context root for
*/
private void loadRuntimeEnvironment(Ruby runtime) {
if (contextRoot != null && !contextRoot.equals("/")) {
String root = runtime.getGlobalVariables().get("$root").asString().asJavaString();
if (root == null || !root.equals(contextRoot)) {
runtime.defineReadonlyVariable("$root",
JavaEmbedUtils.javaToRuby(runtime, contextRoot));
}
}
String logger = runtime.getGlobalVariables().get("$logger").asString().asJavaString();
if (logger == null || logger.length() == 0) {
IRubyObject loggerObj = JavaEmbedUtils.javaToRuby(runtime, new Logger(getLogger()));
runtime.defineReadonlyVariable("$logger", loggerObj);
}
//Looks like Rails ENV hash keeps state of previous request.
//we reset it a fresh with the initial value or else every request is going to be the same.
RubyHash env = (RubyHash) runtime.getObject().getConstant("ENV");
if (environment.size() == 0) {
environment.putAll(env);
} else {
env.clear();
env.putAll(environment);
}
}
/**
* 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: 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.info(msg);
}
}
public void service(GrizzlyRequest req, GrizzlyResponse res) {
// Commit the response so Grizzly doesn't add its own headers.
// try {
// ((InternalOutputBuffer) res.getResponse().getOutputBuffer()).commit();
// } catch (IOException e) {
// res.getResponse().setCommitted(true);
// logger.log(Level.WARNING, Messages.format(Messages.GRIZZLY_COMMIT_ERR, res.getResponse().isCommitted()));
// }
Ruby runtime = null;
try {
// Borrow a Runtime
runtime = pool.borrowObject();
if (runtime == 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(runtime, req, res);
} else {
dispatchRailsRequest(runtime, req, res);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (runtime != null) {
pool.returnObject(runtime);
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(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
RubyThread oldContext = runtime.getThreadService().getMainThread();
try {
RubyThread context = getContextThread(runtime);
runtime.getThreadService().setMainThread(context);
dispatchRailsRequest(runtime, req, res);
} finally {
runtime.getThreadService().setMainThread(oldContext);
}
}
private void dispatchRailsRequest(Ruby runtime, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
try {
OutputStream os = new RailsOutputStream(res);
//OutputStream os = res.getOutputStream();
RubyIO iObj = new RubyIO(runtime, req.getInputStream());
runtime.defineReadonlyVariable("$stdin", iObj);
RubyIO oObj = new RubyIO(runtime, os);
runtime.defineReadonlyVariable("$stdout", oObj);
loadRuntimeEnvironment(runtime);
IRubyObject[] args = {JavaEmbedUtils.javaToRuby(runtime, req), JavaEmbedUtils.javaToRuby(runtime, res)};
IRubyObject responder = runtime.getGlobalVariables().get("$responder");
JavaEmbedUtils.invokeMethod(runtime, responder, "service", args, IRubyObject.class);
} catch (RaiseException e) {
getLogger().log(Level.SEVERE, e.getLocalizedMessage(), e);
RubyException exception = e.getException();
exception.printBacktrace(System.err);
throw e;
}
}
// Moved some of the internal code out into separate methods to make it clearer - Jacob
@Override
protected void service(String uri, Request req, Response res) throws Exception {
if (contextRoot != null && uri.startsWith(contextRoot)) {
uri = uri.substring(contextRoot.length());
}
FileInputStream fis = null;
try {
// set the web directory, if needed
webDir = findWebDir();
// local file
File resource = getStaticResource(uri);
if (!resource.exists()) {
if (getLogger().isLoggable(Level.FINE)) {
getLogger().log(Level.FINE, Messages.format(Messages.STATIC_FILE_NOTFOUND, resource));
}
res.setStatus(404);
customizedErrorPage(req, res);
return;
}
res.setStatus(200);
int dot = uri.lastIndexOf(".");
if (dot > 0) {
String ext = uri.substring(dot + 1);
String ct = MimeType.get(ext);
if (ct != null) {
res.setContentType(ct);
}
} else {
res.setContentType(MimeType.get("html"));
}
res.setContentLength((int) resource.length());
res.sendHeaders();
/* Workaround Linux NIO bug
* 6427312: (fc) FileChannel.transferTo() throws IOException "system call interrupted"
* 5103988: (fc) FileChannel.transferTo should return -1 for EAGAIN instead throws IOException
* 6253145: (fc) FileChannel.transferTo on Linux fails when going beyond 2GB boundary
* 6470086: (fc) FileChannel.transferTo(2147483647, 1, channel) cause "Value too large" exception
*/
// Write the found resource to the output stream
fis = new FileInputStream(resource);
byte b[] = new byte[8192];
ByteChunk chunk = new ByteChunk();
int rd;
while ((rd = fis.read(b)) > 0) {
chunk.setBytes(b, 0, rd);
res.doWrite(chunk);
}
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Error closeing static file stream! " + ex);
}
}
}
res.setCommitted(true);
}
// Attempts to find requested static resources. Does not guarantee the existance of the File it returns
private File getStaticResource(String uri) {
File resource = cache.get(uri);
if (resource == null) {
resource = new File(webDir, uri);
cache.put(uri, resource);
}
if (resource.isDirectory()) {
resource = new File(resource, "index.html");
cache.put(uri, resource);
}
return resource;
}
// Attempts to find the web directory if it has not yet been set
private File findWebDir() {
if (webDir == null) {
initializedLock.lock();
try {
webDir = new File(getRootFolder());
try {
setRootFolder(webDir.getCanonicalPath());
} catch (IOException e) {
logger.log(Level.WARNING, "service()", e);
}
} finally {
initializedLock.unlock();
}
}
return webDir;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy