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