Don't initialize static numeric variables to 0
[collectd.git] / src / daemon / collectd.c
1 /**
2  * collectd - src/collectd.c
3  * Copyright (C) 2005-2007  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  *   Alvaro Barcellos <alvaro.barcellos at gmail.com>
26  **/
27
28 #include "collectd.h"
29
30 #include "common.h"
31 #include "configfile.h"
32 #include "plugin.h"
33
34 #include <netdb.h>
35 #include <sys/types.h>
36 #include <sys/un.h>
37
38 #if HAVE_LOCALE_H
39 #include <locale.h>
40 #endif
41
42 #if HAVE_STATGRAB_H
43 #include <statgrab.h>
44 #endif
45
46 #if HAVE_KSTAT_H
47 #include <kstat.h>
48 #endif
49
50 #ifndef COLLECTD_LOCALE
51 #define COLLECTD_LOCALE "C"
52 #endif
53
54 static int loop;
55
56 static void *do_flush(void __attribute__((unused)) * arg) {
57   INFO("Flushing all data.");
58   plugin_flush(/* plugin = */ NULL,
59                /* timeout = */ 0,
60                /* ident = */ NULL);
61   INFO("Finished flushing all data.");
62   pthread_exit(NULL);
63   return NULL;
64 }
65
66 static void sig_int_handler(int __attribute__((unused)) signal) { loop++; }
67
68 static void sig_term_handler(int __attribute__((unused)) signal) { loop++; }
69
70 static void sig_usr1_handler(int __attribute__((unused)) signal) {
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   pthread_attr_destroy(&attr);
80 }
81
82 static int init_hostname(void) {
83   const char *str = global_option_get("Hostname");
84   if ((str != NULL) && (str[0] != 0)) {
85     hostname_set(str);
86     return 0;
87   }
88
89   long hostname_len = sysconf(_SC_HOST_NAME_MAX);
90   if (hostname_len == -1) {
91     hostname_len = NI_MAXHOST;
92   }
93   char hostname[hostname_len];
94
95   if (gethostname(hostname, hostname_len) != 0) {
96     fprintf(stderr, "`gethostname' failed and no "
97                     "hostname was configured.\n");
98     return -1;
99   }
100
101   hostname_set(hostname);
102
103   str = global_option_get("FQDNLookup");
104   if (IS_FALSE(str))
105     return 0;
106
107   struct addrinfo *ai_list;
108   struct addrinfo ai_hints = {.ai_flags = AI_CANONNAME};
109
110   int status = getaddrinfo(hostname, NULL, &ai_hints, &ai_list);
111   if (status != 0) {
112     ERROR("Looking up \"%s\" failed. You have set the "
113           "\"FQDNLookup\" option, but I cannot resolve "
114           "my hostname to a fully qualified domain "
115           "name. Please fix the network "
116           "configuration.",
117           hostname);
118     return -1;
119   }
120
121   for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
122        ai_ptr = ai_ptr->ai_next) {
123     if (ai_ptr->ai_canonname == NULL)
124       continue;
125
126     hostname_set(ai_ptr->ai_canonname);
127     break;
128   }
129
130   freeaddrinfo(ai_list);
131   return 0;
132 } /* int init_hostname */
133
134 static int init_global_variables(void) {
135   char const *str;
136
137   interval_g = cf_get_default_interval();
138   assert(interval_g > 0);
139   DEBUG("interval_g = %.3f;", CDTIME_T_TO_DOUBLE(interval_g));
140
141   str = global_option_get("Timeout");
142   if (str == NULL)
143     str = "2";
144   timeout_g = atoi(str);
145   if (timeout_g <= 1) {
146     fprintf(stderr, "Cannot set the timeout to a correct value.\n"
147                     "Please check your settings.\n");
148     return -1;
149   }
150   DEBUG("timeout_g = %i;", timeout_g);
151
152   if (init_hostname() != 0)
153     return -1;
154   DEBUG("hostname_g = %s;", hostname_g);
155
156   return 0;
157 } /* int init_global_variables */
158
159 static int change_basedir(const char *orig_dir, bool create) {
160   char *dir;
161   size_t dirlen;
162   int status;
163
164   dir = strdup(orig_dir);
165   if (dir == NULL) {
166     ERROR("strdup failed: %s", STRERRNO);
167     return -1;
168   }
169
170   dirlen = strlen(dir);
171   while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
172     dir[--dirlen] = '\0';
173
174   if (dirlen == 0) {
175     free(dir);
176     return -1;
177   }
178
179   status = chdir(dir);
180   if (status == 0) {
181     free(dir);
182     return 0;
183   } else if (!create || (errno != ENOENT)) {
184     ERROR("change_basedir: chdir (%s): %s", dir, STRERRNO);
185     free(dir);
186     return -1;
187   }
188
189   status = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
190   if (status != 0) {
191     ERROR("change_basedir: mkdir (%s): %s", dir, STRERRNO);
192     free(dir);
193     return -1;
194   }
195
196   status = chdir(dir);
197   if (status != 0) {
198     ERROR("change_basedir: chdir (%s): %s", dir, STRERRNO);
199     free(dir);
200     return -1;
201   }
202
203   free(dir);
204   return 0;
205 } /* static int change_basedir (char *dir) */
206
207 #if HAVE_LIBKSTAT
208 extern kstat_ctl_t *kc;
209 static void update_kstat(void) {
210   if (kc == NULL) {
211     if ((kc = kstat_open()) == NULL)
212       ERROR("Unable to open kstat control structure");
213   } else {
214     kid_t kid;
215     kid = kstat_chain_update(kc);
216     if (kid > 0) {
217       INFO("kstat chain has been updated");
218       plugin_init_all();
219     } else if (kid < 0)
220       ERROR("kstat chain update failed");
221     /* else: everything works as expected */
222   }
223
224   return;
225 } /* static void update_kstat (void) */
226 #endif /* HAVE_LIBKSTAT */
227
228 /* TODO
229  * Remove all settings but `-f' and `-C'
230  */
231 __attribute__((noreturn)) static void exit_usage(int status) {
232   printf("Usage: " PACKAGE_NAME " [OPTIONS]\n\n"
233
234          "Available options:\n"
235          "  General:\n"
236          "    -C <file>       Configuration file.\n"
237          "                    Default: " CONFIGFILE "\n"
238          "    -t              Test config and exit.\n"
239          "    -T              Test plugin read and exit.\n"
240          "    -P <file>       PID-file.\n"
241          "                    Default: " PIDFILE "\n"
242 #if COLLECT_DAEMON
243          "    -f              Don't fork to the background.\n"
244 #endif
245          "    -B              Don't create the BaseDir\n"
246          "    -h              Display help (this message)\n"
247          "\nBuiltin defaults:\n"
248          "  Config file       " CONFIGFILE "\n"
249          "  PID file          " PIDFILE "\n"
250          "  Plugin directory  " PLUGINDIR "\n"
251          "  Data directory    " PKGLOCALSTATEDIR "\n"
252          "\n" PACKAGE_NAME " " PACKAGE_VERSION ", http://collectd.org/\n"
253          "by Florian octo Forster <octo@collectd.org>\n"
254          "for contributions see `AUTHORS'\n");
255   exit(status);
256 } /* static void exit_usage (int status) */
257
258 static int do_init(void) {
259 #if HAVE_SETLOCALE
260   if (setlocale(LC_NUMERIC, COLLECTD_LOCALE) == NULL)
261     WARNING("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
262
263   /* Update the environment, so that libraries that are calling
264    * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
265   unsetenv("LC_ALL");
266   setenv("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
267 #endif
268
269 #if HAVE_LIBKSTAT
270   kc = NULL;
271   update_kstat();
272 #endif
273
274 #if HAVE_LIBSTATGRAB
275   if (sg_init(
276 #if HAVE_LIBSTATGRAB_0_90
277           0
278 #endif
279           )) {
280     ERROR("sg_init: %s", sg_str_error(sg_get_error()));
281     return -1;
282   }
283
284   if (sg_drop_privileges()) {
285     ERROR("sg_drop_privileges: %s", sg_str_error(sg_get_error()));
286     return -1;
287   }
288 #endif
289
290   return plugin_init_all();
291 } /* int do_init () */
292
293 static int do_loop(void) {
294   cdtime_t interval = cf_get_default_interval();
295   cdtime_t wait_until;
296
297   wait_until = cdtime() + interval;
298
299   while (loop == 0) {
300     cdtime_t now;
301
302 #if HAVE_LIBKSTAT
303     update_kstat();
304 #endif
305
306     /* Issue all plugins */
307     plugin_read_all();
308
309     now = cdtime();
310     if (now >= wait_until) {
311       WARNING("Not sleeping because the next interval is "
312               "%.3f seconds in the past!",
313               CDTIME_T_TO_DOUBLE(now - wait_until));
314       wait_until = now + interval;
315       continue;
316     }
317
318     struct timespec ts_wait = CDTIME_T_TO_TIMESPEC(wait_until - now);
319     wait_until = wait_until + interval;
320
321     while ((loop == 0) && (nanosleep(&ts_wait, &ts_wait) != 0)) {
322       if (errno != EINTR) {
323         ERROR("nanosleep failed: %s", STRERRNO);
324         return -1;
325       }
326     }
327   } /* while (loop == 0) */
328
329   return 0;
330 } /* int do_loop */
331
332 static int do_shutdown(void) {
333   return plugin_shutdown_all();
334 } /* int do_shutdown */
335
336 #if COLLECT_DAEMON
337 static int pidfile_create(void) {
338   FILE *fh;
339   const char *file = global_option_get("PIDFile");
340
341   if ((fh = fopen(file, "w")) == NULL) {
342     ERROR("fopen (%s): %s", file, STRERRNO);
343     return 1;
344   }
345
346   fprintf(fh, "%i\n", (int)getpid());
347   fclose(fh);
348
349   return 0;
350 } /* static int pidfile_create (const char *file) */
351
352 static int pidfile_remove(void) {
353   const char *file = global_option_get("PIDFile");
354   if (file == NULL)
355     return 0;
356
357   return unlink(file);
358 } /* static int pidfile_remove (const char *file) */
359 #endif /* COLLECT_DAEMON */
360
361 #ifdef KERNEL_LINUX
362 static int notify_upstart(void) {
363   char const *upstart_job = getenv("UPSTART_JOB");
364
365   if (upstart_job == NULL)
366     return 0;
367
368   if (strcmp(upstart_job, "collectd") != 0) {
369     WARNING("Environment specifies unexpected UPSTART_JOB=\"%s\", expected "
370             "\"collectd\". Ignoring the variable.",
371             upstart_job);
372     return 0;
373   }
374
375   NOTICE("Upstart detected, stopping now to signal readiness.");
376   raise(SIGSTOP);
377   unsetenv("UPSTART_JOB");
378
379   return 1;
380 }
381
382 static int notify_systemd(void) {
383   int fd;
384   const char *notifysocket;
385   struct sockaddr_un su = {0};
386   size_t su_size;
387   char buffer[] = "READY=1\n";
388
389   notifysocket = getenv("NOTIFY_SOCKET");
390   if (notifysocket == NULL)
391     return 0;
392
393   if ((strlen(notifysocket) < 2) ||
394       ((notifysocket[0] != '@') && (notifysocket[0] != '/'))) {
395     ERROR("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be "
396           "absolute",
397           notifysocket);
398     return 0;
399   }
400   NOTICE("Systemd detected, trying to signal readiness.");
401
402   unsetenv("NOTIFY_SOCKET");
403
404 #if defined(SOCK_CLOEXEC)
405   fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, /* protocol = */ 0);
406 #else
407   fd = socket(AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
408 #endif
409   if (fd < 0) {
410     ERROR("creating UNIX socket failed: %s", STRERRNO);
411     return 0;
412   }
413
414   su.sun_family = AF_UNIX;
415   if (notifysocket[0] != '@') {
416     /* regular UNIX socket */
417     sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
418     su_size = sizeof(su);
419   } else {
420     /* Linux abstract namespace socket: specify address as "\0foo", i.e.
421      * start with a null byte. Since null bytes have no special meaning in
422      * that case, we have to set su_size correctly to cover only the bytes
423      * that are part of the address. */
424     sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
425     su.sun_path[0] = 0;
426     su_size = sizeof(sa_family_t) + strlen(notifysocket);
427     if (su_size > sizeof(su))
428       su_size = sizeof(su);
429   }
430
431   if (sendto(fd, buffer, strlen(buffer), MSG_NOSIGNAL, (void *)&su,
432              (socklen_t)su_size) < 0) {
433     ERROR("sendto(\"%s\") failed: %s", notifysocket, STRERRNO);
434     close(fd);
435     return 0;
436   }
437
438   unsetenv("NOTIFY_SOCKET");
439   close(fd);
440   return 1;
441 }
442 #endif /* KERNEL_LINUX */
443
444 struct cmdline_config {
445   bool test_config;
446   bool test_readall;
447   bool create_basedir;
448   const char *configfile;
449   bool daemonize;
450 };
451
452 static void read_cmdline(int argc, char **argv, struct cmdline_config *config) {
453   /* read options */
454   while (1) {
455     int c;
456     c = getopt(argc, argv, "htTC:"
457 #if COLLECT_DAEMON
458                            "fP:"
459 #endif
460                );
461
462     if (c == -1)
463       break;
464
465     switch (c) {
466     case 'B':
467       config->create_basedir = false;
468       break;
469     case 'C':
470       config->configfile = optarg;
471       break;
472     case 't':
473       config->test_config = true;
474       break;
475     case 'T':
476       config->test_readall = true;
477       global_option_set("ReadThreads", "-1", 1);
478 #if COLLECT_DAEMON
479       config->daemonize = false;
480 #endif /* COLLECT_DAEMON */
481       break;
482 #if COLLECT_DAEMON
483     case 'P':
484       global_option_set("PIDFile", optarg, 1);
485       break;
486     case 'f':
487       config->daemonize = false;
488       break;
489 #endif /* COLLECT_DAEMON */
490     case 'h':
491       exit_usage(0);
492       break;
493     default:
494       exit_usage(1);
495     } /* switch (c) */
496   }   /* while (1) */
497 }
498
499 static int configure_collectd(struct cmdline_config *config) {
500   const char *basedir;
501   /*
502    * Read options from the config file, the environment and the command
503    * line (in that order, with later options overwriting previous ones in
504    * general).
505    * Also, this will automatically load modules.
506    */
507   if (cf_read(config->configfile)) {
508     fprintf(stderr, "Error: Reading the config file failed!\n"
509                     "Read the logs for details.\n");
510     return 1;
511   }
512
513   /*
514    * Change directory. We do this _after_ reading the config and loading
515    * modules to relative paths work as expected.
516    */
517   if ((basedir = global_option_get("BaseDir")) == NULL) {
518     fprintf(stderr,
519             "Don't have a basedir to use. This should not happen. Ever.");
520     return 1;
521   } else if (change_basedir(basedir, config->create_basedir)) {
522     fprintf(stderr, "Error: Unable to change to directory `%s'.\n", basedir);
523     return 1;
524   }
525
526   /*
527    * Set global variables or, if that fails, exit. We cannot run with
528    * them being uninitialized. If nothing is configured, then defaults
529    * are being used. So this means that the user has actually done
530    * something wrong.
531    */
532   if (init_global_variables() != 0)
533     return 1;
534
535   return 0;
536 }
537
538 int main(int argc, char **argv) {
539 #if COLLECT_DAEMON
540   pid_t pid;
541 #endif
542   int exit_status = 0;
543
544   struct cmdline_config config = {
545       .daemonize = true, .create_basedir = true, .configfile = CONFIGFILE,
546   };
547
548   read_cmdline(argc, argv, &config);
549
550   if (config.test_config)
551     return 0;
552
553   if (optind < argc)
554     exit_usage(1);
555
556   plugin_init_ctx();
557
558   if (configure_collectd(&config) != 0)
559     exit(EXIT_FAILURE);
560
561 #if COLLECT_DAEMON
562   /*
563    * fork off child
564    */
565   struct sigaction sig_chld_action = {.sa_handler = SIG_IGN};
566
567   sigaction(SIGCHLD, &sig_chld_action, NULL);
568
569   /*
570    * Only daemonize if we're not being supervised
571    * by upstart or systemd (when using Linux).
572    */
573   if (config.daemonize
574 #ifdef KERNEL_LINUX
575       && notify_upstart() == 0 && notify_systemd() == 0
576 #endif
577       ) {
578     int status;
579
580     if ((pid = fork()) == -1) {
581       /* error */
582       fprintf(stderr, "fork: %s", STRERRNO);
583       return 1;
584     } else if (pid != 0) {
585       /* parent */
586       /* printf ("Running (PID %i)\n", pid); */
587       return 0;
588     }
589
590     /* Detach from session */
591     setsid();
592
593     /* Write pidfile */
594     if (pidfile_create())
595       exit(2);
596
597     /* close standard descriptors */
598     close(2);
599     close(1);
600     close(0);
601
602     status = open("/dev/null", O_RDWR);
603     if (status != 0) {
604       ERROR("Error: Could not connect `STDIN' to `/dev/null' (status %d)",
605             status);
606       return 1;
607     }
608
609     status = dup(0);
610     if (status != 1) {
611       ERROR("Error: Could not connect `STDOUT' to `/dev/null' (status %d)",
612             status);
613       return 1;
614     }
615
616     status = dup(0);
617     if (status != 2) {
618       ERROR("Error: Could not connect `STDERR' to `/dev/null', (status %d)",
619             status);
620       return 1;
621     }
622   }    /* if (config.daemonize) */
623 #endif /* COLLECT_DAEMON */
624
625   struct sigaction sig_pipe_action = {.sa_handler = SIG_IGN};
626
627   sigaction(SIGPIPE, &sig_pipe_action, NULL);
628
629   /*
630    * install signal handlers
631    */
632   struct sigaction sig_int_action = {.sa_handler = sig_int_handler};
633
634   if (0 != sigaction(SIGINT, &sig_int_action, NULL)) {
635     ERROR("Error: Failed to install a signal handler for signal INT: %s",
636           STRERRNO);
637     return 1;
638   }
639
640   struct sigaction sig_term_action = {.sa_handler = sig_term_handler};
641
642   if (0 != sigaction(SIGTERM, &sig_term_action, NULL)) {
643     ERROR("Error: Failed to install a signal handler for signal TERM: %s",
644           STRERRNO);
645     return 1;
646   }
647
648   struct sigaction sig_usr1_action = {.sa_handler = sig_usr1_handler};
649
650   if (0 != sigaction(SIGUSR1, &sig_usr1_action, NULL)) {
651     ERROR("Error: Failed to install a signal handler for signal USR1: %s",
652           STRERRNO);
653     return 1;
654   }
655
656   /*
657    * run the actual loops
658    */
659   if (do_init() != 0) {
660     ERROR("Error: one or more plugin init callbacks failed.");
661     exit_status = 1;
662   }
663
664   if (config.test_readall) {
665     if (plugin_read_all_once() != 0) {
666       ERROR("Error: one or more plugin read callbacks failed.");
667       exit_status = 1;
668     }
669   } else {
670     INFO("Initialization complete, entering read-loop.");
671     do_loop();
672   }
673
674   /* close syslog */
675   INFO("Exiting normally.");
676
677   if (do_shutdown() != 0) {
678     ERROR("Error: one or more plugin shutdown callbacks failed.");
679     exit_status = 1;
680   }
681
682 #if COLLECT_DAEMON
683   if (config.daemonize)
684     pidfile_remove();
685 #endif /* COLLECT_DAEMON */
686
687   return exit_status;
688 } /* int main */