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>
32 #include "configfile.h"
34 #include <sys/types.h>
45 # include <statgrab.h>
48 #ifndef COLLECTD_LOCALE
49 # define COLLECTD_LOCALE "C"
55 char hostname_g[DATA_MAX_NAME_LEN];
60 #endif /* HAVE_LIBKSTAT */
64 static void *do_flush (void __attribute__((unused)) *arg)
66 INFO ("Flushing all data.");
67 plugin_flush (/* plugin = */ NULL,
70 INFO ("Finished flushing all data.");
75 static void sig_int_handler (int __attribute__((unused)) signal)
80 static void sig_term_handler (int __attribute__((unused)) signal)
85 static void sig_usr1_handler (int __attribute__((unused)) signal)
90 /* flushing the data might take a while,
91 * so it should be done asynchronously */
92 pthread_attr_init (&attr);
93 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
94 pthread_create (&thread, &attr, do_flush, NULL);
95 pthread_attr_destroy (&attr);
98 static int init_hostname (void)
102 struct addrinfo ai_hints;
103 struct addrinfo *ai_list;
104 struct addrinfo *ai_ptr;
107 str = global_option_get ("Hostname");
110 sstrncpy (hostname_g, str, sizeof (hostname_g));
114 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
116 fprintf (stderr, "`gethostname' failed and no "
117 "hostname was configured.\n");
121 str = global_option_get ("FQDNLookup");
125 memset (&ai_hints, '\0', sizeof (ai_hints));
126 ai_hints.ai_flags = AI_CANONNAME;
128 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
131 ERROR ("Looking up \"%s\" failed. You have set the "
132 "\"FQDNLookup\" option, but I cannot resolve "
133 "my hostname to a fully qualified domain "
134 "name. Please fix the network "
135 "configuration.", hostname_g);
139 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
141 if (ai_ptr->ai_canonname == NULL)
144 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
148 freeaddrinfo (ai_list);
150 } /* int init_hostname */
152 static int init_global_variables (void)
156 interval_g = cf_get_default_interval ();
157 assert (interval_g > 0);
158 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
160 str = global_option_get ("Timeout");
163 timeout_g = atoi (str);
166 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
167 "Please check your settings.\n");
170 DEBUG ("timeout_g = %i;", timeout_g);
172 if (init_hostname () != 0)
174 DEBUG ("hostname_g = %s;", hostname_g);
177 } /* int init_global_variables */
179 static int change_basedir (const char *orig_dir)
185 dir = strdup (orig_dir);
189 ERROR ("strdup failed: %s",
190 sstrerror (errno, errbuf, sizeof (errbuf)));
194 dirlen = strlen (dir);
195 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
196 dir[--dirlen] = '\0';
203 status = chdir (dir);
209 else if (errno != ENOENT)
212 ERROR ("change_basedir: chdir (%s): %s", dir,
213 sstrerror (errno, errbuf, sizeof (errbuf)));
218 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
222 ERROR ("change_basedir: mkdir (%s): %s", dir,
223 sstrerror (errno, errbuf, sizeof (errbuf)));
228 status = chdir (dir);
232 ERROR ("change_basedir: chdir (%s): %s", dir,
233 sstrerror (errno, errbuf, sizeof (errbuf)));
240 } /* static int change_basedir (char *dir) */
243 static void update_kstat (void)
247 if ((kc = kstat_open ()) == NULL)
248 ERROR ("Unable to open kstat control structure");
253 kid = kstat_chain_update (kc);
256 INFO ("kstat chain has been updated");
260 ERROR ("kstat chain update failed");
261 /* else: everything works as expected */
265 } /* static void update_kstat (void) */
266 #endif /* HAVE_LIBKSTAT */
269 * Remove all settings but `-f' and `-C'
271 __attribute__((noreturn))
272 static void exit_usage (int status)
274 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
276 "Available options:\n"
278 " -C <file> Configuration file.\n"
279 " Default: "CONFIGFILE"\n"
280 " -t Test config and exit.\n"
281 " -T Test plugin read and exit.\n"
282 " -P <file> PID-file.\n"
283 " Default: "PIDFILE"\n"
285 " -f Don't fork to the background.\n"
287 " -h Display help (this message)\n"
288 "\nBuiltin defaults:\n"
289 " Config file "CONFIGFILE"\n"
290 " PID file "PIDFILE"\n"
291 " Plugin directory "PLUGINDIR"\n"
292 " Data directory "PKGLOCALSTATEDIR"\n"
293 "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
294 "by Florian octo Forster <octo@collectd.org>\n"
295 "for contributions see `AUTHORS'\n");
297 } /* static void exit_usage (int status) */
299 static int do_init (void)
302 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
303 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
305 /* Update the environment, so that libraries that are calling
306 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
308 setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
318 # if HAVE_LIBSTATGRAB_0_90
323 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
327 if (sg_drop_privileges ())
329 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
334 return plugin_init_all ();
335 } /* int do_init () */
338 static int do_loop (void)
340 cdtime_t interval = cf_get_default_interval ();
343 wait_until = cdtime () + interval;
347 struct timespec ts_wait = { 0, 0 };
354 /* Issue all plugins */
358 if (now >= wait_until)
360 WARNING ("Not sleeping because the next interval is "
361 "%.3f seconds in the past!",
362 CDTIME_T_TO_DOUBLE (now - wait_until));
363 wait_until = now + interval;
367 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
368 wait_until = wait_until + interval;
370 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
375 ERROR ("nanosleep failed: %s",
376 sstrerror (errno, errbuf,
381 } /* while (loop == 0) */
386 static int do_shutdown (void)
388 return plugin_shutdown_all ();
389 } /* int do_shutdown */
392 static int pidfile_create (void)
395 const char *file = global_option_get ("PIDFile");
397 if ((fh = fopen (file, "w")) == NULL)
400 ERROR ("fopen (%s): %s", file,
401 sstrerror (errno, errbuf, sizeof (errbuf)));
405 fprintf (fh, "%i\n", (int) getpid ());
409 } /* static int pidfile_create (const char *file) */
411 static int pidfile_remove (void)
413 const char *file = global_option_get ("PIDFile");
417 return (unlink (file));
418 } /* static int pidfile_remove (const char *file) */
419 #endif /* COLLECT_DAEMON */
422 static int notify_upstart (void)
424 char const *upstart_job = getenv("UPSTART_JOB");
426 if (upstart_job == NULL)
429 if (strcmp(upstart_job, "collectd") != 0)
431 WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
435 NOTICE("Upstart detected, stopping now to signal readyness.");
437 unsetenv("UPSTART_JOB");
442 static int notify_systemd (void)
445 const char *notifysocket;
446 struct sockaddr_un su;
448 char buffer[] = "READY=1\n";
450 notifysocket = getenv ("NOTIFY_SOCKET");
451 if (notifysocket == NULL)
454 if ((strlen (notifysocket) < 2)
455 || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
457 ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
460 NOTICE ("Systemd detected, trying to signal readyness.");
462 unsetenv ("NOTIFY_SOCKET");
464 #if defined(SOCK_CLOEXEC)
465 fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
467 fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
471 ERROR ("creating UNIX socket failed: %s",
472 sstrerror (errno, errbuf, sizeof (errbuf)));
476 memset (&su, 0, sizeof (su));
477 su.sun_family = AF_UNIX;
478 if (notifysocket[0] != '@')
480 /* regular UNIX socket */
481 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
482 su_size = sizeof (su);
486 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
487 * start with a null byte. Since null bytes have no special meaning in
488 * that case, we have to set su_size correctly to cover only the bytes
489 * that are part of the address. */
490 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
492 su_size = sizeof (sa_family_t) + strlen (notifysocket);
493 if (su_size > sizeof (su))
494 su_size = sizeof (su);
497 if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
500 ERROR ("sendto(\"%s\") failed: %s", notifysocket,
501 sstrerror (errno, errbuf, sizeof (errbuf)));
506 unsetenv ("NOTIFY_SOCKET");
510 #endif /* KERNEL_LINUX */
512 int main (int argc, char **argv)
514 struct sigaction sig_int_action;
515 struct sigaction sig_term_action;
516 struct sigaction sig_usr1_action;
517 struct sigaction sig_pipe_action;
518 const char *configfile = CONFIGFILE;
520 int test_readall = 0;
523 struct sigaction sig_chld_action;
534 c = getopt (argc, argv, "htTC:"
553 global_option_set ("ReadThreads", "-1", 1);
556 #endif /* COLLECT_DAEMON */
560 global_option_set ("PIDFile", optarg, 1);
565 #endif /* COLLECT_DAEMON */
580 * Read options from the config file, the environment and the command
581 * line (in that order, with later options overwriting previous ones in
583 * Also, this will automatically load modules.
585 if (cf_read (configfile))
587 fprintf (stderr, "Error: Reading the config file failed!\n"
588 "Read the syslog for details.\n");
593 * Change directory. We do this _after_ reading the config and loading
594 * modules to relative paths work as expected.
596 if ((basedir = global_option_get ("BaseDir")) == NULL)
598 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
601 else if (change_basedir (basedir))
603 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
608 * Set global variables or, if that failes, exit. We cannot run with
609 * them being uninitialized. If nothing is configured, then defaults
610 * are being used. So this means that the user has actually done
613 if (init_global_variables () != 0)
623 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
624 sig_chld_action.sa_handler = SIG_IGN;
625 sigaction (SIGCHLD, &sig_chld_action, NULL);
628 * Only daemonize if we're not being supervised
629 * by upstart or systemd (when using Linux).
633 && notify_upstart() == 0 && notify_systemd() == 0
639 if ((pid = fork ()) == -1)
643 fprintf (stderr, "fork: %s",
644 sstrerror (errno, errbuf,
651 /* printf ("Running (PID %i)\n", pid); */
655 /* Detach from session */
659 if (pidfile_create ())
662 /* close standard descriptors */
667 status = open ("/dev/null", O_RDWR);
670 ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
677 ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
684 ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
687 } /* if (daemonize) */
688 #endif /* COLLECT_DAEMON */
690 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
691 sig_pipe_action.sa_handler = SIG_IGN;
692 sigaction (SIGPIPE, &sig_pipe_action, NULL);
695 * install signal handlers
697 memset (&sig_int_action, '\0', sizeof (sig_int_action));
698 sig_int_action.sa_handler = sig_int_handler;
699 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
701 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
702 sstrerror (errno, errbuf, sizeof (errbuf)));
706 memset (&sig_term_action, '\0', sizeof (sig_term_action));
707 sig_term_action.sa_handler = sig_term_handler;
708 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
710 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
711 sstrerror (errno, errbuf, sizeof (errbuf)));
715 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
716 sig_usr1_action.sa_handler = sig_usr1_handler;
717 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
719 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
720 sstrerror (errno, errbuf, sizeof (errbuf)));
725 * run the actual loops
729 ERROR ("Error: one or more plugin init callbacks failed.");
735 if (plugin_read_all_once () != 0)
737 ERROR ("Error: one or more plugin read callbacks failed.");
743 INFO ("Initialization complete, entering read-loop.");
748 INFO ("Exiting normally.");
750 if (do_shutdown () != 0)
752 ERROR ("Error: one or more plugin shutdown callbacks failed.");
759 #endif /* COLLECT_DAEMON */
761 return (exit_status);