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) {
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)));
194 status = mkdir(dir, S_IRWXU | S_IRWXG | S_IRWXO);
197 ERROR("change_basedir: mkdir (%s): %s", dir,
198 sstrerror(errno, errbuf, sizeof(errbuf)));
206 ERROR("change_basedir: chdir (%s): %s", dir,
207 sstrerror(errno, errbuf, sizeof(errbuf)));
214 } /* static int change_basedir (char *dir) */
217 static void update_kstat(void) {
219 if ((kc = kstat_open()) == NULL)
220 ERROR("Unable to open kstat control structure");
223 kid = kstat_chain_update(kc);
225 INFO("kstat chain has been updated");
228 ERROR("kstat chain update failed");
229 /* else: everything works as expected */
233 } /* static void update_kstat (void) */
234 #endif /* HAVE_LIBKSTAT */
237 * Remove all settings but `-f' and `-C'
239 __attribute__((noreturn)) static void exit_usage(int status) {
240 printf("Usage: " PACKAGE_NAME " [OPTIONS]\n\n"
242 "Available options:\n"
244 " -C <file> Configuration file.\n"
245 " Default: " CONFIGFILE "\n"
246 " -t Test config and exit.\n"
247 " -T Test plugin read and exit.\n"
248 " -P <file> PID-file.\n"
249 " Default: " PIDFILE "\n"
251 " -f Don't fork to the background.\n"
253 " -h Display help (this message)\n"
254 "\nBuiltin defaults:\n"
255 " Config file " CONFIGFILE "\n"
256 " PID file " PIDFILE "\n"
257 " Plugin directory " PLUGINDIR "\n"
258 " Data directory " PKGLOCALSTATEDIR "\n"
259 "\n" PACKAGE_NAME " " PACKAGE_VERSION ", http://collectd.org/\n"
260 "by Florian octo Forster <octo@collectd.org>\n"
261 "for contributions see `AUTHORS'\n");
263 } /* static void exit_usage (int status) */
265 static int do_init(void) {
267 if (setlocale(LC_NUMERIC, COLLECTD_LOCALE) == NULL)
268 WARNING("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
270 /* Update the environment, so that libraries that are calling
271 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
273 setenv("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
283 #if HAVE_LIBSTATGRAB_0_90
287 ERROR("sg_init: %s", sg_str_error(sg_get_error()));
291 if (sg_drop_privileges()) {
292 ERROR("sg_drop_privileges: %s", sg_str_error(sg_get_error()));
297 return plugin_init_all();
298 } /* int do_init () */
300 static int do_loop(void) {
301 cdtime_t interval = cf_get_default_interval();
304 wait_until = cdtime() + interval;
313 /* Issue all plugins */
317 if (now >= wait_until) {
318 WARNING("Not sleeping because the next interval is "
319 "%.3f seconds in the past!",
320 CDTIME_T_TO_DOUBLE(now - wait_until));
321 wait_until = now + interval;
325 struct timespec ts_wait = CDTIME_T_TO_TIMESPEC(wait_until - now);
326 wait_until = wait_until + interval;
328 while ((loop == 0) && (nanosleep(&ts_wait, &ts_wait) != 0)) {
329 if (errno != EINTR) {
331 ERROR("nanosleep failed: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
335 } /* while (loop == 0) */
340 static int do_shutdown(void) {
341 return plugin_shutdown_all();
342 } /* int do_shutdown */
345 static int pidfile_create(void) {
347 const char *file = global_option_get("PIDFile");
349 if ((fh = fopen(file, "w")) == NULL) {
351 ERROR("fopen (%s): %s", file, sstrerror(errno, errbuf, sizeof(errbuf)));
355 fprintf(fh, "%i\n", (int)getpid());
359 } /* static int pidfile_create (const char *file) */
361 static int pidfile_remove(void) {
362 const char *file = global_option_get("PIDFile");
367 } /* static int pidfile_remove (const char *file) */
368 #endif /* COLLECT_DAEMON */
371 static int notify_upstart(void) {
372 char const *upstart_job = getenv("UPSTART_JOB");
374 if (upstart_job == NULL)
377 if (strcmp(upstart_job, "collectd") != 0) {
378 WARNING("Environment specifies unexpected UPSTART_JOB=\"%s\", expected "
379 "\"collectd\". Ignoring the variable.",
384 NOTICE("Upstart detected, stopping now to signal readyness.");
386 unsetenv("UPSTART_JOB");
391 static int notify_systemd(void) {
393 const char *notifysocket;
394 struct sockaddr_un su = {0};
396 char buffer[] = "READY=1\n";
398 notifysocket = getenv("NOTIFY_SOCKET");
399 if (notifysocket == NULL)
402 if ((strlen(notifysocket) < 2) ||
403 ((notifysocket[0] != '@') && (notifysocket[0] != '/'))) {
404 ERROR("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be "
409 NOTICE("Systemd detected, trying to signal readyness.");
411 unsetenv("NOTIFY_SOCKET");
413 #if defined(SOCK_CLOEXEC)
414 fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, /* protocol = */ 0);
416 fd = socket(AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
420 ERROR("creating UNIX socket failed: %s",
421 sstrerror(errno, errbuf, sizeof(errbuf)));
425 su.sun_family = AF_UNIX;
426 if (notifysocket[0] != '@') {
427 /* regular UNIX socket */
428 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
429 su_size = sizeof(su);
431 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
432 * start with a null byte. Since null bytes have no special meaning in
433 * that case, we have to set su_size correctly to cover only the bytes
434 * that are part of the address. */
435 sstrncpy(su.sun_path, notifysocket, sizeof(su.sun_path));
437 su_size = sizeof(sa_family_t) + strlen(notifysocket);
438 if (su_size > sizeof(su))
439 su_size = sizeof(su);
442 if (sendto(fd, buffer, strlen(buffer), MSG_NOSIGNAL, (void *)&su,
443 (socklen_t)su_size) < 0) {
445 ERROR("sendto(\"%s\") failed: %s", notifysocket,
446 sstrerror(errno, errbuf, sizeof(errbuf)));
451 unsetenv("NOTIFY_SOCKET");
455 #endif /* KERNEL_LINUX */
457 int main(int argc, char **argv) {
458 const char *configfile = CONFIGFILE;
460 int test_readall = 0;
472 c = getopt(argc, argv, "htTC:"
490 global_option_set("ReadThreads", "-1", 1);
493 #endif /* COLLECT_DAEMON */
497 global_option_set("PIDFile", optarg, 1);
502 #endif /* COLLECT_DAEMON */
517 * Read options from the config file, the environment and the command
518 * line (in that order, with later options overwriting previous ones in
520 * Also, this will automatically load modules.
522 if (cf_read(configfile)) {
523 fprintf(stderr, "Error: Reading the config file failed!\n"
524 "Read the logs for details.\n");
529 * Change directory. We do this _after_ reading the config and loading
530 * modules to relative paths work as expected.
532 if ((basedir = global_option_get("BaseDir")) == NULL) {
534 "Don't have a basedir to use. This should not happen. Ever.");
536 } else if (change_basedir(basedir)) {
537 fprintf(stderr, "Error: Unable to change to directory `%s'.\n", basedir);
542 * Set global variables or, if that failes, exit. We cannot run with
543 * them being uninitialized. If nothing is configured, then defaults
544 * are being used. So this means that the user has actually done
547 if (init_global_variables() != 0)
557 struct sigaction sig_chld_action = {.sa_handler = SIG_IGN};
559 sigaction(SIGCHLD, &sig_chld_action, NULL);
562 * Only daemonize if we're not being supervised
563 * by upstart or systemd (when using Linux).
567 && notify_upstart() == 0 && notify_systemd() == 0
572 if ((pid = fork()) == -1) {
575 fprintf(stderr, "fork: %s", sstrerror(errno, errbuf, sizeof(errbuf)));
577 } else if (pid != 0) {
579 /* printf ("Running (PID %i)\n", pid); */
583 /* Detach from session */
587 if (pidfile_create())
590 /* close standard descriptors */
595 status = open("/dev/null", O_RDWR);
597 ERROR("Error: Could not connect `STDIN' to `/dev/null' (status %d)",
604 ERROR("Error: Could not connect `STDOUT' to `/dev/null' (status %d)",
611 ERROR("Error: Could not connect `STDERR' to `/dev/null', (status %d)",
615 } /* if (daemonize) */
616 #endif /* COLLECT_DAEMON */
618 struct sigaction sig_pipe_action = {.sa_handler = SIG_IGN};
620 sigaction(SIGPIPE, &sig_pipe_action, NULL);
623 * install signal handlers
625 struct sigaction sig_int_action = {.sa_handler = sig_int_handler};
627 if (0 != sigaction(SIGINT, &sig_int_action, NULL)) {
629 ERROR("Error: Failed to install a signal handler for signal INT: %s",
630 sstrerror(errno, errbuf, sizeof(errbuf)));
634 struct sigaction sig_term_action = {.sa_handler = sig_term_handler};
636 if (0 != sigaction(SIGTERM, &sig_term_action, NULL)) {
638 ERROR("Error: Failed to install a signal handler for signal TERM: %s",
639 sstrerror(errno, errbuf, sizeof(errbuf)));
643 struct sigaction sig_usr1_action = {.sa_handler = sig_usr1_handler};
645 if (0 != sigaction(SIGUSR1, &sig_usr1_action, NULL)) {
647 ERROR("Error: Failed to install a signal handler for signal USR1: %s",
648 sstrerror(errno, errbuf, sizeof(errbuf)));
653 * run the actual loops
655 if (do_init() != 0) {
656 ERROR("Error: one or more plugin init callbacks failed.");
661 if (plugin_read_all_once() != 0) {
662 ERROR("Error: one or more plugin read callbacks failed.");
666 INFO("Initialization complete, entering read-loop.");
671 INFO("Exiting normally.");
673 if (do_shutdown() != 0) {
674 ERROR("Error: one or more plugin shutdown callbacks failed.");
681 #endif /* COLLECT_DAEMON */