11

I have a Java service (implemented using Dropwizard) which I'm launching from a user instance of systemd. So far so good. Now I would like to use systemd's notification features to make it aware of the service state (available as a C library function or shell script but eventually both methods talk to a socket referenced by an environment variable). I can run arbitrary code when the service has finished starting up, but I'm not sure how best to notify systemd from within Java.

Other developers run this service on Windows, so for bonus points it would be really useful if my notification code were discreet and didn't cause any output if not running with systemd.

Andrew Aylett
  • 39,182
  • 5
  • 68
  • 95

2 Answers2

3

I found this implementation which does use system hooks, but at least doesn't require JNA/JNI.

https://gist.github.com/yrro/18dc22513f1001d0ec8d

As you say, systemd uses sockets referenced by an environment variable (System.getenv("NOTIFY_SOCKET") in the code), so I'd imagine there may also be a way to use a Java Socket, although I'd imagine a lot of research and/or trial-and-error would be required.

Andrew Aylett
  • 39,182
  • 5
  • 68
  • 95
Jonathan
  • 176
  • 2
  • 6
  • Good call -- I've yet to find a better solution. I've removed your link, as it's actually referencing a SO clone's copy of this question. – Andrew Aylett Feb 22 '16 at 16:09
  • 2
    This class uses something, forking a child `systemd-notify` process, that is notoriously unreliable. [There is a better way.](http://stackoverflow.com/a/36992645/340790) – JdeBP May 02 '16 at 22:32
  • 4
    I've taken the answer from @JdeBP and turned it into something a little more generic: https://gist.github.com/juur/048cc3d0554953b717e9c6867970f30e – Ian Nov 06 '18 at 18:16
0

There is Java + JNI implementation:

https://github.com/faljse/SDNotify

The Notify protocol uses datagram unix sockets, which are not accessible via Java; Therefore SDNotify includes a JNA wrapper of the socket API.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303