Hostinfo day 4: Implement command processing code.
[virt-hostinfo.git] / hostinfod / monitor_sockets.c
1 /* virt-hostinfo
2  * Copyright (C) 2009 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <sys/inotify.h>
29 #include <sys/stat.h>
30
31 #include <apr_general.h>
32
33 #include "hostinfod.h"
34
35 int sockets_inotify_fd = -1;
36
37 void
38 monitor_socket_dir (void)
39 {
40   struct stat statbuf;
41
42   if (!socket_dir) {
43     error ("no socket directory was configured - see hostinfo(8)");
44     exit (1);
45   }
46
47   if (stat (socket_dir, &statbuf) == -1) {
48     perrorf ("%s (socket directory): does not exist or is not accessible",
49              socket_dir);
50     exit (1);
51   }
52   if (!S_ISDIR (statbuf.st_mode)) {
53     error ("%s (socket directory): not a directory", socket_dir);
54     exit (1);
55   }
56
57 #ifdef HAVE_INOTIFY_INIT1
58   sockets_inotify_fd = inotify_init1 (IN_NONBLOCK | IN_CLOEXEC);
59   if (sockets_inotify_fd == -1) {
60     perrorf ("inotify_init");
61     exit (1);
62   }
63 #else
64   sockets_inotify_fd = inotify_init ();
65   if (sockets_inotify_fd == -1) {
66     perrorf ("inotify_init");
67     exit (1);
68   }
69   if (fcntl (sockets_inotify_fd, F_SETFL, O_NONBLOCK) == -1) {
70     perrorf ("fcntl: O_NONBLOCK");
71     exit (1);
72   }
73   if (fcntl (sockets_inotify_fd, F_SETFD, FD_CLOEXEC) == -1) {
74     perrorf ("fcntl: FD_CLOEXEC");
75     exit (1);
76   }
77 #endif
78
79   if (inotify_add_watch (sockets_inotify_fd, socket_dir,
80                          IN_CREATE|IN_DELETE|IN_MOVE) == -1) {
81     perrorf ("inotify_add_watch: %s", socket_dir);
82     exit (1);
83   }
84
85   debug ("inotify of %s successful, fd = %d",
86          socket_dir, sockets_inotify_fd);
87 }