Skip to content

Instantly share code, notes, and snippets.

@lburgazzoli
Created November 11, 2015 14:23
Show Gist options
  • Save lburgazzoli/318a6b07671bbc8d0b2d to your computer and use it in GitHub Desktop.
Save lburgazzoli/318a6b07671bbc8d0b2d to your computer and use it in GitHub Desktop.
Systemd Watchdog
import jnr.constants.platform.Signal;
import jnr.ffi.LibraryLoader;
import jnr.posix.POSIX;
import jnr.posix.POSIXFactory;
import jnr.posix.SignalHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SystemdWatchdog {
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
private static final POSIX POSIX = POSIXFactory.getPOSIX();
public static void main(String[] args) {
try {
final Watchdog wd = new Watchdog();
final SignalHandler handler = signal ->LOGGER.info("Got signal : " + signal);
POSIX.signal(Signal.SIGHUP , handler);
POSIX.signal(Signal.SIGUSR1, handler);
POSIX.signal(Signal.SIGUSR2, handler);
wd.start();
for(int i=0; i<100; i++) {
LOGGER.info("Sleep ...");
Thread.sleep(1000);
}
wd.stop();
} catch (Exception e) {
}
}
public static class Watchdog {
private final ScheduledExecutorService scheduler;
public Watchdog() {
this.scheduler = Executors.newScheduledThreadPool(1);
}
public void start() throws Exception {
String timeouts = System.getenv("WATCHDOG_USEC");
Systemd systemd = LibraryLoader.create(Systemd.class).load("systemd-daemon");
if(timeouts != null) {
scheduler.scheduleAtFixedRate(
() -> LOGGER.info("Notify {}", systemd.sd_notify(0, "WATCHDOG=1")),
0,
Long.parseLong(timeouts) / 2,
TimeUnit.MICROSECONDS
);
}
}
public void stop() throws Exception {
this.scheduler.shutdown();
this.scheduler.awaitTermination(5, TimeUnit.SECONDS);
}
}
public interface Systemd {
int sd_notify(int unsetEnvironment, String state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment