1 module sdnotify;
2 
3 import ssll;
4 
5 import std.exception : enforce;
6 import std.string : toStringz, format;
7 
8 private enum libNames = [
9     "libsystemd.so",
10     "libsystemd.so.0"
11 ];
12 
13 private __gshared void* lib;
14 
15 alias pid_t = size_t;
16 
17 ///
18 void initSystemDLib()
19 {
20     if (lib !is null) return;
21     foreach (name; libNames)
22     {
23         lib = loadLibrary(name);
24         if (lib !is null) break;
25     }
26     enforce(lib, "can't load systemd lib");
27     loadApiSymbols();
28 }
29 
30 ///
31 void cleanupSystemDLib() { unloadLibrary(lib); }
32 
33 mixin apiSymbols;
34 
35 @api("lib") @nogc
36 {
37     int sd_notify(int unset_environment, const char* state) { mixin(rtLib); }
38     int sd_pid_notify(pid_t pid, int unset_environment, const char *state) { mixin(rtLib); }
39 
40     extern (C) // because variablic arguments
41     {
42         pragma(mangle, "sdutil_dlib_sd_journal_print") // because extern(C)
43         int sd_journal_print(int priority, const char* fmt, ...) { mixin(rtLib); }
44 
45         pragma(mangle, "sdutil_dlib_sd_journal_send")
46         int sd_journal_send(const char* fmt, ...) { mixin(rtLib); }
47     }
48 
49     int sd_journal_perror(const char *message) { mixin(rtLib); }
50 }
51 
52 ///
53 int sdNotify(int unset_environment, string state)
54 { return sd_notify(unset_environment, state.toStringz); }
55 
56 /// shortcut 
57 int sdNotify_ready(int unset_environment=0) @nogc
58 { return sd_notify(unset_environment, "READY=1"); }
59 
60 /// ditto
61 int sdNotify_reloading(int unset_environment=0) @nogc
62 { return sd_notify(unset_environment, "RELOADING=1"); }
63 
64 /// ditto
65 int sdNotify_stopping(int unset_environment=0) @nogc
66 { return sd_notify(unset_environment, "STOPPING=1"); }
67 
68 /// ditto
69 int sdNotify_watchdog(int unset_environment=0) @nogc
70 { return sd_notify(unset_environment, "WATCHDOG=1"); }
71 
72 ///
73 int sdPidNotify(pid_t pid, int unset_environment, string state)
74 { return sd_pid_notify(pid, unset_environment, state.toStringz); }
75 
76 ///
77 int sdNotifyf(Args...)(int unset_environment, string fmt, Args args)
78 { return sd_notify(unset_environment, format(fmt, args)); }
79 
80 ///
81 int sdPidNotifyf(Args...)(pid_t pid, int unset_environment, string fmt, Args args)
82 { return sd_pid_notify(pid, unset_environment, format(fmt, args)); }