Hostinfo day 2: Implement the daemon.
[virt-hostinfo.git] / hostinfod / monitor_sockets.c
diff --git a/hostinfod/monitor_sockets.c b/hostinfod/monitor_sockets.c
new file mode 100644 (file)
index 0000000..547a535
--- /dev/null
@@ -0,0 +1,87 @@
+/* virt-hostinfo
+ * Copyright (C) 2009 Red Hat Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <sys/inotify.h>
+#include <sys/stat.h>
+
+#include <apr_general.h>
+
+#include "hostinfod.h"
+
+int sockets_inotify_fd = -1;
+
+void
+monitor_socket_dir (void)
+{
+  struct stat statbuf;
+
+  if (!socket_dir) {
+    error ("no socket directory was configured - see hostinfo(8)");
+    exit (1);
+  }
+
+  if (stat (socket_dir, &statbuf) == -1) {
+    perrorf ("%s (socket directory): does not exist or is not accessible",
+            socket_dir);
+    exit (1);
+  }
+  if (!S_ISDIR (statbuf.st_mode)) {
+    error ("%s (socket directory): not a directory", socket_dir);
+    exit (1);
+  }
+
+#ifdef HAVE_INOTIFY_INIT1
+  sockets_inotify_fd = inotify_init1 (IN_NONBLOCK | IN_CLOEXEC);
+  if (sockets_inotify_fd == -1) {
+    perrorf ("inotify_init");
+    exit (1);
+  }
+#else
+  sockets_inotify_fd = inotify_init ();
+  if (sockets_inotify_fd == -1) {
+    perrorf ("inotify_init");
+    exit (1);
+  }
+  if (fcntl (sockets_inotify_fd, F_SETFL, O_NONBLOCK) == -1) {
+    perrorf ("fcntl: O_NONBLOCK");
+    exit (1);
+  }
+  if (fcntl (sockets_inotify_fd, F_SETFD, FD_CLOEXEC) == -1) {
+    perrorf ("fcntl: FD_CLOEXEC");
+    exit (1);
+  }
+#endif
+
+  if (inotify_add_watch (sockets_inotify_fd, socket_dir,
+                        IN_CREATE|IN_DELETE|IN_MOVE) == -1) {
+    perrorf ("inotify_add_watch: %s", socket_dir);
+    exit (1);
+  }
+
+  debug ("inotify of %s successful, fd = %d",
+        socket_dir, sockets_inotify_fd);
+}