-
-
Save hanikesn/568882f96d543758e7b2 to your computer and use it in GitHub Desktop.
The poor Java programmer's alternative to calling sd_notify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package systemd; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.nio.file.Files; | |
import java.nio.file.LinkOption; | |
import java.nio.file.Paths; | |
import java.util.function.Supplier; | |
@lombok.extern.slf4j.Slf4j | |
public class SdDaemon { | |
public static void status(String status) { | |
notify("--status=" + status); | |
} | |
public static void ready() { | |
notify("--ready"); | |
} | |
public static boolean booted() { | |
return Files.isDirectory(Paths.get("/run/systemd/system"), LinkOption.NOFOLLOW_LINKS); | |
} | |
private static void notify(String arg) { | |
if (!booted() || System.getenv("NOTIFY_SOCKET") == null) | |
return; | |
try { | |
Process p = new ProcessBuilder("systemd-notify", arg) | |
.redirectErrorStream(true) | |
.start(); | |
if (ignoreInterruptedException(p::waitFor) == 0) | |
return; | |
log.error("Failed to notify systemd of/that {}; systemd-notify exited with status {}", arg, p.exitValue()); | |
try (BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()))) { | |
r.lines().forEach(l -> log.error("systemd-notify: {}", l)); | |
} | |
} catch (Exception e) { | |
log.warn("Failed to notify systemd of service readiness", e); | |
} | |
} | |
private interface ThrowingSupplier<T, E extends Throwable> { | |
T get() throws E; | |
} | |
private static <T> T ignoreInterruptedException(ThrowingSupplier<T, InterruptedException> r) { | |
Supplier<Object> s; | |
for (;;) { | |
try { | |
return r.get(); | |
} catch (InterruptedException e) { | |
continue; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment