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>
35 #include <sys/socket.h>
46 # include <statgrab.h>
49 #ifndef COLLECTD_LOCALE
50 # define COLLECTD_LOCALE "C"
56 char hostname_g[DATA_MAX_NAME_LEN];
58 int pidfile_from_cli = 0;
62 #endif /* HAVE_LIBKSTAT */
66 static void *do_flush (void __attribute__((unused)) *arg)
68 INFO ("Flushing all data.");
69 plugin_flush (/* plugin = */ NULL,
72 INFO ("Finished flushing all data.");
77 static void sig_int_handler (int __attribute__((unused)) signal)
82 static void sig_term_handler (int __attribute__((unused)) signal)
87 static void sig_usr1_handler (int __attribute__((unused)) signal)
92 /* flushing the data might take a while,
93 * so it should be done asynchronously */
94 pthread_attr_init (&attr);
95 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
96 pthread_create (&thread, &attr, do_flush, NULL);
97 pthread_attr_destroy (&attr);
100 static int init_hostname (void)
104 struct addrinfo ai_hints;
105 struct addrinfo *ai_list;
106 struct addrinfo *ai_ptr;
109 str = global_option_get ("Hostname");
112 sstrncpy (hostname_g, str, sizeof (hostname_g));
116 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
118 fprintf (stderr, "`gethostname' failed and no "
119 "hostname was configured.\n");
123 str = global_option_get ("FQDNLookup");
127 memset (&ai_hints, '\0', sizeof (ai_hints));
128 ai_hints.ai_flags = AI_CANONNAME;
130 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
133 ERROR ("Looking up \"%s\" failed. You have set the "
134 "\"FQDNLookup\" option, but I cannot resolve "
135 "my hostname to a fully qualified domain "
136 "name. Please fix the network "
137 "configuration.", hostname_g);
141 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
143 if (ai_ptr->ai_canonname == NULL)
146 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
150 freeaddrinfo (ai_list);
152 } /* int init_hostname */
154 static int init_global_variables (void)
158 interval_g = cf_get_default_interval ();
159 assert (interval_g > 0);
160 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
162 str = global_option_get ("Timeout");
165 timeout_g = atoi (str);
168 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
169 "Please check your settings.\n");
172 DEBUG ("timeout_g = %i;", timeout_g);
174 if (init_hostname () != 0)
176 DEBUG ("hostname_g = %s;", hostname_g);
179 } /* int init_global_variables */
181 static int change_basedir (const char *orig_dir)
187 dir = strdup (orig_dir);
191 ERROR ("strdup failed: %s",
192 sstrerror (errno, errbuf, sizeof (errbuf)));
196 dirlen = strlen (dir);
197 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
198 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 static void exit_usage (int status)
273 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
275 "Available options:\n"
277 " -C <file> Configuration file.\n"
278 " Default: "CONFIGFILE"\n"
279 " -t Test config and exit.\n"
280 " -T Test plugin read and exit.\n"
281 " -P <file> PID-file.\n"
282 " Default: "PIDFILE"\n"
284 " -f Don't fork to the background.\n"
286 " -h Display help (this message)\n"
287 "\nBuiltin defaults:\n"
288 " Config file "CONFIGFILE"\n"
289 " PID file "PIDFILE"\n"
290 " Plugin directory "PLUGINDIR"\n"
291 " Data directory "PKGLOCALSTATEDIR"\n"
292 "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
293 "by Florian octo Forster <octo@collectd.org>\n"
294 "for contributions see `AUTHORS'\n");
296 } /* static void exit_usage (int status) */
298 static int do_init (void)
301 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
302 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
312 # if HAVE_LIBSTATGRAB_0_90
317 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
321 if (sg_drop_privileges ())
323 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
331 } /* int do_init () */
334 static int do_loop (void)
336 cdtime_t interval = cf_get_default_interval ();
339 wait_until = cdtime () + interval;
343 struct timespec ts_wait = { 0, 0 };
350 /* Issue all plugins */
354 if (now >= wait_until)
356 WARNING ("Not sleeping because the next interval is "
357 "%.3f seconds in the past!",
358 CDTIME_T_TO_DOUBLE (now - wait_until));
359 wait_until = now + interval;
363 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
364 wait_until = wait_until + interval;
366 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
371 ERROR ("nanosleep failed: %s",
372 sstrerror (errno, errbuf,
377 } /* while (loop == 0) */
382 static int do_shutdown (void)
384 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 int notify_upstart (void)
421 const char *upstart_job = getenv("UPSTART_JOB");
423 if (upstart_job == NULL)
426 if (strcmp(upstart_job, "collectd") != 0)
429 WARNING ("supervised by upstart, will stop to signal readyness");
431 unsetenv("UPSTART_JOB");
436 int notify_systemd (void)
439 const char *notifysocket = getenv("NOTIFY_SOCKET");
440 struct sockaddr_un su;
444 if (notifysocket == NULL)
447 if ((strchr("@/", notifysocket[0])) == NULL ||
448 strlen(notifysocket) < 2)
451 WARNING ("supervised by systemd, will signal readyness");
452 if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) {
453 WARNING ("cannot contact systemd socket %s", notifysocket);
457 bzero(&su, sizeof(su));
458 su.sun_family = AF_UNIX;
459 sstrncpy (su.sun_path, notifysocket, sizeof(su.sun_path));
461 if (notifysocket[0] == '@')
464 bzero(&iov, sizeof(iov));
465 iov.iov_base = "READY=1";
466 iov.iov_len = strlen("READY=1");
468 bzero(&hdr, sizeof(hdr));
470 hdr.msg_namelen = offsetof(struct sockaddr_un, sun_path) +
471 strlen(notifysocket);
475 unsetenv("NOTIFY_SOCKET");
476 if (sendmsg(fd, &hdr, MSG_NOSIGNAL) < 0) {
477 WARNING ("cannot send notification to systemd");
484 #endif /* KERNEL_LINUX */
486 int main (int argc, char **argv)
488 struct sigaction sig_int_action;
489 struct sigaction sig_term_action;
490 struct sigaction sig_usr1_action;
491 struct sigaction sig_pipe_action;
492 char *configfile = CONFIGFILE;
494 int test_readall = 0;
497 struct sigaction sig_chld_action;
508 c = getopt (argc, argv, "htTC:"
527 global_option_set ("ReadThreads", "-1");
530 #endif /* COLLECT_DAEMON */
534 global_option_set ("PIDFile", optarg);
535 pidfile_from_cli = 1;
540 #endif /* COLLECT_DAEMON */
555 * Read options from the config file, the environment and the command
556 * line (in that order, with later options overwriting previous ones in
558 * Also, this will automatically load modules.
560 if (cf_read (configfile))
562 fprintf (stderr, "Error: Reading the config file failed!\n"
563 "Read the syslog for details.\n");
568 * Change directory. We do this _after_ reading the config and loading
569 * modules to relative paths work as expected.
571 if ((basedir = global_option_get ("BaseDir")) == NULL)
573 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
576 else if (change_basedir (basedir))
578 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
583 * Set global variables or, if that failes, exit. We cannot run with
584 * them being uninitialized. If nothing is configured, then defaults
585 * are being used. So this means that the user has actually done
588 if (init_global_variables () != 0)
598 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
599 sig_chld_action.sa_handler = SIG_IGN;
600 sigaction (SIGCHLD, &sig_chld_action, NULL);
603 * Only daemonize if we're not being supervised
604 * by upstart or systemd (when using Linux).
608 && notify_upstart() == 0 && notify_systemd() == 0
612 if ((pid = fork ()) == -1)
616 fprintf (stderr, "fork: %s",
617 sstrerror (errno, errbuf,
624 /* printf ("Running (PID %i)\n", pid); */
628 /* Detach from session */
632 if (pidfile_create ())
635 /* close standard descriptors */
640 if (open ("/dev/null", O_RDWR) != 0)
642 ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
647 ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
652 ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
655 } /* if (daemonize) */
656 #endif /* COLLECT_DAEMON */
658 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
659 sig_pipe_action.sa_handler = SIG_IGN;
660 sigaction (SIGPIPE, &sig_pipe_action, NULL);
663 * install signal handlers
665 memset (&sig_int_action, '\0', sizeof (sig_int_action));
666 sig_int_action.sa_handler = sig_int_handler;
667 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
669 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
670 sstrerror (errno, errbuf, sizeof (errbuf)));
674 memset (&sig_term_action, '\0', sizeof (sig_term_action));
675 sig_term_action.sa_handler = sig_term_handler;
676 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
678 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
679 sstrerror (errno, errbuf, sizeof (errbuf)));
683 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
684 sig_usr1_action.sa_handler = sig_usr1_handler;
685 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
687 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
688 sstrerror (errno, errbuf, sizeof (errbuf)));
693 * run the actual loops
699 if (plugin_read_all_once () != 0)
704 INFO ("Initialization complete, entering read-loop.");
709 INFO ("Exiting normally.");
716 #endif /* COLLECT_DAEMON */
718 return (exit_status);