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_list;
103 str = global_option_get ("Hostname");
106 sstrncpy (hostname_g, str, sizeof (hostname_g));
110 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
112 fprintf (stderr, "`gethostname' failed and no "
113 "hostname was configured.\n");
117 str = global_option_get ("FQDNLookup");
121 struct addrinfo ai_hints = {
122 .ai_flags = AI_CANONNAME
125 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
128 ERROR ("Looking up \"%s\" failed. You have set the "
129 "\"FQDNLookup\" option, but I cannot resolve "
130 "my hostname to a fully qualified domain "
131 "name. Please fix the network "
132 "configuration.", hostname_g);
136 for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
138 if (ai_ptr->ai_canonname == NULL)
141 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
145 freeaddrinfo (ai_list);
147 } /* int init_hostname */
149 static int init_global_variables (void)
153 interval_g = cf_get_default_interval ();
154 assert (interval_g > 0);
155 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
157 str = global_option_get ("Timeout");
160 timeout_g = atoi (str);
163 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
164 "Please check your settings.\n");
167 DEBUG ("timeout_g = %i;", timeout_g);
169 if (init_hostname () != 0)
171 DEBUG ("hostname_g = %s;", hostname_g);
174 } /* int init_global_variables */
176 static int change_basedir (const char *orig_dir)
182 dir = strdup (orig_dir);
186 ERROR ("strdup failed: %s",
187 sstrerror (errno, errbuf, sizeof (errbuf)));
191 dirlen = strlen (dir);
192 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
193 dir[--dirlen] = '\0';
200 status = chdir (dir);
206 else if (errno != ENOENT)
209 ERROR ("change_basedir: chdir (%s): %s", dir,
210 sstrerror (errno, errbuf, sizeof (errbuf)));
215 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
219 ERROR ("change_basedir: mkdir (%s): %s", dir,
220 sstrerror (errno, errbuf, sizeof (errbuf)));
225 status = chdir (dir);
229 ERROR ("change_basedir: chdir (%s): %s", dir,
230 sstrerror (errno, errbuf, sizeof (errbuf)));
237 } /* static int change_basedir (char *dir) */
240 static void update_kstat (void)
244 if ((kc = kstat_open ()) == NULL)
245 ERROR ("Unable to open kstat control structure");
250 kid = kstat_chain_update (kc);
253 INFO ("kstat chain has been updated");
257 ERROR ("kstat chain update failed");
258 /* else: everything works as expected */
262 } /* static void update_kstat (void) */
263 #endif /* HAVE_LIBKSTAT */
266 * Remove all settings but `-f' and `-C'
268 __attribute__((noreturn))
269 static void exit_usage (int status)
271 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
273 "Available options:\n"
275 " -C <file> Configuration file.\n"
276 " Default: "CONFIGFILE"\n"
277 " -t Test config and exit.\n"
278 " -T Test plugin read and exit.\n"
279 " -P <file> PID-file.\n"
280 " Default: "PIDFILE"\n"
282 " -f Don't fork to the background.\n"
284 " -h Display help (this message)\n"
285 "\nBuiltin defaults:\n"
286 " Config file "CONFIGFILE"\n"
287 " PID file "PIDFILE"\n"
288 " Plugin directory "PLUGINDIR"\n"
289 " Data directory "PKGLOCALSTATEDIR"\n"
290 "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
291 "by Florian octo Forster <octo@collectd.org>\n"
292 "for contributions see `AUTHORS'\n");
294 } /* static void exit_usage (int status) */
296 static int do_init (void)
299 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
300 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
302 /* Update the environment, so that libraries that are calling
303 * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
305 setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
315 # if HAVE_LIBSTATGRAB_0_90
320 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
324 if (sg_drop_privileges ())
326 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
331 return plugin_init_all ();
332 } /* int do_init () */
335 static int do_loop (void)
337 cdtime_t interval = cf_get_default_interval ();
340 wait_until = cdtime () + interval;
344 struct timespec ts_wait = { 0, 0 };
351 /* Issue all plugins */
355 if (now >= wait_until)
357 WARNING ("Not sleeping because the next interval is "
358 "%.3f seconds in the past!",
359 CDTIME_T_TO_DOUBLE (now - wait_until));
360 wait_until = now + interval;
364 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
365 wait_until = wait_until + interval;
367 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
372 ERROR ("nanosleep failed: %s",
373 sstrerror (errno, errbuf,
378 } /* while (loop == 0) */
383 static int do_shutdown (void)
385 return plugin_shutdown_all ();
386 } /* int do_shutdown */
389 static int pidfile_create (void)
392 const char *file = global_option_get ("PIDFile");
394 if ((fh = fopen (file, "w")) == NULL)
397 ERROR ("fopen (%s): %s", file,
398 sstrerror (errno, errbuf, sizeof (errbuf)));
402 fprintf (fh, "%i\n", (int) getpid ());
406 } /* static int pidfile_create (const char *file) */
408 static int pidfile_remove (void)
410 const char *file = global_option_get ("PIDFile");
414 return (unlink (file));
415 } /* static int pidfile_remove (const char *file) */
416 #endif /* COLLECT_DAEMON */
419 static int notify_upstart (void)
421 char const *upstart_job = getenv("UPSTART_JOB");
423 if (upstart_job == NULL)
426 if (strcmp(upstart_job, "collectd") != 0)
428 WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
432 NOTICE("Upstart detected, stopping now to signal readyness.");
434 unsetenv("UPSTART_JOB");
439 static int notify_systemd (void)
442 const char *notifysocket;
443 struct sockaddr_un su = { 0 };
445 char buffer[] = "READY=1\n";
447 notifysocket = getenv ("NOTIFY_SOCKET");
448 if (notifysocket == NULL)
451 if ((strlen (notifysocket) < 2)
452 || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
454 ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
457 NOTICE ("Systemd detected, trying to signal readyness.");
459 unsetenv ("NOTIFY_SOCKET");
461 #if defined(SOCK_CLOEXEC)
462 fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
464 fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
468 ERROR ("creating UNIX socket failed: %s",
469 sstrerror (errno, errbuf, sizeof (errbuf)));
473 su.sun_family = AF_UNIX;
474 if (notifysocket[0] != '@')
476 /* regular UNIX socket */
477 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
478 su_size = sizeof (su);
482 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
483 * start with a null byte. Since null bytes have no special meaning in
484 * that case, we have to set su_size correctly to cover only the bytes
485 * that are part of the address. */
486 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
488 su_size = sizeof (sa_family_t) + strlen (notifysocket);
489 if (su_size > sizeof (su))
490 su_size = sizeof (su);
493 if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
496 ERROR ("sendto(\"%s\") failed: %s", notifysocket,
497 sstrerror (errno, errbuf, sizeof (errbuf)));
502 unsetenv ("NOTIFY_SOCKET");
506 #endif /* KERNEL_LINUX */
508 int main (int argc, char **argv)
510 const char *configfile = CONFIGFILE;
512 int test_readall = 0;
525 c = getopt (argc, argv, "htTC:"
544 global_option_set ("ReadThreads", "-1", 1);
547 #endif /* COLLECT_DAEMON */
551 global_option_set ("PIDFile", optarg, 1);
556 #endif /* COLLECT_DAEMON */
571 * Read options from the config file, the environment and the command
572 * line (in that order, with later options overwriting previous ones in
574 * Also, this will automatically load modules.
576 if (cf_read (configfile))
578 fprintf (stderr, "Error: Reading the config file failed!\n"
579 "Read the syslog for details.\n");
584 * Change directory. We do this _after_ reading the config and loading
585 * modules to relative paths work as expected.
587 if ((basedir = global_option_get ("BaseDir")) == NULL)
589 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
592 else if (change_basedir (basedir))
594 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
599 * Set global variables or, if that failes, exit. We cannot run with
600 * them being uninitialized. If nothing is configured, then defaults
601 * are being used. So this means that the user has actually done
604 if (init_global_variables () != 0)
614 struct sigaction sig_chld_action = {
615 .sa_handler = SIG_IGN
618 sigaction (SIGCHLD, &sig_chld_action, NULL);
621 * Only daemonize if we're not being supervised
622 * by upstart or systemd (when using Linux).
626 && notify_upstart() == 0 && notify_systemd() == 0
632 if ((pid = fork ()) == -1)
636 fprintf (stderr, "fork: %s",
637 sstrerror (errno, errbuf,
644 /* printf ("Running (PID %i)\n", pid); */
648 /* Detach from session */
652 if (pidfile_create ())
655 /* close standard descriptors */
660 status = open ("/dev/null", O_RDWR);
663 ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
670 ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
677 ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
680 } /* if (daemonize) */
681 #endif /* COLLECT_DAEMON */
683 struct sigaction sig_pipe_action = {
684 .sa_handler = SIG_IGN
687 sigaction (SIGPIPE, &sig_pipe_action, NULL);
690 * install signal handlers
692 struct sigaction sig_int_action = {
693 .sa_handler = sig_int_handler
696 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
698 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
699 sstrerror (errno, errbuf, sizeof (errbuf)));
703 struct sigaction sig_term_action = {
704 .sa_handler = sig_term_handler
707 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
709 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
710 sstrerror (errno, errbuf, sizeof (errbuf)));
714 struct sigaction sig_usr1_action = {
715 .sa_handler = sig_usr1_handler
718 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
720 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
721 sstrerror (errno, errbuf, sizeof (errbuf)));
726 * run the actual loops
730 ERROR ("Error: one or more plugin init callbacks failed.");
736 if (plugin_read_all_once () != 0)
738 ERROR ("Error: one or more plugin read callbacks failed.");
744 INFO ("Initialization complete, entering read-loop.");
749 INFO ("Exiting normally.");
751 if (do_shutdown () != 0)
753 ERROR ("Error: one or more plugin shutdown callbacks failed.");
760 #endif /* COLLECT_DAEMON */
762 return (exit_status);