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"
53 char hostname_g[DATA_MAX_NAME_LEN];
58 #endif /* HAVE_LIBKSTAT */
62 static void *do_flush(void __attribute__((unused)) * arg) {
63 INFO("Flushing all data.");
64 plugin_flush(/* plugin = */ NULL,
67 INFO("Finished flushing all data.");
72 static void sig_int_handler(int __attribute__((unused)) signal) { loop++; }
74 static void sig_term_handler(int __attribute__((unused)) signal) { loop++; }
76 static void sig_usr1_handler(int __attribute__((unused)) signal) {
80 /* flushing the data might take a while,
81 * so it should be done asynchronously */
82 pthread_attr_init(&attr);
83 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
84 pthread_create(&thread, &attr, do_flush, NULL);
85 pthread_attr_destroy(&attr);
88 static int init_hostname(void) {
91 struct addrinfo *ai_list;
94 str = global_option_get("Hostname");
95 if ((str != NULL) && (str[0] != 0)) {
96 sstrncpy(hostname_g, str, sizeof(hostname_g));
100 if (gethostname(hostname_g, sizeof(hostname_g)) != 0) {
101 fprintf(stderr, "`gethostname' failed and no "
102 "hostname was configured.\n");
106 str = global_option_get("FQDNLookup");
110 struct addrinfo ai_hints = {.ai_flags = AI_CANONNAME};
112 status = getaddrinfo(hostname_g, NULL, &ai_hints, &ai_list);
114 ERROR("Looking up \"%s\" failed. You have set the "
115 "\"FQDNLookup\" option, but I cannot resolve "
116 "my hostname to a fully qualified domain "
117 "name. Please fix the network "
123 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL;
124 ai_ptr = ai_ptr->ai_next) {
125 if (ai_ptr->ai_canonname == NULL)
128 sstrncpy(hostname_g, ai_ptr->ai_canonname, sizeof(hostname_g));
132 freeaddrinfo(ai_list);
134 } /* int init_hostname */
136 static int init_global_variables(void) {
139 interval_g = cf_get_default_interval();
140 assert(interval_g > 0);
141 DEBUG("interval_g = %.3f;", CDTIME_T_TO_DOUBLE(interval_g));
143 str = global_option_get("Timeout");
146 timeout_g = atoi(str);
147 if (timeout_g <= 1) {
148 fprintf(stderr, "Cannot set the timeout to a correct value.\n"
149 "Please check your settings.\n");
152 DEBUG("timeout_g = %i;", timeout_g);
154 if (init_hostname() != 0)
156 DEBUG("hostname_g = %s;", hostname_g);
159 } /* int init_global_variables */
161 static int change_basedir(const char *orig_dir, int nocreate) {
166 dir = strdup(orig_dir);
169 ERROR("strdup failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
173 dirlen = strlen(dir);
174 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
175 dir[--dirlen] = '\0';
186 } else if (errno != ENOENT) {
188 ERROR("change_basedir: chdir (%s): %s", dir,
189 sstrerror(errno, errbuf, sizeof(errbuf)));
195 status = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
198 ERROR("change_basedir: mkdir (%s): %s", dir,
199 sstrerror(errno, errbuf, sizeof(errbuf)));
208 ERROR("change_basedir: chdir (%s): %s", dir,
209 sstrerror(errno, errbuf, sizeof(errbuf)));
216 } /* static int change_basedir (char *dir) */
219 static void update_kstat(void) {
221 if ((kc = kstat_open()) == NULL)
222 ERROR("Unable to open kstat control structure");
225 kid = kstat_chain_update(kc);
227 INFO("kstat chain has been updated");
230 ERROR("kstat chain update failed");
231 /* else: everything works as expected */
235 } /* static void update_kstat (void) */
236 #endif /* HAVE_LIBKSTAT */
239 * Remove all settings but `-f' and `-C'
241 __attribute__((noreturn)) static void exit_usage(int status) {
242 printf("Usage: " PACKAGE_NAME " [OPTIONS]\n\n"
244 "Available options:\n"
246 " -C <file> Configuration file.\n"
247 " Default: " CONFIGFILE "\n"
248 " -t Test config and exit.\n"
249 " -T Test plugin read and exit.\n"
250 " -P <file> PID-file.\n"
251 " Default: " PIDFILE "\n"
253 " -f Don't fork to the background.\n"
255 " -B Don't create the BaseDir\n"
256 " -h Display help (this message)\n"
257 "\nBuiltin defaults:\n"
258 " Config file " CONFIGFILE "\n"
259 " PID file " PIDFILE "\n"
260 " Plugin directory " PLUGINDIR "\n"
261 " Data directory " PKGLOCALSTATEDIR "\n"
262 "\n" PACKAGE_NAME " " PACKAGE_VERSION ", http://collectd.org/\n"
263 "by Florian octo Forster <octo@collectd.org>\n"
264 "for contributions see `AUTHORS'\n");
266 } /* static void exit_usage (int status) */
268 static int do_init(void) {
270 if (setlocale(LC_NUMERIC, COLLECTD_LOCALE) == NULL)
271 WARNING("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
273 /* Update the environment, so that libraries that are calling
274 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
276 setenv("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
286 #if HAVE_LIBSTATGRAB_0_90
290 ERROR("sg_init: %s", sg_str_error(sg_get_error()));
294 if (sg_drop_privileges()) {
295 ERROR("sg_drop_privileges: %s", sg_str_error(sg_get_error()));
300 return plugin_init_all();
301 } /* int do_init () */
303 static int do_loop(void) {
304 cdtime_t interval = cf_get_default_interval();
307 wait_until = cdtime() + interval;
316 /* Issue all plugins */
320 if (now >= wait_until) {
321 WARNING("Not sleeping because the next interval is "
322 "%.3f seconds in the past!",
323 CDTIME_T_TO_DOUBLE(now - wait_until));
324 wait_until = now + interval;
328 struct timespec ts_wait = CDTIME_T_TO_TIMESPEC(wait_until - now);
329 wait_until = wait_until + interval;
331 while ((loop == 0) && (nanosleep(&ts_wait, &ts_wait) != 0)) {
332 if (errno != EINTR) {
334 ERROR("nanosleep failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
338 } /* while (loop == 0) */
343 static int do_shutdown(void) {
344 return plugin_shutdown_all();
345 } /* int do_shutdown */
348 static int pidfile_create(void) {
350 const char *file = global_option_get("PIDFile");
352 if ((fh = fopen(file, "w")) == NULL) {
354 ERROR("fopen (%s): %s", file, sstrerror(errno, errbuf, sizeof(errbuf)));
358 fprintf(fh, "%i\n", (int)getpid());
362 } /* static int pidfile_create (const char *file) */
364 static int pidfile_remove(void) {
365 const char *file = global_option_get("PIDFile");
370 } /* static int pidfile_remove (const char *file) */
371 #endif /* COLLECT_DAEMON */
374 static int notify_upstart(void) {
375 char const *upstart_job = getenv("UPSTART_JOB");
377 if (upstart_job == NULL)
380 if (strcmp(upstart_job, "collectd") != 0) {
381 WARNING("Environment specifies unexpected UPSTART_JOB=\"%s\", expected "
382 "\"collectd\". Ignoring the variable.",
387 NOTICE("Upstart detected, stopping now to signal readyness.");
389 unsetenv("UPSTART_JOB");
394 static int notify_systemd(void) {
396 const char *notifysocket;
397 struct sockaddr_un su = {0};
399 char buffer[] = "READY=1\n";
401 notifysocket = getenv("NOTIFY_SOCKET");
402 if (notifysocket == NULL)
405 if ((strlen(notifysocket) < 2) ||
406 ((notifysocket[0] != '@') && (notifysocket[0] != '/'))) {
407 ERROR("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be "
412 NOTICE("Systemd detected, trying to signal readyness.");
414 unsetenv("NOTIFY_SOCKET");
416 #if defined(SOCK_CLOEXEC)
417 fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, /* protocol = */ 0);
419 fd = socket(AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
423 ERROR("creating UNIX socket failed: %s",
424 sstrerror(errno, errbuf, sizeof(errbuf)));
428 su.sun_family = AF_UNIX;
429 if (notifysocket[0] != '@') {
430 /* regular UNIX socket */
431 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
432 su_size = sizeof(su);
434 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
435 * start with a null byte. Since null bytes have no special meaning in
436 * that case, we have to set su_size correctly to cover only the bytes
437 * that are part of the address. */
438 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
440 su_size = sizeof(sa_family_t) + strlen(notifysocket);
441 if (su_size > sizeof(su))
442 su_size = sizeof(su);
445 if (sendto(fd, buffer, strlen(buffer), MSG_NOSIGNAL, (void *)&su,
446 (socklen_t)su_size) < 0) {
448 ERROR("sendto(\"%s\") failed: %s", notifysocket,
449 sstrerror(errno, errbuf, sizeof(errbuf)));
454 unsetenv("NOTIFY_SOCKET");
458 #endif /* KERNEL_LINUX */
460 int main(int argc, char **argv) {
461 const char *configfile = CONFIGFILE;
463 int test_readall = 0;
465 int basedir_nocreate = 0;
476 c = getopt(argc, argv, "BhtTC:"
487 basedir_nocreate = 1;
497 global_option_set("ReadThreads", "-1", 1);
500 #endif /* COLLECT_DAEMON */
504 global_option_set("PIDFile", optarg, 1);
509 #endif /* COLLECT_DAEMON */
524 * Read options from the config file, the environment and the command
525 * line (in that order, with later options overwriting previous ones in
527 * Also, this will automatically load modules.
529 if (cf_read(configfile)) {
530 fprintf(stderr, "Error: Reading the config file failed!\n"
531 "Read the logs for details.\n");
536 * Change directory. We do this _after_ reading the config and loading
537 * modules to relative paths work as expected.
539 if ((basedir = global_option_get("BaseDir")) == NULL) {
541 "Don't have a basedir to use. This should not happen. Ever.");
543 } else if (change_basedir(basedir, basedir_nocreate)) {
544 fprintf(stderr, "Error: Unable to change to directory `%s'.\n", basedir);
549 * Set global variables or, if that failes, exit. We cannot run with
550 * them being uninitialized. If nothing is configured, then defaults
551 * are being used. So this means that the user has actually done
554 if (init_global_variables() != 0)
564 struct sigaction sig_chld_action = {.sa_handler = SIG_IGN};
566 sigaction(SIGCHLD, &sig_chld_action, NULL);
569 * Only daemonize if we're not being supervised
570 * by upstart or systemd (when using Linux).
574 && notify_upstart() == 0 && notify_systemd() == 0
579 if ((pid = fork()) == -1) {
582 fprintf(stderr, "fork: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
584 } else if (pid != 0) {
586 /* printf ("Running (PID %i)\n", pid); */
590 /* Detach from session */
594 if (pidfile_create())
597 /* close standard descriptors */
602 status = open("/dev/null", O_RDWR);
604 ERROR("Error: Could not connect `STDIN' to `/dev/null' (status %d)",
611 ERROR("Error: Could not connect `STDOUT' to `/dev/null' (status %d)",
618 ERROR("Error: Could not connect `STDERR' to `/dev/null', (status %d)",
622 } /* if (daemonize) */
623 #endif /* COLLECT_DAEMON */
625 struct sigaction sig_pipe_action = {.sa_handler = SIG_IGN};
627 sigaction(SIGPIPE, &sig_pipe_action, NULL);
630 * install signal handlers
632 struct sigaction sig_int_action = {.sa_handler = sig_int_handler};
634 if (0 != sigaction(SIGINT, &sig_int_action, NULL)) {
636 ERROR("Error: Failed to install a signal handler for signal INT: %s",
637 sstrerror(errno, errbuf, sizeof(errbuf)));
641 struct sigaction sig_term_action = {.sa_handler = sig_term_handler};
643 if (0 != sigaction(SIGTERM, &sig_term_action, NULL)) {
645 ERROR("Error: Failed to install a signal handler for signal TERM: %s",
646 sstrerror(errno, errbuf, sizeof(errbuf)));
650 struct sigaction sig_usr1_action = {.sa_handler = sig_usr1_handler};
652 if (0 != sigaction(SIGUSR1, &sig_usr1_action, NULL)) {
654 ERROR("Error: Failed to install a signal handler for signal USR1: %s",
655 sstrerror(errno, errbuf, sizeof(errbuf)));
660 * run the actual loops
662 if (do_init() != 0) {
663 ERROR("Error: one or more plugin init callbacks failed.");
668 if (plugin_read_all_once() != 0) {
669 ERROR("Error: one or more plugin read callbacks failed.");
673 INFO("Initialization complete, entering read-loop.");
678 INFO("Exiting normally.");
680 if (do_shutdown() != 0) {
681 ERROR("Error: one or more plugin shutdown callbacks failed.");
688 #endif /* COLLECT_DAEMON */