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