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