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];
57 int pidfile_from_cli = 0;
61 #endif /* HAVE_LIBKSTAT */
65 static void *do_flush (void __attribute__((unused)) *arg)
67 INFO ("Flushing all data.");
68 plugin_flush (/* plugin = */ NULL,
71 INFO ("Finished flushing all data.");
76 static void sig_int_handler (int __attribute__((unused)) signal)
81 static void sig_term_handler (int __attribute__((unused)) signal)
86 static void sig_usr1_handler (int __attribute__((unused)) signal)
91 /* flushing the data might take a while,
92 * so it should be done asynchronously */
93 pthread_attr_init (&attr);
94 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
95 pthread_create (&thread, &attr, do_flush, NULL);
96 pthread_attr_destroy (&attr);
99 static int init_hostname (void)
103 struct addrinfo ai_hints;
104 struct addrinfo *ai_list;
105 struct addrinfo *ai_ptr;
108 str = global_option_get ("Hostname");
111 sstrncpy (hostname_g, str, sizeof (hostname_g));
115 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
117 fprintf (stderr, "`gethostname' failed and no "
118 "hostname was configured.\n");
122 str = global_option_get ("FQDNLookup");
126 memset (&ai_hints, '\0', sizeof (ai_hints));
127 ai_hints.ai_flags = AI_CANONNAME;
129 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
132 ERROR ("Looking up \"%s\" failed. You have set the "
133 "\"FQDNLookup\" option, but I cannot resolve "
134 "my hostname to a fully qualified domain "
135 "name. Please fix the network "
136 "configuration.", hostname_g);
140 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
142 if (ai_ptr->ai_canonname == NULL)
145 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
149 freeaddrinfo (ai_list);
151 } /* int init_hostname */
153 static int init_global_variables (void)
157 interval_g = cf_get_default_interval ();
158 assert (interval_g > 0);
159 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
161 str = global_option_get ("Timeout");
164 timeout_g = atoi (str);
167 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
168 "Please check your settings.\n");
171 DEBUG ("timeout_g = %i;", timeout_g);
173 if (init_hostname () != 0)
175 DEBUG ("hostname_g = %s;", hostname_g);
178 } /* int init_global_variables */
180 static int change_basedir (const char *orig_dir)
186 dir = strdup (orig_dir);
190 ERROR ("strdup failed: %s",
191 sstrerror (errno, errbuf, sizeof (errbuf)));
195 dirlen = strlen (dir);
196 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
197 dir[--dirlen] = '\0';
204 status = chdir (dir);
210 else if (errno != ENOENT)
213 ERROR ("change_basedir: chdir (%s): %s", dir,
214 sstrerror (errno, errbuf, sizeof (errbuf)));
219 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
223 ERROR ("change_basedir: mkdir (%s): %s", dir,
224 sstrerror (errno, errbuf, sizeof (errbuf)));
229 status = chdir (dir);
233 ERROR ("change_basedir: chdir (%s): %s", dir,
234 sstrerror (errno, errbuf, sizeof (errbuf)));
241 } /* static int change_basedir (char *dir) */
244 static void update_kstat (void)
248 if ((kc = kstat_open ()) == NULL)
249 ERROR ("Unable to open kstat control structure");
254 kid = kstat_chain_update (kc);
257 INFO ("kstat chain has been updated");
261 ERROR ("kstat chain update failed");
262 /* else: everything works as expected */
266 } /* static void update_kstat (void) */
267 #endif /* HAVE_LIBKSTAT */
270 * Remove all settings but `-f' and `-C'
272 __attribute__((noreturn))
273 static void exit_usage (int status)
275 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
277 "Available options:\n"
279 " -C <file> Configuration file.\n"
280 " Default: "CONFIGFILE"\n"
281 " -t Test config and exit.\n"
282 " -T Test plugin read and exit.\n"
283 " -P <file> PID-file.\n"
284 " Default: "PIDFILE"\n"
286 " -f Don't fork to the background.\n"
288 " -h Display help (this message)\n"
289 "\nBuiltin defaults:\n"
290 " Config file "CONFIGFILE"\n"
291 " PID file "PIDFILE"\n"
292 " Plugin directory "PLUGINDIR"\n"
293 " Data directory "PKGLOCALSTATEDIR"\n"
294 "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
295 "by Florian octo Forster <octo@collectd.org>\n"
296 "for contributions see `AUTHORS'\n");
298 } /* static void exit_usage (int status) */
300 static int do_init (void)
303 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
304 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
306 /* Update the environment, so that libraries that are calling
307 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
309 setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
319 # if HAVE_LIBSTATGRAB_0_90
324 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
328 if (sg_drop_privileges ())
330 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
335 return plugin_init_all ();
336 } /* int do_init () */
339 static int do_loop (void)
341 cdtime_t interval = cf_get_default_interval ();
344 wait_until = cdtime () + interval;
348 struct timespec ts_wait = { 0, 0 };
355 /* Issue all plugins */
359 if (now >= wait_until)
361 WARNING ("Not sleeping because the next interval is "
362 "%.3f seconds in the past!",
363 CDTIME_T_TO_DOUBLE (now - wait_until));
364 wait_until = now + interval;
368 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
369 wait_until = wait_until + interval;
371 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
376 ERROR ("nanosleep failed: %s",
377 sstrerror (errno, errbuf,
382 } /* while (loop == 0) */
387 static int do_shutdown (void)
389 return plugin_shutdown_all ();
390 } /* int do_shutdown */
393 static int pidfile_create (void)
396 const char *file = global_option_get ("PIDFile");
398 if ((fh = fopen (file, "w")) == NULL)
401 ERROR ("fopen (%s): %s", file,
402 sstrerror (errno, errbuf, sizeof (errbuf)));
406 fprintf (fh, "%i\n", (int) getpid ());
410 } /* static int pidfile_create (const char *file) */
412 static int pidfile_remove (void)
414 const char *file = global_option_get ("PIDFile");
418 return (unlink (file));
419 } /* static int pidfile_remove (const char *file) */
420 #endif /* COLLECT_DAEMON */
423 static int notify_upstart (void)
425 char const *upstart_job = getenv("UPSTART_JOB");
427 if (upstart_job == NULL)
430 if (strcmp(upstart_job, "collectd") != 0)
432 WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
436 NOTICE("Upstart detected, stopping now to signal readyness.");
438 unsetenv("UPSTART_JOB");
443 static int notify_systemd (void)
446 const char *notifysocket;
447 struct sockaddr_un su;
449 char buffer[] = "READY=1\n";
451 notifysocket = getenv ("NOTIFY_SOCKET");
452 if (notifysocket == NULL)
455 if ((strlen (notifysocket) < 2)
456 || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
458 ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
461 NOTICE ("Systemd detected, trying to signal readyness.");
463 unsetenv ("NOTIFY_SOCKET");
465 #if defined(SOCK_CLOEXEC)
466 fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
468 fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
472 ERROR ("creating UNIX socket failed: %s",
473 sstrerror (errno, errbuf, sizeof (errbuf)));
477 memset (&su, 0, sizeof (su));
478 su.sun_family = AF_UNIX;
479 if (notifysocket[0] != '@')
481 /* regular UNIX socket */
482 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
483 su_size = sizeof (su);
487 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
488 * start with a null byte. Since null bytes have no special meaning in
489 * that case, we have to set su_size correctly to cover only the bytes
490 * that are part of the address. */
491 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
493 su_size = sizeof (sa_family_t) + strlen (notifysocket);
494 if (su_size > sizeof (su))
495 su_size = sizeof (su);
498 if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
501 ERROR ("sendto(\"%s\") failed: %s", notifysocket,
502 sstrerror (errno, errbuf, sizeof (errbuf)));
507 unsetenv ("NOTIFY_SOCKET");
511 #endif /* KERNEL_LINUX */
513 int main (int argc, char **argv)
515 struct sigaction sig_int_action;
516 struct sigaction sig_term_action;
517 struct sigaction sig_usr1_action;
518 struct sigaction sig_pipe_action;
519 const char *configfile = CONFIGFILE;
521 int test_readall = 0;
524 struct sigaction sig_chld_action;
535 c = getopt (argc, argv, "htTC:"
554 global_option_set ("ReadThreads", "-1");
557 #endif /* COLLECT_DAEMON */
561 global_option_set ("PIDFile", optarg);
562 pidfile_from_cli = 1;
567 #endif /* COLLECT_DAEMON */
582 * Read options from the config file, the environment and the command
583 * line (in that order, with later options overwriting previous ones in
585 * Also, this will automatically load modules.
587 if (cf_read (configfile))
589 fprintf (stderr, "Error: Reading the config file failed!\n"
590 "Read the syslog for details.\n");
595 * Change directory. We do this _after_ reading the config and loading
596 * modules to relative paths work as expected.
598 if ((basedir = global_option_get ("BaseDir")) == NULL)
600 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
603 else if (change_basedir (basedir))
605 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
610 * Set global variables or, if that failes, exit. We cannot run with
611 * them being uninitialized. If nothing is configured, then defaults
612 * are being used. So this means that the user has actually done
615 if (init_global_variables () != 0)
625 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
626 sig_chld_action.sa_handler = SIG_IGN;
627 sigaction (SIGCHLD, &sig_chld_action, NULL);
630 * Only daemonize if we're not being supervised
631 * by upstart or systemd (when using Linux).
635 && notify_upstart() == 0 && notify_systemd() == 0
641 if ((pid = fork ()) == -1)
645 fprintf (stderr, "fork: %s",
646 sstrerror (errno, errbuf,
653 /* printf ("Running (PID %i)\n", pid); */
657 /* Detach from session */
661 if (pidfile_create ())
664 /* close standard descriptors */
669 status = open ("/dev/null", O_RDWR);
672 ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
679 ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
686 ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
689 } /* if (daemonize) */
690 #endif /* COLLECT_DAEMON */
692 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
693 sig_pipe_action.sa_handler = SIG_IGN;
694 sigaction (SIGPIPE, &sig_pipe_action, NULL);
697 * install signal handlers
699 memset (&sig_int_action, '\0', sizeof (sig_int_action));
700 sig_int_action.sa_handler = sig_int_handler;
701 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
703 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
704 sstrerror (errno, errbuf, sizeof (errbuf)));
708 memset (&sig_term_action, '\0', sizeof (sig_term_action));
709 sig_term_action.sa_handler = sig_term_handler;
710 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
712 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
713 sstrerror (errno, errbuf, sizeof (errbuf)));
717 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
718 sig_usr1_action.sa_handler = sig_usr1_handler;
719 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
721 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
722 sstrerror (errno, errbuf, sizeof (errbuf)));
727 * run the actual loops
731 ERROR ("Error: one or more plugin init callbacks failed.");
737 if (plugin_read_all_once () != 0)
739 ERROR ("Error: one or more plugin read callbacks failed.");
745 INFO ("Initialization complete, entering read-loop.");
750 INFO ("Exiting normally.");
752 if (do_shutdown () != 0)
754 ERROR ("Error: one or more plugin shutdown callbacks failed.");
761 #endif /* COLLECT_DAEMON */
763 return (exit_status);