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>
46 #ifndef COLLECTD_LOCALE
47 #define COLLECTD_LOCALE "C"
52 static void *do_flush(void __attribute__((unused)) * arg) {
53 INFO("Flushing all data.");
54 plugin_flush(/* plugin = */ NULL,
57 INFO("Finished flushing all data.");
62 static void sig_int_handler(int __attribute__((unused)) signal) { loop++; }
64 static void sig_term_handler(int __attribute__((unused)) signal) { loop++; }
66 static void sig_usr1_handler(int __attribute__((unused)) signal) {
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);
78 static int init_hostname(void) {
81 struct addrinfo *ai_list;
84 long hostname_len = sysconf(_SC_HOST_NAME_MAX);
85 if (hostname_len == -1) {
86 hostname_len = NI_MAXHOST;
88 char hostname[hostname_len];
89 hostname_set(hostname);
91 str = global_option_get("Hostname");
92 if ((str != NULL) && (str[0] != 0)) {
97 if (gethostname(hostname, hostname_len) != 0) {
98 fprintf(stderr, "`gethostname' failed and no "
99 "hostname was configured.\n");
103 str = global_option_get("FQDNLookup");
107 struct addrinfo ai_hints = {.ai_flags = AI_CANONNAME};
109 status = getaddrinfo(hostname, NULL, &ai_hints, &ai_list);
111 ERROR("Looking up \"%s\" failed. You have set the "
112 "\"FQDNLookup\" option, but I cannot resolve "
113 "my hostname to a fully qualified domain "
114 "name. Please fix the network "
120 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
121 ai_ptr = ai_ptr->ai_next) {
122 if (ai_ptr->ai_canonname == NULL)
125 hostname_set(ai_ptr->ai_canonname);
129 freeaddrinfo(ai_list);
131 } /* int init_hostname */
133 static int init_global_variables(void) {
136 interval_g = cf_get_default_interval();
137 assert(interval_g > 0);
138 DEBUG("interval_g = %.3f;", CDTIME_T_TO_DOUBLE(interval_g));
140 str = global_option_get("Timeout");
143 timeout_g = atoi(str);
144 if (timeout_g <= 1) {
145 fprintf(stderr, "Cannot set the timeout to a correct value.\n"
146 "Please check your settings.\n");
149 DEBUG("timeout_g = %i;", timeout_g);
151 if (init_hostname() != 0)
153 DEBUG("hostname_g = %s;", hostname_g);
156 } /* int init_global_variables */
158 static int change_basedir(const char *orig_dir, _Bool create) {
163 dir = strdup(orig_dir);
166 ERROR("strdup failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
170 dirlen = strlen(dir);
171 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
172 dir[--dirlen] = '\0';
183 } else if (!create || (errno != ENOENT)) {
185 ERROR("change_basedir: chdir (%s): %s", dir,
186 sstrerror(errno, errbuf, sizeof(errbuf)));
191 status = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
194 ERROR("change_basedir: mkdir (%s): %s", dir,
195 sstrerror(errno, errbuf, sizeof(errbuf)));
203 ERROR("change_basedir: chdir (%s): %s", dir,
204 sstrerror(errno, errbuf, sizeof(errbuf)));
211 } /* static int change_basedir (char *dir) */
214 static void update_kstat(void) {
216 if ((kc = kstat_open()) == NULL)
217 ERROR("Unable to open kstat control structure");
220 kid = kstat_chain_update(kc);
222 INFO("kstat chain has been updated");
225 ERROR("kstat chain update failed");
226 /* else: everything works as expected */
230 } /* static void update_kstat (void) */
231 #endif /* HAVE_LIBKSTAT */
234 * Remove all settings but `-f' and `-C'
236 __attribute__((noreturn)) static void exit_usage(int status) {
237 printf("Usage: " PACKAGE_NAME " [OPTIONS]\n\n"
239 "Available options:\n"
241 " -C <file> Configuration file.\n"
242 " Default: " CONFIGFILE "\n"
243 " -t Test config and exit.\n"
244 " -T Test plugin read and exit.\n"
245 " -P <file> PID-file.\n"
246 " Default: " PIDFILE "\n"
248 " -f Don't fork to the background.\n"
250 " -B Don't create the BaseDir\n"
251 " -h Display help (this message)\n"
252 "\nBuiltin defaults:\n"
253 " Config file " CONFIGFILE "\n"
254 " PID file " PIDFILE "\n"
255 " Plugin directory " PLUGINDIR "\n"
256 " Data directory " PKGLOCALSTATEDIR "\n"
257 "\n" PACKAGE_NAME " " PACKAGE_VERSION ", http://collectd.org/\n"
258 "by Florian octo Forster <octo@collectd.org>\n"
259 "for contributions see `AUTHORS'\n");
261 } /* static void exit_usage (int status) */
263 static int do_init(void) {
265 if (setlocale(LC_NUMERIC, COLLECTD_LOCALE) == NULL)
266 WARNING("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
268 /* Update the environment, so that libraries that are calling
269 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
271 setenv("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
281 #if HAVE_LIBSTATGRAB_0_90
285 ERROR("sg_init: %s", sg_str_error(sg_get_error()));
289 if (sg_drop_privileges()) {
290 ERROR("sg_drop_privileges: %s", sg_str_error(sg_get_error()));
295 return plugin_init_all();
296 } /* int do_init () */
298 static int do_loop(void) {
299 cdtime_t interval = cf_get_default_interval();
302 wait_until = cdtime() + interval;
311 /* Issue all plugins */
315 if (now >= wait_until) {
316 WARNING("Not sleeping because the next interval is "
317 "%.3f seconds in the past!",
318 CDTIME_T_TO_DOUBLE(now - wait_until));
319 wait_until = now + interval;
323 struct timespec ts_wait = CDTIME_T_TO_TIMESPEC(wait_until - now);
324 wait_until = wait_until + interval;
326 while ((loop == 0) && (nanosleep(&ts_wait, &ts_wait) != 0)) {
327 if (errno != EINTR) {
329 ERROR("nanosleep failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
333 } /* while (loop == 0) */
338 static int do_shutdown(void) {
339 return plugin_shutdown_all();
340 } /* int do_shutdown */
343 static int pidfile_create(void) {
345 const char *file = global_option_get("PIDFile");
347 if ((fh = fopen(file, "w")) == NULL) {
349 ERROR("fopen (%s): %s", file, sstrerror(errno, errbuf, sizeof(errbuf)));
353 fprintf(fh, "%i\n", (int)getpid());
357 } /* static int pidfile_create (const char *file) */
359 static int pidfile_remove(void) {
360 const char *file = global_option_get("PIDFile");
365 } /* static int pidfile_remove (const char *file) */
366 #endif /* COLLECT_DAEMON */
369 static int notify_upstart(void) {
370 char const *upstart_job = getenv("UPSTART_JOB");
372 if (upstart_job == NULL)
375 if (strcmp(upstart_job, "collectd") != 0) {
376 WARNING("Environment specifies unexpected UPSTART_JOB=\"%s\", expected "
377 "\"collectd\". Ignoring the variable.",
382 NOTICE("Upstart detected, stopping now to signal readyness.");
384 unsetenv("UPSTART_JOB");
389 static int notify_systemd(void) {
391 const char *notifysocket;
392 struct sockaddr_un su = {0};
394 char buffer[] = "READY=1\n";
396 notifysocket = getenv("NOTIFY_SOCKET");
397 if (notifysocket == NULL)
400 if ((strlen(notifysocket) < 2) ||
401 ((notifysocket[0] != '@') && (notifysocket[0] != '/'))) {
402 ERROR("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be "
407 NOTICE("Systemd detected, trying to signal readyness.");
409 unsetenv("NOTIFY_SOCKET");
411 #if defined(SOCK_CLOEXEC)
412 fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, /* protocol = */ 0);
414 fd = socket(AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
418 ERROR("creating UNIX socket failed: %s",
419 sstrerror(errno, errbuf, sizeof(errbuf)));
423 su.sun_family = AF_UNIX;
424 if (notifysocket[0] != '@') {
425 /* regular UNIX socket */
426 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
427 su_size = sizeof(su);
429 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
430 * start with a null byte. Since null bytes have no special meaning in
431 * that case, we have to set su_size correctly to cover only the bytes
432 * that are part of the address. */
433 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
435 su_size = sizeof(sa_family_t) + strlen(notifysocket);
436 if (su_size > sizeof(su))
437 su_size = sizeof(su);
440 if (sendto(fd, buffer, strlen(buffer), MSG_NOSIGNAL, (void *)&su,
441 (socklen_t)su_size) < 0) {
443 ERROR("sendto(\"%s\") failed: %s", notifysocket,
444 sstrerror(errno, errbuf, sizeof(errbuf)));
449 unsetenv("NOTIFY_SOCKET");
453 #endif /* KERNEL_LINUX */
455 struct cmdline_config {
458 _Bool create_basedir;
459 const char *configfile;
463 void read_cmdline(int argc, char **argv, struct cmdline_config *config) {
467 c = getopt(argc, argv, "htTC:"
478 config->create_basedir = 0;
481 config->configfile = optarg;
484 config->test_config = 1;
487 config->test_readall = 1;
488 global_option_set("ReadThreads", "-1", 1);
490 config->daemonize = 0;
491 #endif /* COLLECT_DAEMON */
495 global_option_set("PIDFile", optarg, 1);
498 config->daemonize = 0;
500 #endif /* COLLECT_DAEMON */
510 int configure_collectd(struct cmdline_config *config) {
513 * Read options from the config file, the environment and the command
514 * line (in that order, with later options overwriting previous ones in
516 * Also, this will automatically load modules.
518 if (cf_read(config->configfile)) {
519 fprintf(stderr, "Error: Reading the config file failed!\n"
520 "Read the logs for details.\n");
525 * Change directory. We do this _after_ reading the config and loading
526 * modules to relative paths work as expected.
528 if ((basedir = global_option_get("BaseDir")) == NULL) {
530 "Don't have a basedir to use. This should not happen. Ever.");
532 } else if (change_basedir(basedir, config->create_basedir)) {
533 fprintf(stderr, "Error: Unable to change to directory `%s'.\n", basedir);
538 * Set global variables or, if that fails, exit. We cannot run with
539 * them being uninitialized. If nothing is configured, then defaults
540 * are being used. So this means that the user has actually done
543 if (init_global_variables() != 0)
549 int main(int argc, char **argv) {
555 struct cmdline_config config = {
556 .daemonize = 1, .create_basedir = 1, .configfile = CONFIGFILE,
559 read_cmdline(argc, argv, &config);
561 if (config.test_config)
570 if ((status = configure_collectd(&config)) != 0)
577 struct sigaction sig_chld_action = {.sa_handler = SIG_IGN};
579 sigaction(SIGCHLD, &sig_chld_action, NULL);
582 * Only daemonize if we're not being supervised
583 * by upstart or systemd (when using Linux).
587 && notify_upstart() == 0 && notify_systemd() == 0
592 if ((pid = fork()) == -1) {
595 fprintf(stderr, "fork: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
597 } else if (pid != 0) {
599 /* printf ("Running (PID %i)\n", pid); */
603 /* Detach from session */
607 if (pidfile_create())
610 /* close standard descriptors */
615 status = open("/dev/null", O_RDWR);
617 ERROR("Error: Could not connect `STDIN' to `/dev/null' (status %d)",
624 ERROR("Error: Could not connect `STDOUT' to `/dev/null' (status %d)",
631 ERROR("Error: Could not connect `STDERR' to `/dev/null', (status %d)",
635 } /* if (config.daemonize) */
636 #endif /* COLLECT_DAEMON */
638 struct sigaction sig_pipe_action = {.sa_handler = SIG_IGN};
640 sigaction(SIGPIPE, &sig_pipe_action, NULL);
643 * install signal handlers
645 struct sigaction sig_int_action = {.sa_handler = sig_int_handler};
647 if (0 != sigaction(SIGINT, &sig_int_action, NULL)) {
649 ERROR("Error: Failed to install a signal handler for signal INT: %s",
650 sstrerror(errno, errbuf, sizeof(errbuf)));
654 struct sigaction sig_term_action = {.sa_handler = sig_term_handler};
656 if (0 != sigaction(SIGTERM, &sig_term_action, NULL)) {
658 ERROR("Error: Failed to install a signal handler for signal TERM: %s",
659 sstrerror(errno, errbuf, sizeof(errbuf)));
663 struct sigaction sig_usr1_action = {.sa_handler = sig_usr1_handler};
665 if (0 != sigaction(SIGUSR1, &sig_usr1_action, NULL)) {
667 ERROR("Error: Failed to install a signal handler for signal USR1: %s",
668 sstrerror(errno, errbuf, sizeof(errbuf)));
673 * run the actual loops
675 if (do_init() != 0) {
676 ERROR("Error: one or more plugin init callbacks failed.");
680 if (config.test_readall) {
681 if (plugin_read_all_once() != 0) {
682 ERROR("Error: one or more plugin read callbacks failed.");
686 INFO("Initialization complete, entering read-loop.");
691 INFO("Exiting normally.");
693 if (do_shutdown() != 0) {
694 ERROR("Error: one or more plugin shutdown callbacks failed.");
699 if (config.daemonize)
701 #endif /* COLLECT_DAEMON */