2 * collectd - src/collectd.c
3 * Copyright (C) 2005-2007 Florian octo Forster
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Florian octo Forster <octo at collectd.org>
25 * Alvaro Barcellos <alvaro.barcellos at gmail.com>
31 #include "configfile.h"
35 #include <sys/types.h>
50 #ifndef COLLECTD_LOCALE
51 #define COLLECTD_LOCALE "C"
56 static void *do_flush(void __attribute__((unused)) * arg) {
57 INFO("Flushing all data.");
58 plugin_flush(/* plugin = */ NULL,
61 INFO("Finished flushing all data.");
66 static void sig_int_handler(int __attribute__((unused)) signal) { loop++; }
68 static void sig_term_handler(int __attribute__((unused)) signal) { loop++; }
70 static void sig_usr1_handler(int __attribute__((unused)) signal) {
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);
82 static int init_hostname(void) {
83 const char *str = global_option_get("Hostname");
84 if ((str != NULL) && (str[0] != 0)) {
89 long hostname_len = sysconf(_SC_HOST_NAME_MAX);
90 if (hostname_len == -1) {
91 hostname_len = NI_MAXHOST;
93 char hostname[hostname_len];
95 if (gethostname(hostname, hostname_len) != 0) {
96 fprintf(stderr, "`gethostname' failed and no "
97 "hostname was configured.\n");
101 hostname_set(hostname);
103 str = global_option_get("FQDNLookup");
107 struct addrinfo *ai_list;
108 struct addrinfo ai_hints = {.ai_flags = AI_CANONNAME};
110 int status = getaddrinfo(hostname, NULL, &ai_hints, &ai_list);
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 "
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)
126 hostname_set(ai_ptr->ai_canonname);
130 freeaddrinfo(ai_list);
132 } /* int init_hostname */
134 static int init_global_variables(void) {
137 interval_g = cf_get_default_interval();
138 assert(interval_g > 0);
139 DEBUG("interval_g = %.3f;", CDTIME_T_TO_DOUBLE(interval_g));
141 str = global_option_get("Timeout");
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");
150 DEBUG("timeout_g = %i;", timeout_g);
152 if (init_hostname() != 0)
154 DEBUG("hostname_g = %s;", hostname_g);
157 } /* int init_global_variables */
159 static int change_basedir(const char *orig_dir, _Bool create) {
164 dir = strdup(orig_dir);
166 ERROR("strdup failed: %s", STRERRNO);
170 dirlen = strlen(dir);
171 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
172 dir[--dirlen] = '\0';
183 } else if (!create || (errno != ENOENT)) {
184 ERROR("change_basedir: chdir (%s): %s", dir, STRERRNO);
189 status = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
191 ERROR("change_basedir: mkdir (%s): %s", dir, STRERRNO);
198 ERROR("change_basedir: chdir (%s): %s", dir, STRERRNO);
205 } /* static int change_basedir (char *dir) */
208 extern kstat_ctl_t *kc;
209 static void update_kstat(void) {
211 if ((kc = kstat_open()) == NULL)
212 ERROR("Unable to open kstat control structure");
215 kid = kstat_chain_update(kc);
217 INFO("kstat chain has been updated");
220 ERROR("kstat chain update failed");
221 /* else: everything works as expected */
225 } /* static void update_kstat (void) */
226 #endif /* HAVE_LIBKSTAT */
229 * Remove all settings but `-f' and `-C'
231 __attribute__((noreturn)) static void exit_usage(int status) {
232 printf("Usage: " PACKAGE_NAME " [OPTIONS]\n\n"
234 "Available options:\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"
243 " -f Don't fork to the background.\n"
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");
256 } /* static void exit_usage (int status) */
258 static int do_init(void) {
260 if (setlocale(LC_NUMERIC, COLLECTD_LOCALE) == NULL)
261 WARNING("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
263 /* Update the environment, so that libraries that are calling
264 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
266 setenv("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
276 #if HAVE_LIBSTATGRAB_0_90
280 ERROR("sg_init: %s", sg_str_error(sg_get_error()));
284 if (sg_drop_privileges()) {
285 ERROR("sg_drop_privileges: %s", sg_str_error(sg_get_error()));
290 return plugin_init_all();
291 } /* int do_init () */
293 static int do_loop(void) {
294 cdtime_t interval = cf_get_default_interval();
297 wait_until = cdtime() + interval;
306 /* Issue all plugins */
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;
318 struct timespec ts_wait = CDTIME_T_TO_TIMESPEC(wait_until - now);
319 wait_until = wait_until + interval;
321 while ((loop == 0) && (nanosleep(&ts_wait, &ts_wait) != 0)) {
322 if (errno != EINTR) {
323 ERROR("nanosleep failed: %s", STRERRNO);
327 } /* while (loop == 0) */
332 static int do_shutdown(void) {
333 return plugin_shutdown_all();
334 } /* int do_shutdown */
337 static int pidfile_create(void) {
339 const char *file = global_option_get("PIDFile");
341 if ((fh = fopen(file, "w")) == NULL) {
342 ERROR("fopen (%s): %s", file, STRERRNO);
346 fprintf(fh, "%i\n", (int)getpid());
350 } /* static int pidfile_create (const char *file) */
352 static int pidfile_remove(void) {
353 const char *file = global_option_get("PIDFile");
358 } /* static int pidfile_remove (const char *file) */
359 #endif /* COLLECT_DAEMON */
362 static int notify_upstart(void) {
363 char const *upstart_job = getenv("UPSTART_JOB");
365 if (upstart_job == NULL)
368 if (strcmp(upstart_job, "collectd") != 0) {
369 WARNING("Environment specifies unexpected UPSTART_JOB=\"%s\", expected "
370 "\"collectd\". Ignoring the variable.",
375 NOTICE("Upstart detected, stopping now to signal readiness.");
377 unsetenv("UPSTART_JOB");
382 static int notify_systemd(void) {
384 const char *notifysocket;
385 struct sockaddr_un su = {0};
387 char buffer[] = "READY=1\n";
389 notifysocket = getenv("NOTIFY_SOCKET");
390 if (notifysocket == NULL)
393 if ((strlen(notifysocket) < 2) ||
394 ((notifysocket[0] != '@') && (notifysocket[0] != '/'))) {
395 ERROR("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be "
400 NOTICE("Systemd detected, trying to signal readiness.");
402 unsetenv("NOTIFY_SOCKET");
404 #if defined(SOCK_CLOEXEC)
405 fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, /* protocol = */ 0);
407 fd = socket(AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
410 ERROR("creating UNIX socket failed: %s", STRERRNO);
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);
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));
426 su_size = sizeof(sa_family_t) + strlen(notifysocket);
427 if (su_size > sizeof(su))
428 su_size = sizeof(su);
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);
438 unsetenv("NOTIFY_SOCKET");
442 #endif /* KERNEL_LINUX */
444 struct cmdline_config {
447 _Bool create_basedir;
448 const char *configfile;
452 void read_cmdline(int argc, char **argv, struct cmdline_config *config) {
456 c = getopt(argc, argv, "htTC:"
467 config->create_basedir = 0;
470 config->configfile = optarg;
473 config->test_config = 1;
476 config->test_readall = 1;
477 global_option_set("ReadThreads", "-1", 1);
479 config->daemonize = 0;
480 #endif /* COLLECT_DAEMON */
484 global_option_set("PIDFile", optarg, 1);
487 config->daemonize = 0;
489 #endif /* COLLECT_DAEMON */
499 int configure_collectd(struct cmdline_config *config) {
502 * Read options from the config file, the environment and the command
503 * line (in that order, with later options overwriting previous ones in
505 * Also, this will automatically load modules.
507 if (cf_read(config->configfile)) {
508 fprintf(stderr, "Error: Reading the config file failed!\n"
509 "Read the logs for details.\n");
514 * Change directory. We do this _after_ reading the config and loading
515 * modules to relative paths work as expected.
517 if ((basedir = global_option_get("BaseDir")) == NULL) {
519 "Don't have a basedir to use. This should not happen. Ever.");
521 } else if (change_basedir(basedir, config->create_basedir)) {
522 fprintf(stderr, "Error: Unable to change to directory `%s'.\n", basedir);
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
532 if (init_global_variables() != 0)
538 int main(int argc, char **argv) {
544 struct cmdline_config config = {
545 .daemonize = 1, .create_basedir = 1, .configfile = CONFIGFILE,
548 read_cmdline(argc, argv, &config);
550 if (config.test_config)
559 if ((status = configure_collectd(&config)) != 0)
566 struct sigaction sig_chld_action = {.sa_handler = SIG_IGN};
568 sigaction(SIGCHLD, &sig_chld_action, NULL);
571 * Only daemonize if we're not being supervised
572 * by upstart or systemd (when using Linux).
576 && notify_upstart() == 0 && notify_systemd() == 0
581 if ((pid = fork()) == -1) {
583 fprintf(stderr, "fork: %s", STRERRNO);
585 } else if (pid != 0) {
587 /* printf ("Running (PID %i)\n", pid); */
591 /* Detach from session */
595 if (pidfile_create())
598 /* close standard descriptors */
603 status = open("/dev/null", O_RDWR);
605 ERROR("Error: Could not connect `STDIN' to `/dev/null' (status %d)",
612 ERROR("Error: Could not connect `STDOUT' to `/dev/null' (status %d)",
619 ERROR("Error: Could not connect `STDERR' to `/dev/null', (status %d)",
623 } /* if (config.daemonize) */
624 #endif /* COLLECT_DAEMON */
626 struct sigaction sig_pipe_action = {.sa_handler = SIG_IGN};
628 sigaction(SIGPIPE, &sig_pipe_action, NULL);
631 * install signal handlers
633 struct sigaction sig_int_action = {.sa_handler = sig_int_handler};
635 if (0 != sigaction(SIGINT, &sig_int_action, NULL)) {
636 ERROR("Error: Failed to install a signal handler for signal INT: %s",
641 struct sigaction sig_term_action = {.sa_handler = sig_term_handler};
643 if (0 != sigaction(SIGTERM, &sig_term_action, NULL)) {
644 ERROR("Error: Failed to install a signal handler for signal TERM: %s",
649 struct sigaction sig_usr1_action = {.sa_handler = sig_usr1_handler};
651 if (0 != sigaction(SIGUSR1, &sig_usr1_action, NULL)) {
652 ERROR("Error: Failed to install a signal handler for signal USR1: %s",
658 * run the actual loops
660 if (do_init() != 0) {
661 ERROR("Error: one or more plugin init callbacks failed.");
665 if (config.test_readall) {
666 if (plugin_read_all_once() != 0) {
667 ERROR("Error: one or more plugin read callbacks failed.");
671 INFO("Initialization complete, entering read-loop.");
676 INFO("Exiting normally.");
678 if (do_shutdown() != 0) {
679 ERROR("Error: one or more plugin shutdown callbacks failed.");
684 if (config.daemonize)
686 #endif /* COLLECT_DAEMON */