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>
43 # include <statgrab.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)
64 INFO ("Flushing all data.");
65 plugin_flush (/* plugin = */ NULL,
68 INFO ("Finished flushing all data.");
73 static void sig_int_handler (int __attribute__((unused)) signal)
78 static void sig_term_handler (int __attribute__((unused)) signal)
83 static void sig_usr1_handler (int __attribute__((unused)) signal)
88 /* flushing the data might take a while,
89 * so it should be done asynchronously */
90 pthread_attr_init (&attr);
91 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
92 pthread_create (&thread, &attr, do_flush, NULL);
93 pthread_attr_destroy (&attr);
96 static int init_hostname (void)
100 struct addrinfo ai_hints;
101 struct addrinfo *ai_list;
102 struct addrinfo *ai_ptr;
105 str = global_option_get ("Hostname");
108 sstrncpy (hostname_g, str, sizeof (hostname_g));
112 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
114 fprintf (stderr, "`gethostname' failed and no "
115 "hostname was configured.\n");
119 str = global_option_get ("FQDNLookup");
123 memset (&ai_hints, '\0', sizeof (ai_hints));
124 ai_hints.ai_flags = AI_CANONNAME;
126 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
129 ERROR ("Looking up \"%s\" failed. You have set the "
130 "\"FQDNLookup\" option, but I cannot resolve "
131 "my hostname to a fully qualified domain "
132 "name. Please fix the network "
133 "configuration.", hostname_g);
137 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
139 if (ai_ptr->ai_canonname == NULL)
142 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
146 freeaddrinfo (ai_list);
148 } /* int init_hostname */
150 static int init_global_variables (void)
154 interval_g = cf_get_default_interval ();
155 assert (interval_g > 0);
156 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
158 str = global_option_get ("Timeout");
161 timeout_g = atoi (str);
164 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
165 "Please check your settings.\n");
168 DEBUG ("timeout_g = %i;", timeout_g);
170 if (init_hostname () != 0)
172 DEBUG ("hostname_g = %s;", hostname_g);
175 } /* int init_global_variables */
177 static int change_basedir (const char *orig_dir)
183 dir = strdup (orig_dir);
187 ERROR ("strdup failed: %s",
188 sstrerror (errno, errbuf, sizeof (errbuf)));
192 dirlen = strlen (dir);
193 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
194 dir[--dirlen] = '\0';
201 status = chdir (dir);
207 else if (errno != ENOENT)
210 ERROR ("change_basedir: chdir (%s): %s", dir,
211 sstrerror (errno, errbuf, sizeof (errbuf)));
216 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
220 ERROR ("change_basedir: mkdir (%s): %s", dir,
221 sstrerror (errno, errbuf, sizeof (errbuf)));
226 status = chdir (dir);
230 ERROR ("change_basedir: chdir (%s): %s", dir,
231 sstrerror (errno, errbuf, sizeof (errbuf)));
238 } /* static int change_basedir (char *dir) */
241 static void update_kstat (void)
245 if ((kc = kstat_open ()) == NULL)
246 ERROR ("Unable to open kstat control structure");
251 kid = kstat_chain_update (kc);
254 INFO ("kstat chain has been updated");
258 ERROR ("kstat chain update failed");
259 /* else: everything works as expected */
263 } /* static void update_kstat (void) */
264 #endif /* HAVE_LIBKSTAT */
267 * Remove all settings but `-f' and `-C'
269 __attribute__((noreturn))
270 static void exit_usage (int status)
272 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
274 "Available options:\n"
276 " -C <file> Configuration file.\n"
277 " Default: "CONFIGFILE"\n"
278 " -t Test config and exit.\n"
279 " -T Test plugin read and exit.\n"
280 " -P <file> PID-file.\n"
281 " Default: "PIDFILE"\n"
283 " -f Don't fork to the background.\n"
285 " -h Display help (this message)\n"
286 "\nBuiltin defaults:\n"
287 " Config file "CONFIGFILE"\n"
288 " PID file "PIDFILE"\n"
289 " Plugin directory "PLUGINDIR"\n"
290 " Data directory "PKGLOCALSTATEDIR"\n"
291 "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
292 "by Florian octo Forster <octo@collectd.org>\n"
293 "for contributions see `AUTHORS'\n");
295 } /* static void exit_usage (int status) */
297 static int do_init (void)
300 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
301 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
303 /* Update the environment, so that libraries that are calling
304 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
306 setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
316 # if HAVE_LIBSTATGRAB_0_90
321 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
325 if (sg_drop_privileges ())
327 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
332 return plugin_init_all ();
333 } /* int do_init () */
336 static int do_loop (void)
338 cdtime_t interval = cf_get_default_interval ();
341 wait_until = cdtime () + interval;
345 struct timespec ts_wait = { 0, 0 };
352 /* Issue all plugins */
356 if (now >= wait_until)
358 WARNING ("Not sleeping because the next interval is "
359 "%.3f seconds in the past!",
360 CDTIME_T_TO_DOUBLE (now - wait_until));
361 wait_until = now + interval;
365 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
366 wait_until = wait_until + interval;
368 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
373 ERROR ("nanosleep failed: %s",
374 sstrerror (errno, errbuf,
379 } /* while (loop == 0) */
384 static int do_shutdown (void)
386 return plugin_shutdown_all ();
387 } /* int do_shutdown */
390 static int pidfile_create (void)
393 const char *file = global_option_get ("PIDFile");
395 if ((fh = fopen (file, "w")) == NULL)
398 ERROR ("fopen (%s): %s", file,
399 sstrerror (errno, errbuf, sizeof (errbuf)));
403 fprintf (fh, "%i\n", (int) getpid ());
407 } /* static int pidfile_create (const char *file) */
409 static int pidfile_remove (void)
411 const char *file = global_option_get ("PIDFile");
415 return (unlink (file));
416 } /* static int pidfile_remove (const char *file) */
417 #endif /* COLLECT_DAEMON */
420 static int notify_upstart (void)
422 char const *upstart_job = getenv("UPSTART_JOB");
424 if (upstart_job == NULL)
427 if (strcmp(upstart_job, "collectd") != 0)
429 WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
433 NOTICE("Upstart detected, stopping now to signal readyness.");
435 unsetenv("UPSTART_JOB");
440 static int notify_systemd (void)
443 const char *notifysocket;
444 struct sockaddr_un su;
446 char buffer[] = "READY=1\n";
448 notifysocket = getenv ("NOTIFY_SOCKET");
449 if (notifysocket == NULL)
452 if ((strlen (notifysocket) < 2)
453 || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
455 ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
458 NOTICE ("Systemd detected, trying to signal readyness.");
460 unsetenv ("NOTIFY_SOCKET");
462 #if defined(SOCK_CLOEXEC)
463 fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
465 fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
469 ERROR ("creating UNIX socket failed: %s",
470 sstrerror (errno, errbuf, sizeof (errbuf)));
474 memset (&su, 0, sizeof (su));
475 su.sun_family = AF_UNIX;
476 if (notifysocket[0] != '@')
478 /* regular UNIX socket */
479 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
480 su_size = sizeof (su);
484 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
485 * start with a null byte. Since null bytes have no special meaning in
486 * that case, we have to set su_size correctly to cover only the bytes
487 * that are part of the address. */
488 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
490 su_size = sizeof (sa_family_t) + strlen (notifysocket);
491 if (su_size > sizeof (su))
492 su_size = sizeof (su);
495 if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
498 ERROR ("sendto(\"%s\") failed: %s", notifysocket,
499 sstrerror (errno, errbuf, sizeof (errbuf)));
504 unsetenv ("NOTIFY_SOCKET");
508 #endif /* KERNEL_LINUX */
510 int main (int argc, char **argv)
512 struct sigaction sig_int_action;
513 struct sigaction sig_term_action;
514 struct sigaction sig_usr1_action;
515 struct sigaction sig_pipe_action;
516 const char *configfile = CONFIGFILE;
518 int test_readall = 0;
521 struct sigaction sig_chld_action;
532 c = getopt (argc, argv, "htTC:"
551 global_option_set ("ReadThreads", "-1", 1);
554 #endif /* COLLECT_DAEMON */
558 global_option_set ("PIDFile", optarg, 1);
563 #endif /* COLLECT_DAEMON */
578 * Read options from the config file, the environment and the command
579 * line (in that order, with later options overwriting previous ones in
581 * Also, this will automatically load modules.
583 if (cf_read (configfile))
585 fprintf (stderr, "Error: Reading the config file failed!\n"
586 "Read the syslog for details.\n");
591 * Change directory. We do this _after_ reading the config and loading
592 * modules to relative paths work as expected.
594 if ((basedir = global_option_get ("BaseDir")) == NULL)
596 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
599 else if (change_basedir (basedir))
601 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
606 * Set global variables or, if that failes, exit. We cannot run with
607 * them being uninitialized. If nothing is configured, then defaults
608 * are being used. So this means that the user has actually done
611 if (init_global_variables () != 0)
621 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
622 sig_chld_action.sa_handler = SIG_IGN;
623 sigaction (SIGCHLD, &sig_chld_action, NULL);
626 * Only daemonize if we're not being supervised
627 * by upstart or systemd (when using Linux).
631 && notify_upstart() == 0 && notify_systemd() == 0
637 if ((pid = fork ()) == -1)
641 fprintf (stderr, "fork: %s",
642 sstrerror (errno, errbuf,
649 /* printf ("Running (PID %i)\n", pid); */
653 /* Detach from session */
657 if (pidfile_create ())
660 /* close standard descriptors */
665 status = open ("/dev/null", O_RDWR);
668 ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
675 ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
682 ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
685 } /* if (daemonize) */
686 #endif /* COLLECT_DAEMON */
688 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
689 sig_pipe_action.sa_handler = SIG_IGN;
690 sigaction (SIGPIPE, &sig_pipe_action, NULL);
693 * install signal handlers
695 memset (&sig_int_action, '\0', sizeof (sig_int_action));
696 sig_int_action.sa_handler = sig_int_handler;
697 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
699 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
700 sstrerror (errno, errbuf, sizeof (errbuf)));
704 memset (&sig_term_action, '\0', sizeof (sig_term_action));
705 sig_term_action.sa_handler = sig_term_handler;
706 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
708 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
709 sstrerror (errno, errbuf, sizeof (errbuf)));
713 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
714 sig_usr1_action.sa_handler = sig_usr1_handler;
715 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
717 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
718 sstrerror (errno, errbuf, sizeof (errbuf)));
723 * run the actual loops
727 ERROR ("Error: one or more plugin init callbacks failed.");
733 if (plugin_read_all_once () != 0)
735 ERROR ("Error: one or more plugin read callbacks failed.");
741 INFO ("Initialization complete, entering read-loop.");
746 INFO ("Exiting normally.");
748 if (do_shutdown () != 0)
750 ERROR ("Error: one or more plugin shutdown callbacks failed.");
757 #endif /* COLLECT_DAEMON */
759 return (exit_status);