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