Skip to content

Instantly share code, notes, and snippets.

@septatrix
Created August 14, 2024 22:29
Show Gist options
  • Save septatrix/dcb1d7763c941be399da5dc97397e6c3 to your computer and use it in GitHub Desktop.
Save septatrix/dcb1d7763c941be399da5dc97397e6c3 to your computer and use it in GitHub Desktop.
sd_notify in Java using junixsocket
/*
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE
FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
// Test using the following command:
// systemd-run --user --pty --same-dir --wait --collect --service-type=notify -p NotifyAccess=all java -cp junixsocket.jar SdNotify.jav
// Should state: "Finished with result: success"
// In case of failure due to wrong sd_notify usage, it will state: "Finished with result: protocol"
import java.io.IOException;
import java.nio.ByteBuffer;
import org.newsclub.net.unix.AFUNIXDatagramSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;
public class SdNotify {
public static void main(String[] args) {
ready();
}
public static void ready() {
notify("READY=1");
}
public static void status(String status) {
notify("STATUS=" + status);
}
/// ...implement other well-known sd_notify(3) messages as needed...
private static void notify(String arg) {
var socketPath = System.getenv("NOTIFY_SOCKET");
if (socketPath == null)
return;
if (!(socketPath.startsWith("/") || socketPath.startsWith("@"))) {
throw new UnsupportedOperationException("Unsupported socket type");
}
if (socketPath.startsWith("@")) {
socketPath = "\0" + socketPath.substring(1);
}
try (var socket = AFUNIXDatagramSocket.newInstance()) {
socket.connect(AFUNIXSocketAddress.of(socketPath.getBytes()));
try (var out = socket.getChannel()) {
out.write(ByteBuffer.wrap(arg.getBytes()));
}
} catch (IOException e) {
System.err.printf("Failed to notify systemd of service readiness: %s", e.toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment