Thursday, February 23, 2017

Restarting a Server From a Web Service


Often times you may want a simple web service call to restart your server. There is a problem however if the web service is running in the application to be restarted. You can't simply call a restart script from your application, at least in Java, since Java needs to die to complete the call, and this would kill the restart process along with it. To overcome this limitation you can wrap the restart script in a nohup and background it.

Create nohup-restart.sh, containing the following:

nohup ./bin/restart.sh $1 > restart.out 2> restart.err &

Then create restart.sh, containing:

sleep 3
kill $1
app.sh

The sleep is to give the web service time to respond before it shuts down.

You can pass the pid from Java into the script. The pid is accessed by

ManagementFactory.getRuntimeMXBean().getName()

But strip out the @machine part).

Now call Runtime.exec with fully qualified path to script. Depending on how it was started you might be able to get away with a path relative to user.dir.

process = Runtime.getRuntime().exec(new String[] {scriptPath, "nohup-restart.sh", ManagementFactory.getRuntimeMXBean().getName().split("@")[0]});

If the script is daemon it's much simpler since it can be called without the nohup nonsense, however it should be called in a Thread to give it time to respond.

No comments:

Post a Comment