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