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