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