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