#include <errno.h>
#include <stdlib.h>
+#include <string.h>
+
+#include <systemd/sd-daemon.h>
+#include <systemd/sd-event.h>
#include "ctx.h"
#include "daemon.h"
struct collecty_daemon {
collecty_ctx* ctx;
int nrefs;
+
+ // Event Loop
+ sd_event* loop;
};
-static void collecty_daemon_free(collecty_daemon* daemon) {
- if (daemon->ctx)
- collecty_ctx_unref(daemon->ctx);
+static int collecty_daemon_setup_loop(collecty_daemon* self) {
+ int r;
+
+ // Create a new loop
+ r = sd_event_new(&self->loop);
+ if (r < 0)
+ return r;
+
+ return 0;
+}
+
+static void collecty_daemon_free(collecty_daemon* self) {
+ if (self->ctx)
+ collecty_ctx_unref(self->ctx);
+ if (self->loop)
+ sd_event_unref(self->loop);
}
int collecty_daemon_create(collecty_daemon** daemon, collecty_ctx* ctx) {
collecty_daemon* self = NULL;
+ int r;
// Allocate some memory
self = calloc(1, sizeof(*self));
// Store a reference to the context
self->ctx = collecty_ctx_ref(ctx);
+ // Setup the event loop
+ r = collecty_daemon_setup_loop(self);
+ if (r < 0)
+ goto ERROR;
+
// Return the pointer
*daemon = self;
-
return 0;
+
+ERROR:
+ if (self)
+ collecty_daemon_unref(self);
+
+ return r;
}
collecty_daemon* collecty_daemon_ref(collecty_daemon* daemon) {
collecty_daemon_free(daemon);
return NULL;
}
+
+int collecty_daemon_run(collecty_daemon* self) {
+ int r;
+
+ // We are now ready
+ sd_notify(0, "READY=1\n" "STATUS=Ready...");
+
+ // Launch the event loop
+ r = sd_event_loop(self->loop);
+ if (r < 0) {
+ ERROR(self->ctx, "Could not run the event loop: %s\n", strerror(-r));
+ goto ERROR;
+ }
+
+ // Let systemd know that we are shutting down
+ sd_notify(0, "STOPPING=1\n" "STATUS=Shutting down...");
+
+ return 0;
+
+ERROR:
+ sd_notifyf(0, "ERRNO=%i", -r);
+
+ return 1;
+}