Skip to content

Instantly share code, notes, and snippets.

@nicobrevin
Created July 2, 2010 22:24
Show Gist options
  • Save nicobrevin/461992 to your computer and use it in GitHub Desktop.
Save nicobrevin/461992 to your computer and use it in GitHub Desktop.
public class JRubyDaemon implements Daemon {
private Ruby runtime;
private Thread thread;
private RubyModule appModule;
private boolean debug;
private RubyModule daemon;
public void init(DaemonContext arguments) throws Exception {
debug = "true".equals(System.getProperty("JRubyDaemon.debug"));
// mimicking startup from org.jruby.Main
RubyInstanceConfig rubyConfig = new RubyInstanceConfig();
rubyConfig.processArguments(arguments.getArguments());
runtime = Ruby.newInstance(rubyConfig);
Thread.currentThread().setContextClassLoader(runtime.getJRubyClassLoader());
if (debug) log("Initialising JRuby program from: " + rubyConfig.getScriptFileName());
// boot her up. The script should yield control back to us (--daemon flag) so we
// can give it back once in start once we are happy that everything is going to
// work. FYI, it also lets us bind to ports < 1024
runtime.runFromMain(rubyConfig.getScriptSource(), rubyConfig.getScriptFileName());
// check it has come up OK
appModule = runtime.getModule("AppModule");
if (appModule == null) { throw new RuntimeException("Couldn't get AppModule module from JRuby runtime"); }
daemon = (RubyModule) appModule.getConstantAt("Daemon");
if (daemon == null) { throw new RuntimeException("Couldn't get AppModule::Daemon module from JRuby runtime"); }
Boolean wasSetup =
(Boolean) JavaEmbedUtils.rubyToJava(runtime, daemon.callMethod("setup?"), Boolean.class);
if (!wasSetup) {
throw new RuntimeException("Script did not call AppModule::Daemon.setup");
}
private void log(String msg) {
System.err.println("JRubyDaemon: " + msg);
}
public void start() throws Exception {
thread = new Thread("Main") {
@Override
public void run() {
if (debug) log("thread " + thread + " starting daemon...");
daemon.callMethod("start");
}
};
thread.setDaemon(false);
thread.setContextClassLoader(runtime.getJRubyClassLoader());
thread.start();
}
public void stop() throws Exception {
// TODO Auto-generated method stub
if (debug) log("Stopping...");
try {
daemon.callMethod("stop");
} catch (MainExitException e) {}
if (debug) log("Stopped");
}
public void destroy() {
runtime.tearDown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment