Moved the signal handler initialization so it gets run in the child, not the parent..
[collectd.git] / src / collectd.c
1 /**
2  * collectd - src/collectd.c
3  * Copyright (C) 2005  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at verplant.org>
21  *   Alvaro Barcellos <alvaro.barcellos at gmail.com>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "utils_debug.h"
27
28 #include "multicast.h"
29 #include "plugin.h"
30 #include "configfile.h"
31
32 #include "ping.h"
33
34 static int loop = 0;
35
36 #if HAVE_LIBKSTAT
37 kstat_ctl_t *kc;
38 #endif /* HAVE_LIBKSTAT */
39
40 #if COLLECT_PING
41 char *pinghosts[MAX_PINGHOSTS];
42 int   num_pinghosts = 0;
43 #endif
44
45 /*
46  * exported variables
47  */
48 time_t curtime;
49
50 #if HAVE_LIBRRD
51 int operating_mode;
52 #endif
53
54 static void sigIntHandler (int signal)
55 {
56         loop++;
57 }
58
59 static void sigTermHandler (int signal)
60 {
61         loop++;
62 }
63
64 static int change_basedir (char *dir)
65 {
66         int dirlen = strlen (dir);
67         
68         while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
69                 dir[--dirlen] = '\0';
70
71         if (dirlen <= 0)
72                 return (-1);
73
74         if (chdir (dir) == -1)
75         {
76                 if (errno == ENOENT)
77                 {
78                         if (mkdir (dir, 0755) == -1)
79                         {
80                                 syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
81                                 return (-1);
82                         }
83                         else if (chdir (dir) == -1)
84                         {
85                                 syslog (LOG_ERR, "chdir (%s): %s", dir, strerror (errno));
86                                 return (-1);
87                         }
88                 }
89                 else
90                 {
91                         syslog (LOG_ERR, "chdir: %s", strerror (errno));
92                         return (-1);
93                 }
94         }
95
96         return (0);
97 } /* static int change_basedir (char *dir) */
98
99 #if HAVE_LIBKSTAT
100 static void update_kstat (void)
101 {
102         if (kc == NULL)
103         {
104                 if ((kc = kstat_open ()) == NULL)
105                         syslog (LOG_ERR, "Unable to open kstat control structure");
106         }
107         else
108         {
109                 kid_t kid;
110                 kid = kstat_chain_update (kc);
111                 if (kid > 0)
112                 {
113                         syslog (LOG_INFO, "kstat chain has been updated");
114                         plugin_init_all ();
115                 }
116                 else if (kid < 0)
117                         syslog (LOG_ERR, "kstat chain update failed");
118                 /* else: everything works as expected */
119         }
120
121         return;
122 } /* static void update_kstat (void) */
123 #endif /* HAVE_LIBKSTAT */
124
125 static void exit_usage (char *name)
126 {
127         printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
128                         
129                         "Available options:\n"
130                         "  General:\n"
131                         "    -C <file>       Configuration file.\n"
132                         "                    Default: "CONFIGFILE"\n"
133 #if COLLECT_DAEMON
134                         "    -P <file>       PID file.\n"
135                         "                    Default: "PIDFILE"\n"
136 #endif
137                         "    -M <dir>        Module/Plugin directory.\n"
138                         "                    Default: "PLUGINDIR"\n"
139                         "    -D <dir>        Data storage directory.\n"
140                         "                    Default: "PKGLOCALSTATEDIR"\n"
141 #if COLLECT_DEBUG
142                         "    -L <file>       Log file.\n"
143                         "                    Default: "LOGFILE"\n"
144 #endif
145 #if COLLECT_DAEMON
146                         "    -f              Don't fork to the background.\n"
147 #endif
148 #if HAVE_LIBRRD
149                         "    -l              Start in local mode (no network).\n"
150                         "    -c              Start in client (sender) mode.\n"
151                         "    -s              Start in server (listener) mode.\n"
152 #endif /* HAVE_LIBRRD */
153 #if COLLECT_PING
154                         "  Ping:\n"
155                         "    -p <host>       Host to ping periodically, may be repeated to ping\n"
156                         "                    more than one host.\n"
157 #endif /* COLLECT_PING */
158                         "\n"PACKAGE" "VERSION", http://verplant.org/collectd/\n"
159                         "by Florian octo Forster <octo@verplant.org>\n"
160                         "for contributions see `AUTHORS'\n");
161         exit (0);
162 } /* static void exit_usage (char *name) */
163
164 static int start_client (void)
165 {
166         int sleepingtime;
167
168 #if HAVE_LIBKSTAT
169         kc = NULL;
170         update_kstat ();
171 #endif
172
173 #if HAVE_LIBSTATGRAB
174         if (sg_init ())
175         {
176                 syslog (LOG_ERR, "sg_init: %s", sg_str_error (sg_get_error ()));
177                 return (-1);
178         }
179
180         if (sg_drop_privileges ())
181         {
182                 syslog (LOG_ERR, "sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
183                 return (-1);
184         }
185 #endif
186
187         plugin_init_all ();
188
189         while (loop == 0)
190         {
191                 curtime = time (NULL);
192 #if HAVE_LIBKSTAT
193                 update_kstat ();
194 #endif
195                 plugin_read_all ();
196
197                 sleepingtime = 10;
198                 while (sleepingtime != 0)
199                 {
200                         if (loop != 0)
201                                 break;
202                         sleepingtime = sleep (sleepingtime);
203                 }
204         }
205
206         return (0);
207 } /* static int start_client (void) */
208
209 #if HAVE_LIBRRD
210 static int start_server (void)
211 {
212         char *host;
213         char *type;
214         char *instance;
215         char *values;
216
217         while (loop == 0)
218         {
219                 if (multicast_receive (&host, &type, &instance, &values) == 0)
220                         plugin_write (host, type, instance, values);
221
222                 if (host     != NULL) free (host);     host     = NULL;
223                 if (type     != NULL) free (type);     type     = NULL;
224                 if (instance != NULL) free (instance); instance = NULL;
225                 if (values   != NULL) free (values);   values   = NULL;
226         }
227         
228         return (0);
229 } /* static int start_server (void) */
230 #endif /* HAVE_LIBRRD */
231
232 #if COLLECT_DAEMON
233 static int pidfile_create (const char *file)
234 {
235         FILE *fh;
236
237         if (file == NULL)
238                 file = PIDFILE;
239
240         if ((fh = fopen (file, "w")) == NULL)
241         {
242                 syslog (LOG_ERR, "fopen (%s): %s", file, strerror (errno));
243                 return (1);
244         }
245
246         fprintf (fh, "%d\n", getpid());
247         fclose(fh);
248
249         return (0);
250 } /* static int pidfile_create (const char *file) */
251 #endif /* COLLECT_DAEMON */
252
253 #if COLLECT_DAEMON
254 static int pidfile_remove (const char *file)
255 {
256         if (file == NULL) {
257                 file = PIDFILE;
258         }
259         return (unlink (file));
260 } /* static int pidfile_remove (const char *file) */
261 #endif /* COLLECT_DAEMON */
262
263 int main (int argc, char **argv)
264 {
265 #if COLLECT_DAEMON
266         struct sigaction sigChldAction;
267 #endif
268         struct sigaction sigIntAction;
269         struct sigaction sigTermAction;
270         char *configfile = CONFIGFILE;
271         char *plugindir  = PLUGINDIR;
272         char *datadir    = PKGLOCALSTATEDIR;
273 #if COLLECT_DAEMON
274         char *pidfile    = PIDFILE;
275         pid_t pid;
276         int daemonize    = 1;
277 #endif
278 #if COLLECT_DEBUG
279         char *logfile    = LOGFILE;
280 #endif
281
282 #if HAVE_LIBRRD
283         operating_mode = MODE_LOCAL;
284 #endif
285
286         /* open syslog */
287         openlog (PACKAGE, LOG_CONS | LOG_PID, LOG_DAEMON);
288
289         /* read options */
290         while (1)
291         {
292                 int c;
293
294                 c = getopt (argc, argv, "C:M:D:h"
295 #if COLLECT_DAEMON
296                                 "fP:"
297 #endif
298 #if COLLECT_DEBUG
299                                 "L:"
300 #endif
301 #if HAVE_LIBRRD
302                                 "csl"
303 #endif /* HAVE_LIBRRD */
304 #if COLLECT_PING
305                                 "p:"
306 #endif /* COLLECT_PING */
307                 );
308
309                 if (c == -1)
310                         break;
311
312                 switch (c)
313                 {
314 #if HAVE_LIBRRD
315                         case 'c':
316                                 operating_mode = MODE_CLIENT;
317                                 break;
318
319                         case 's':
320                                 operating_mode = MODE_SERVER;
321                                 break;
322
323                         case 'l':
324                                 operating_mode = MODE_LOCAL;
325                                 break;
326 #endif /* HAVE_LIBRRD */
327                         case 'C':
328                                 configfile = optarg;
329                                 break;
330 #if COLLECT_DAEMON
331                         case 'P':
332                                 pidfile = optarg;
333                                 break;
334                         case 'f':
335                                 daemonize = 0;
336                                 break;
337 #endif /* COLLECT_DAEMON */
338                         case 'M':
339                                 plugindir = optarg;
340                                 break;
341                         case 'D':
342                                 datadir = optarg;
343                                 break;
344 #if COLLECT_DEBUG
345                         case 'L':
346                                 logfile = optarg;
347                                 break;
348 #endif
349 #if COLLECT_PING
350                         case 'p':
351                                 if (num_pinghosts < MAX_PINGHOSTS)
352                                         pinghosts[num_pinghosts++] = optarg;
353                                 else
354                                         fprintf (stderr, "Maximum of %i ping hosts reached.\n", MAX_PINGHOSTS);
355                                 break;
356 #endif /* COLLECT_PING */
357                         case 'h':
358                         default:
359                                 exit_usage (argv[0]);
360                 } /* switch (c) */
361         } /* while (1) */
362
363         DBG_STARTFILE(logfile, "debug file opened.");
364
365         /*
366          * Read the config file. This will load any modules automagically.
367          */
368         plugin_set_dir (plugindir);
369
370         if (cf_read (configfile))
371         {
372                 fprintf (stderr, "Error: Reading the config file failed!\n"
373                                 "Read the syslog for details.\n");
374                 return (1);
375         }
376
377         /*
378          * Change directory. We do this _after_ reading the config and loading
379          * modules to relative paths work as expected.
380          */
381         if (change_basedir (datadir))
382         {
383                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", datadir);
384                 return (1);
385         }
386
387         /*
388          * fork off child
389          */
390 #if COLLECT_DAEMON
391         sigChldAction.sa_handler = SIG_IGN;
392         sigaction (SIGCHLD, &sigChldAction, NULL);
393
394         if (daemonize)
395         {
396                 if ((pid = fork ()) == -1)
397                 {
398                         /* error */
399                         fprintf (stderr, "fork: %s", strerror (errno));
400                         return (1);
401                 }
402                 else if (pid != 0)
403                 {
404                         /* parent */
405                         /* printf ("Running (PID %i)\n", pid); */
406                         return (0);
407                 }
408
409                 /* Detach from session */
410                 setsid ();
411
412                 /* Write pidfile */
413                 if (pidfile_create (pidfile))
414                         exit (2);
415
416                 /* close standard descriptors */
417                 close (2);
418                 close (1);
419                 close (0);
420
421                 if (open ("/dev/null", O_RDWR) != 0)
422                 {
423                         syslog (LOG_ERR, "Error: Could not connect `STDIN' to `/dev/null'");
424                         return (1);
425                 }
426                 if (dup (0) != 1)
427                 {
428                         syslog (LOG_ERR, "Error: Could not connect `STDOUT' to `/dev/null'");
429                         return (1);
430                 }
431                 if (dup (0) != 2)
432                 {
433                         syslog (LOG_ERR, "Error: Could not connect `STDERR' to `/dev/null'");
434                         return (1);
435                 }
436         } /* if (daemonize) */
437 #endif /* COLLECT_DAEMON */
438
439         /*
440          * install signal handlers
441          */
442         sigIntAction.sa_handler = sigIntHandler;
443         sigaction (SIGINT, &sigIntAction, NULL);
444
445         sigIntAction.sa_handler = sigTermHandler;
446         sigaction (SIGTERM, &sigTermAction, NULL);
447
448         /*
449          * run the actual loops
450          */
451 #if HAVE_LIBRRD
452         if (operating_mode == MODE_SERVER)
453                 start_server ();
454         else /* if (operating_mode == MODE_CLIENT || operating_mode == MODE_LOCAL) */
455 #endif
456                 start_client ();
457
458         DBG_STOPFILE("debug file closed.");
459
460         /* close syslog */
461         syslog (LOG_INFO, "Exiting normally");
462         closelog ();
463
464 #if COLLECT_DAEMON
465         if (daemonize)
466                 pidfile_remove(pidfile);
467 #endif /* COLLECT_DAEMON */
468
469         return (0);
470 } /* int main (int argc, char **argv) */