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