Various plugins: Use the IS_TRUE and IS_FALSE macros everywhere.
[collectd.git] / src / collectd.c
1 /**
2  * collectd - src/collectd.c
3  * Copyright (C) 2005-2007  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
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
29
30 #include <pthread.h>
31
32 #include "plugin.h"
33 #include "configfile.h"
34
35 #if HAVE_STATGRAB_H
36 # include <statgrab.h>
37 #endif
38
39 /*
40  * Global variables
41  */
42 char hostname_g[DATA_MAX_NAME_LEN];
43 int  interval_g;
44 #if HAVE_LIBKSTAT
45 kstat_ctl_t *kc;
46 #endif /* HAVE_LIBKSTAT */
47
48 static int loop = 0;
49
50 static void *do_flush (void __attribute__((unused)) *arg)
51 {
52         INFO ("Flushing all data.");
53         plugin_flush (NULL, -1, NULL);
54         INFO ("Finished flushing all data.");
55         pthread_exit (NULL);
56         return NULL;
57 }
58
59 static void sig_int_handler (int __attribute__((unused)) signal)
60 {
61         loop++;
62 }
63
64 static void sig_term_handler (int __attribute__((unused)) signal)
65 {
66         loop++;
67 }
68
69 static void sig_usr1_handler (int __attribute__((unused)) signal)
70 {
71         pthread_t      thread;
72         pthread_attr_t attr;
73
74         /* flushing the data might take a while,
75          * so it should be done asynchronously */
76         pthread_attr_init (&attr);
77         pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
78         pthread_create (&thread, &attr, do_flush, NULL);
79 }
80
81 static int init_hostname (void)
82 {
83         const char *str;
84
85         struct addrinfo  ai_hints;
86         struct addrinfo *ai_list;
87         struct addrinfo *ai_ptr;
88         int status;
89
90         str = global_option_get ("Hostname");
91         if (str != NULL)
92         {
93                 sstrncpy (hostname_g, str, sizeof (hostname_g));
94                 return (0);
95         }
96
97         if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
98         {
99                 fprintf (stderr, "`gethostname' failed and no "
100                                 "hostname was configured.\n");
101                 return (-1);
102         }
103
104         str = global_option_get ("FQDNLookup");
105         if (IS_FALSE (str))
106                 return (0);
107
108         memset (&ai_hints, '\0', sizeof (ai_hints));
109         ai_hints.ai_flags = AI_CANONNAME;
110
111         status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
112         if (status != 0)
113         {
114                 ERROR ("Looking up \"%s\" failed. You have set the "
115                                 "\"FQDNLookup\" option, but I cannot resolve "
116                                 "my hostname to a fully qualified domain "
117                                 "name. Please fix you network "
118                                 "configuration.", hostname_g);
119                 return (-1);
120         }
121
122         for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
123         {
124                 if (ai_ptr->ai_canonname == NULL)
125                         continue;
126
127                 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
128                 break;
129         }
130
131         freeaddrinfo (ai_list);
132         return (0);
133 } /* int init_hostname */
134
135 static int init_global_variables (void)
136 {
137         const char *str;
138
139         str = global_option_get ("Interval");
140         if (str == NULL)
141                 str = "10";
142         interval_g = atoi (str);
143         if (interval_g <= 0)
144         {
145                 fprintf (stderr, "Cannot set the interval to a correct value.\n"
146                                 "Please check your settings.\n");
147                 return (-1);
148         }
149         DEBUG ("interval_g = %i;", interval_g);
150
151         if (init_hostname () != 0)
152                 return (-1);
153         DEBUG ("hostname_g = %s;", hostname_g);
154
155         return (0);
156 } /* int init_global_variables */
157
158 static int change_basedir (const char *orig_dir)
159 {
160         char *dir = strdup (orig_dir);
161         int dirlen;
162         int status;
163
164         if (dir == NULL)
165         {
166                 char errbuf[1024];
167                 ERROR ("strdup failed: %s",
168                                 sstrerror (errno, errbuf, sizeof (errbuf)));
169                 return (-1);
170         }
171         
172         dirlen = strlen (dir);
173         while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
174                 dir[--dirlen] = '\0';
175
176         if (dirlen <= 0)
177                 return (-1);
178
179         status = chdir (dir);
180         free (dir);
181
182         if (status != 0)
183         {
184                 if (errno == ENOENT)
185                 {
186                         if (mkdir (orig_dir, 0755) == -1)
187                         {
188                                 char errbuf[1024];
189                                 ERROR ("change_basedir: mkdir (%s): %s", orig_dir,
190                                                 sstrerror (errno, errbuf,
191                                                         sizeof (errbuf)));
192                                 return (-1);
193                         }
194                         else if (chdir (orig_dir) == -1)
195                         {
196                                 char errbuf[1024];
197                                 ERROR ("chdir (%s): %s", orig_dir,
198                                                 sstrerror (errno, errbuf,
199                                                         sizeof (errbuf)));
200                                 return (-1);
201                         }
202                 }
203                 else
204                 {
205                         char errbuf[1024];
206                         ERROR ("chdir (%s): %s", orig_dir,
207                                         sstrerror (errno, errbuf,
208                                                 sizeof (errbuf)));
209                         return (-1);
210                 }
211         }
212
213         return (0);
214 } /* static int change_basedir (char *dir) */
215
216 #if HAVE_LIBKSTAT
217 static void update_kstat (void)
218 {
219         if (kc == NULL)
220         {
221                 if ((kc = kstat_open ()) == NULL)
222                         ERROR ("Unable to open kstat control structure");
223         }
224         else
225         {
226                 kid_t kid;
227                 kid = kstat_chain_update (kc);
228                 if (kid > 0)
229                 {
230                         INFO ("kstat chain has been updated");
231                         plugin_init_all ();
232                 }
233                 else if (kid < 0)
234                         ERROR ("kstat chain update failed");
235                 /* else: everything works as expected */
236         }
237
238         return;
239 } /* static void update_kstat (void) */
240 #endif /* HAVE_LIBKSTAT */
241
242 /* TODO
243  * Remove all settings but `-f' and `-C'
244  */
245 static void exit_usage (int status)
246 {
247         printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
248                         
249                         "Available options:\n"
250                         "  General:\n"
251                         "    -C <file>       Configuration file.\n"
252                         "                    Default: "CONFIGFILE"\n"
253                         "    -t              Test config and exit.\n"
254                         "    -T              Test plugin read and exit.\n"
255                         "    -P <file>       PID-file.\n"
256                         "                    Default: "PIDFILE"\n"
257 #if COLLECT_DAEMON
258                         "    -f              Don't fork to the background.\n"
259 #endif
260                         "    -h              Display help (this message)\n"
261                         "\nBuiltin defaults:\n"
262                         "  Config-File       "CONFIGFILE"\n"
263                         "  PID-File          "PIDFILE"\n"
264                         "  Data-Directory    "PKGLOCALSTATEDIR"\n"
265                         "\n"PACKAGE" "VERSION", http://collectd.org/\n"
266                         "by Florian octo Forster <octo@verplant.org>\n"
267                         "for contributions see `AUTHORS'\n");
268         exit (status);
269 } /* static void exit_usage (int status) */
270
271 static int do_init (void)
272 {
273 #if HAVE_LIBKSTAT
274         kc = NULL;
275         update_kstat ();
276 #endif
277
278 #if HAVE_LIBSTATGRAB
279         if (sg_init ())
280         {
281                 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
282                 return (-1);
283         }
284
285         if (sg_drop_privileges ())
286         {
287                 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
288                 return (-1);
289         }
290 #endif
291
292         plugin_init_all ();
293
294         return (0);
295 } /* int do_init () */
296
297
298 static int do_loop (void)
299 {
300         struct timeval tv_now;
301         struct timeval tv_next;
302         struct timeval tv_wait;
303         struct timespec ts_wait;
304
305         while (loop == 0)
306         {
307                 if (gettimeofday (&tv_next, NULL) < 0)
308                 {
309                         char errbuf[1024];
310                         ERROR ("gettimeofday failed: %s",
311                                         sstrerror (errno, errbuf,
312                                                 sizeof (errbuf)));
313                         return (-1);
314                 }
315                 tv_next.tv_sec += interval_g;
316
317 #if HAVE_LIBKSTAT
318                 update_kstat ();
319 #endif
320
321                 /* Issue all plugins */
322                 plugin_read_all ();
323
324                 if (gettimeofday (&tv_now, NULL) < 0)
325                 {
326                         char errbuf[1024];
327                         ERROR ("gettimeofday failed: %s",
328                                         sstrerror (errno, errbuf,
329                                                 sizeof (errbuf)));
330                         return (-1);
331                 }
332
333                 if (timeval_cmp (tv_next, tv_now, &tv_wait) <= 0)
334                 {
335                         WARNING ("Not sleeping because the next interval is "
336                                         "%i.%06i seconds in the past!",
337                                         (int) tv_wait.tv_sec, (int) tv_wait.tv_usec);
338                         continue;
339                 }
340
341                 ts_wait.tv_sec  = tv_wait.tv_sec;
342                 ts_wait.tv_nsec = (long) (1000 * tv_wait.tv_usec);
343
344                 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) == -1))
345                 {
346                         if (errno != EINTR)
347                         {
348                                 char errbuf[1024];
349                                 ERROR ("nanosleep failed: %s",
350                                                 sstrerror (errno, errbuf,
351                                                         sizeof (errbuf)));
352                                 return (-1);
353                         }
354                 }
355         } /* while (loop == 0) */
356
357         DEBUG ("return (0);");
358         return (0);
359 } /* int do_loop */
360
361 static int do_shutdown (void)
362 {
363         plugin_shutdown_all ();
364         return (0);
365 } /* int do_shutdown */
366
367 #if COLLECT_DAEMON
368 static int pidfile_create (void)
369 {
370         FILE *fh;
371         const char *file = global_option_get ("PIDFile");
372
373         if ((fh = fopen (file, "w")) == NULL)
374         {
375                 char errbuf[1024];
376                 ERROR ("fopen (%s): %s", file,
377                                 sstrerror (errno, errbuf, sizeof (errbuf)));
378                 return (1);
379         }
380
381         fprintf (fh, "%i\n", (int) getpid ());
382         fclose(fh);
383
384         return (0);
385 } /* static int pidfile_create (const char *file) */
386
387 static int pidfile_remove (void)
388 {
389         const char *file = global_option_get ("PIDFile");
390
391         DEBUG ("unlink (%s)", (file != NULL) ? file : "<null>");
392         return (unlink (file));
393 } /* static int pidfile_remove (const char *file) */
394 #endif /* COLLECT_DAEMON */
395
396 int main (int argc, char **argv)
397 {
398         struct sigaction sig_int_action;
399         struct sigaction sig_term_action;
400         struct sigaction sig_usr1_action;
401         struct sigaction sig_pipe_action;
402         char *configfile = CONFIGFILE;
403         int test_config  = 0;
404         int test_readall = 0;
405         const char *basedir;
406 #if COLLECT_DAEMON
407         struct sigaction sig_chld_action;
408         pid_t pid;
409         int daemonize    = 1;
410 #endif
411         int exit_status = 0;
412
413         /* read options */
414         while (1)
415         {
416                 int c;
417
418                 c = getopt (argc, argv, "htTC:"
419 #if COLLECT_DAEMON
420                                 "fP:"
421 #endif
422                 );
423
424                 if (c == -1)
425                         break;
426
427                 switch (c)
428                 {
429                         case 'C':
430                                 configfile = optarg;
431                                 break;
432                         case 't':
433                                 test_config = 1;
434                                 break;
435                         case 'T':
436                                 test_readall = 1;
437                                 global_option_set ("ReadThreads", "-1");
438 #if COLLECT_DAEMON
439                                 daemonize = 0;
440 #endif /* COLLECT_DAEMON */
441                                 break;
442 #if COLLECT_DAEMON
443                         case 'P':
444                                 global_option_set ("PIDFile", optarg);
445                                 break;
446                         case 'f':
447                                 daemonize = 0;
448                                 break;
449 #endif /* COLLECT_DAEMON */
450                         case 'h':
451                                 exit_usage (0);
452                                 break;
453                         default:
454                                 exit_usage (1);
455                 } /* switch (c) */
456         } /* while (1) */
457
458         if (optind < argc)
459                 exit_usage (1);
460
461         /*
462          * Read options from the config file, the environment and the command
463          * line (in that order, with later options overwriting previous ones in
464          * general).
465          * Also, this will automatically load modules.
466          */
467         if (cf_read (configfile))
468         {
469                 fprintf (stderr, "Error: Reading the config file failed!\n"
470                                 "Read the syslog for details.\n");
471                 return (1);
472         }
473
474         /*
475          * Change directory. We do this _after_ reading the config and loading
476          * modules to relative paths work as expected.
477          */
478         if ((basedir = global_option_get ("BaseDir")) == NULL)
479         {
480                 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
481                 return (1);
482         }
483         else if (change_basedir (basedir))
484         {
485                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
486                 return (1);
487         }
488
489         /*
490          * Set global variables or, if that failes, exit. We cannot run with
491          * them being uninitialized. If nothing is configured, then defaults
492          * are being used. So this means that the user has actually done
493          * something wrong.
494          */
495         if (init_global_variables () != 0)
496                 return (1);
497
498         if (test_config)
499                 return (0);
500
501 #if COLLECT_DAEMON
502         /*
503          * fork off child
504          */
505         memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
506         sig_chld_action.sa_handler = SIG_IGN;
507         sigaction (SIGCHLD, &sig_chld_action, NULL);
508
509         if (daemonize)
510         {
511                 if ((pid = fork ()) == -1)
512                 {
513                         /* error */
514                         char errbuf[1024];
515                         fprintf (stderr, "fork: %s",
516                                         sstrerror (errno, errbuf,
517                                                 sizeof (errbuf)));
518                         return (1);
519                 }
520                 else if (pid != 0)
521                 {
522                         /* parent */
523                         /* printf ("Running (PID %i)\n", pid); */
524                         return (0);
525                 }
526
527                 /* Detach from session */
528                 setsid ();
529
530                 /* Write pidfile */
531                 if (pidfile_create ())
532                         exit (2);
533
534                 /* close standard descriptors */
535                 close (2);
536                 close (1);
537                 close (0);
538
539                 if (open ("/dev/null", O_RDWR) != 0)
540                 {
541                         ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
542                         return (1);
543                 }
544                 if (dup (0) != 1)
545                 {
546                         ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
547                         return (1);
548                 }
549                 if (dup (0) != 2)
550                 {
551                         ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
552                         return (1);
553                 }
554         } /* if (daemonize) */
555 #endif /* COLLECT_DAEMON */
556
557         memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
558         sig_pipe_action.sa_handler = SIG_IGN;
559         sigaction (SIGPIPE, &sig_pipe_action, NULL);
560
561         /*
562          * install signal handlers
563          */
564         memset (&sig_int_action, '\0', sizeof (sig_int_action));
565         sig_int_action.sa_handler = sig_int_handler;
566         if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
567                 char errbuf[1024];
568                 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
569                                 sstrerror (errno, errbuf, sizeof (errbuf)));
570                 return (1);
571         }
572
573         memset (&sig_term_action, '\0', sizeof (sig_term_action));
574         sig_term_action.sa_handler = sig_term_handler;
575         if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
576                 char errbuf[1024];
577                 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
578                                 sstrerror (errno, errbuf, sizeof (errbuf)));
579                 return (1);
580         }
581
582         memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
583         sig_usr1_action.sa_handler = sig_usr1_handler;
584         if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
585                 char errbuf[1024];
586                 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
587                                 sstrerror (errno, errbuf, sizeof (errbuf)));
588                 return (1);
589         }
590
591         /*
592          * run the actual loops
593          */
594         do_init ();
595
596         if (test_readall)
597         {
598                 if (plugin_read_all_once () != 0)
599                         exit_status = 1;
600         }
601         else
602         {
603                 INFO ("Initialization complete, entering read-loop.");
604                 do_loop ();
605         }
606
607         /* close syslog */
608         INFO ("Exiting normally.");
609
610         do_shutdown ();
611
612 #if COLLECT_DAEMON
613         if (daemonize)
614                 pidfile_remove ();
615 #endif /* COLLECT_DAEMON */
616
617         return (exit_status);
618 } /* int main */