com.sun.grizzly.jruby.RackGrizzlyAdapter 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.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 com.sun.grizzly.util.buf.ByteChunk;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicLong;
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 RackGrizzlyAdapter extends GrizzlyAdapter {
private RackAdapter handler;
private int numThreads;
private final boolean asyncExecution;
private RackApplicationFactory factory;
private JRubyVersion jrubyVersion;
public final JRubyGrizzlyConfigImpl config;
private final AtomicLong counter = new AtomicLong();
private long startTime;
public RackGrizzlyAdapter(JRubyGrizzlyConfigImpl config, boolean asyncExecution) {
super(config.appRoot());
this.config = config;
this.setHandleStaticResources(false);
this.setRootFolder(config.appRoot() + File.separator+"public");
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 = new JRubyVersion();
logger.log(Level.INFO, Messages.format(Messages.JRUBY_VERSION, jrubyVersion));
if (jrubyVersion.compare("1.1.5") < 0)
numThreads = 1;
else
numThreads = Math.min(Runtime.getRuntime().availableProcessors(), config.runtimeConfig().getInitRuntime());
}
public boolean async() {
return asyncExecution;
}
public int getNumThreads() {
return numThreads;
}
/**
* 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;
}
}
private FutureTask jrubyStartUp;
private void startThread(){
ExecutorService exec = Executors.newFixedThreadPool(1);
jrubyStartUp = new FutureTask(new Callable(){
public Boolean call() throws Exception {
return startJRubyRuntime();
}
});
exec.execute(jrubyStartUp);
}
@Override
public void start() {
startThread();
logger.fine("Sending JRubyProbeProvider() start event for application: "+config.getAppName());
config.jRubyProbeProvider.jrubyModuleStartedEvent(config.getAppName(), config.framework().type(), config.environment(), jrubyVersion.toString());
}
private boolean startJRubyRuntime(){
handler = RackApplicationChooser.getFactory(config.appRoot(), this);
factory = handler.getFactory();
return true;
}
@Override
public void destroy() {
handler.shutdown();
logger.fine("Sending JRubyProbeProvider() Stop event for application: "+config.getAppName());
config.jRubyProbeProvider.jrubyModuleStoppedEvent(config.getAppName(), config.framework().type(), config.environment());
}
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();
}
private final static String CSS =
"H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} " +
"H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} " +
"H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} " +
"BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} " +
"B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} " +
"P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}" +
"A {color : black;}" +
"HR {color : #525D76;}";
private byte[] getHtmlPage() {
StringBuffer sb = new StringBuffer();
sb.append("");
sb.append(" ");
sb.append("");
sb.append("");
sb.append("");
sb.append("Server is busy loading the application... ");
sb.append("
");
sb.append("
");
sb.append("Powered by GlassFish v3");
sb.append("");
return sb.toString().getBytes();
}
public void service(GrizzlyRequest req, GrizzlyResponse res) {
counter.getAndIncrement();
config.jrubyHttpProbeProvider.requestStartEvent(config.contextRoot(), req.getServerName(), req.getServerPort());
if(!jrubyStartUp.isDone()){
res.setStatus(503); //
byte[] bytes = getHtmlPage();
ByteChunk chunk = new ByteChunk();
chunk.setBytes(bytes, 0, bytes.length);
res.setContentLength(bytes.length);
res.setContentType("text/html");
//jruby is still being loaded, wait for 3 sec
String delta = System.getProperty("jruby.http.retry-after");
if(delta == null){
delta = "3";
}
res.setHeader("Retry-After", delta);
try {
res.getResponse().sendHeaders();
res.getResponse().doWrite(chunk);
} catch (IOException e) {
logger.log(Level.SEVERE, e.getMessage(), e);
}
return;
}
RackApplication serviceApp = null;
try {
// Borrow a Runtime
serviceApp = handler.getApp();
if (serviceApp == null) {
throw new IllegalStateException(Messages.format(Messages.JRUBY_RUNTIME_NOTAVAILABLE));
}
dispatchRequest(serviceApp, req, res);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serviceApp != null) {
handler.returnApp(serviceApp);
}
config.jrubyHttpProbeProvider.requestEndEvent(config.contextRoot(), res.getStatus());
}
}
private void dispatchRequest(final RackApplication app, GrizzlyRequest req, GrizzlyResponse res) throws IOException {
try {
app.call(req).respond(res);
} catch (Exception e) {
res.setError();
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);
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy