Search code examples
javaservicejenkinsjettyembedded-jetty

How can you shut down an embedded jetty instance?


I have an embedded jetty project that builds a single .jar file that starts up our webapp.

public static void main(String[] args){            
            final Server server = new Server(threadPool);
            //Do config/setup code for servlets/database/contexts/connectors/etc
            server.start();
            server.dumpStdErr();
            server.join();
}

So while this works great to start our server by calling java -jar MyApp.jar I am at a loss for a way to stop it. This is especially annoying when I want to stop the server via our build server.

When we used the Jetty service and deployed a .war file we could do this:

  1. Build latest .war file via Jenkins
  2. Stop Jetty service via shell (sudo service jetty stop)
  3. Overwrite old .war file in /opt/jetty/webapp with new .war file
  4. Start Jetty service via shell (sudo service jetty start)

I currently have two ideas:

  1. Create a servlet that calls server.stop() if you have a secret get parameter specified. Use curl on the shell in Jekins to hit this servlet.
  2. Use something like Apache-Commons daemon wrapper to make my app into a service.

Is there some obvious mechanism I am missing to stop the server?


Solution

  • Use the ShutdownHandler

    The server side:

    Server server = new Server(8080);
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[]
    { someOtherHandler, new ShutdownHandler("secret password", false, true) });
    server.setHandler(handlers);
    server.start();
    

    The client side (to issue shutdown).

    public static void attemptShutdown(int port, String shutdownCookie) {
        try {
            URL url = new URL("http://localhost:" + port + "/shutdown?token=" + shutdownCookie);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.getResponseCode();
            logger.info("Shutting down " + url + ": " + connection.getResponseMessage());
        } catch (SocketException e) {
            logger.debug("Not running");
            // Okay - the server is not running
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }