1 /**
2 * collectd - src/collectd.c
3 * Copyright (C) 2005-2007 Florian octo Forster
4 *
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:
11 *
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
14 *
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.
22 *
23 * Authors:
24 * Florian octo Forster <octo at collectd.org>
25 * Alvaro Barcellos <alvaro.barcellos at gmail.com>
26 **/
28 #include "collectd.h"
29 #include "common.h"
31 #include "plugin.h"
32 #include "configfile.h"
34 #include <sys/types.h>
35 #include <sys/un.h>
36 #include <netdb.h>
38 #include <pthread.h>
40 #if HAVE_LOCALE_H
41 # include <locale.h>
42 #endif
44 #if HAVE_STATGRAB_H
45 # include <statgrab.h>
46 #endif
48 #ifndef COLLECTD_LOCALE
49 # define COLLECTD_LOCALE "C"
50 #endif
52 /*
53 * Global variables
54 */
55 char hostname_g[DATA_MAX_NAME_LEN];
56 cdtime_t interval_g;
57 int pidfile_from_cli = 0;
58 int timeout_g;
59 #if HAVE_LIBKSTAT
60 kstat_ctl_t *kc;
61 #endif /* HAVE_LIBKSTAT */
63 static int loop = 0;
65 static void *do_flush (void __attribute__((unused)) *arg)
66 {
67 INFO ("Flushing all data.");
68 plugin_flush (/* plugin = */ NULL,
69 /* timeout = */ 0,
70 /* ident = */ NULL);
71 INFO ("Finished flushing all data.");
72 pthread_exit (NULL);
73 return NULL;
74 }
76 static void sig_int_handler (int __attribute__((unused)) signal)
77 {
78 loop++;
79 }
81 static void sig_term_handler (int __attribute__((unused)) signal)
82 {
83 loop++;
84 }
86 static void sig_usr1_handler (int __attribute__((unused)) signal)
87 {
88 pthread_t thread;
89 pthread_attr_t attr;
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);
97 }
99 static int init_hostname (void)
100 {
101 const char *str;
103 struct addrinfo ai_hints;
104 struct addrinfo *ai_list;
105 struct addrinfo *ai_ptr;
106 int status;
108 str = global_option_get ("Hostname");
109 if (str != NULL)
110 {
111 sstrncpy (hostname_g, str, sizeof (hostname_g));
112 return (0);
113 }
115 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
116 {
117 fprintf (stderr, "`gethostname' failed and no "
118 "hostname was configured.\n");
119 return (-1);
120 }
122 str = global_option_get ("FQDNLookup");
123 if (IS_FALSE (str))
124 return (0);
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);
130 if (status != 0)
131 {
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);
137 return (-1);
138 }
140 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
141 {
142 if (ai_ptr->ai_canonname == NULL)
143 continue;
145 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
146 break;
147 }
149 freeaddrinfo (ai_list);
150 return (0);
151 } /* int init_hostname */
153 static int init_global_variables (void)
154 {
155 char const *str;
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");
162 if (str == NULL)
163 str = "2";
164 timeout_g = atoi (str);
165 if (timeout_g <= 1)
166 {
167 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
168 "Please check your settings.\n");
169 return (-1);
170 }
171 DEBUG ("timeout_g = %i;", timeout_g);
173 if (init_hostname () != 0)
174 return (-1);
175 DEBUG ("hostname_g = %s;", hostname_g);
177 return (0);
178 } /* int init_global_variables */
180 static int change_basedir (const char *orig_dir)
181 {
182 char *dir;
183 size_t dirlen;
184 int status;
186 dir = strdup (orig_dir);
187 if (dir == NULL)
188 {
189 char errbuf[1024];
190 ERROR ("strdup failed: %s",
191 sstrerror (errno, errbuf, sizeof (errbuf)));
192 return (-1);
193 }
195 dirlen = strlen (dir);
196 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
197 dir[--dirlen] = '\0';
199 if (dirlen <= 0) {
200 free (dir);
201 return (-1);
202 }
204 status = chdir (dir);
205 if (status == 0)
206 {
207 free (dir);
208 return (0);
209 }
210 else if (errno != ENOENT)
211 {
212 char errbuf[1024];
213 ERROR ("change_basedir: chdir (%s): %s", dir,
214 sstrerror (errno, errbuf, sizeof (errbuf)));
215 free (dir);
216 return (-1);
217 }
219 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
220 if (status != 0)
221 {
222 char errbuf[1024];
223 ERROR ("change_basedir: mkdir (%s): %s", dir,
224 sstrerror (errno, errbuf, sizeof (errbuf)));
225 free (dir);
226 return (-1);
227 }
229 status = chdir (dir);
230 if (status != 0)
231 {
232 char errbuf[1024];
233 ERROR ("change_basedir: chdir (%s): %s", dir,
234 sstrerror (errno, errbuf, sizeof (errbuf)));
235 free (dir);
236 return (-1);
237 }
239 free (dir);
240 return (0);
241 } /* static int change_basedir (char *dir) */
243 #if HAVE_LIBKSTAT
244 static void update_kstat (void)
245 {
246 if (kc == NULL)
247 {
248 if ((kc = kstat_open ()) == NULL)
249 ERROR ("Unable to open kstat control structure");
250 }
251 else
252 {
253 kid_t kid;
254 kid = kstat_chain_update (kc);
255 if (kid > 0)
256 {
257 INFO ("kstat chain has been updated");
258 plugin_init_all ();
259 }
260 else if (kid < 0)
261 ERROR ("kstat chain update failed");
262 /* else: everything works as expected */
263 }
265 return;
266 } /* static void update_kstat (void) */
267 #endif /* HAVE_LIBKSTAT */
269 /* TODO
270 * Remove all settings but `-f' and `-C'
271 */
272 static void exit_usage (int status)
273 {
274 printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
276 "Available options:\n"
277 " General:\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"
284 #if COLLECT_DAEMON
285 " -f Don't fork to the background.\n"
286 #endif
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");
296 exit (status);
297 } /* static void exit_usage (int status) */
299 static int do_init (void)
300 {
301 #if HAVE_SETLOCALE
302 if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
303 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
304 #endif
306 #if HAVE_LIBKSTAT
307 kc = NULL;
308 update_kstat ();
309 #endif
311 #if HAVE_LIBSTATGRAB
312 if (sg_init (
313 # if HAVE_LIBSTATGRAB_0_90
314 0
315 # endif
316 ))
317 {
318 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
319 return (-1);
320 }
322 if (sg_drop_privileges ())
323 {
324 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
325 return (-1);
326 }
327 #endif
329 plugin_init_all ();
331 return (0);
332 } /* int do_init () */
335 static int do_loop (void)
336 {
337 cdtime_t interval = cf_get_default_interval ();
338 cdtime_t wait_until;
340 wait_until = cdtime () + interval;
342 while (loop == 0)
343 {
344 struct timespec ts_wait = { 0, 0 };
345 cdtime_t now;
347 #if HAVE_LIBKSTAT
348 update_kstat ();
349 #endif
351 /* Issue all plugins */
352 plugin_read_all ();
354 now = cdtime ();
355 if (now >= wait_until)
356 {
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;
361 continue;
362 }
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))
368 {
369 if (errno != EINTR)
370 {
371 char errbuf[1024];
372 ERROR ("nanosleep failed: %s",
373 sstrerror (errno, errbuf,
374 sizeof (errbuf)));
375 return (-1);
376 }
377 }
378 } /* while (loop == 0) */
380 return (0);
381 } /* int do_loop */
383 static int do_shutdown (void)
384 {
385 plugin_shutdown_all ();
386 return (0);
387 } /* int do_shutdown */
389 #if COLLECT_DAEMON
390 static int pidfile_create (void)
391 {
392 FILE *fh;
393 const char *file = global_option_get ("PIDFile");
395 if ((fh = fopen (file, "w")) == NULL)
396 {
397 char errbuf[1024];
398 ERROR ("fopen (%s): %s", file,
399 sstrerror (errno, errbuf, sizeof (errbuf)));
400 return (1);
401 }
403 fprintf (fh, "%i\n", (int) getpid ());
404 fclose(fh);
406 return (0);
407 } /* static int pidfile_create (const char *file) */
409 static int pidfile_remove (void)
410 {
411 const char *file = global_option_get ("PIDFile");
412 if (file == NULL)
413 return 0;
415 return (unlink (file));
416 } /* static int pidfile_remove (const char *file) */
417 #endif /* COLLECT_DAEMON */
419 #ifdef KERNEL_LINUX
420 int notify_upstart (void)
421 {
422 char const *upstart_job = getenv("UPSTART_JOB");
424 if (upstart_job == NULL)
425 return 0;
427 if (strcmp(upstart_job, "collectd") != 0)
428 {
429 WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
430 return 0;
431 }
433 NOTICE("Upstart detected, stopping now to signal readyness.");
434 raise(SIGSTOP);
435 unsetenv("UPSTART_JOB");
437 return 1;
438 }
440 int notify_systemd (void)
441 {
442 int fd;
443 const char *notifysocket;
444 struct sockaddr_un su;
445 size_t su_size;
446 char buffer[] = "READY=1\n";
448 notifysocket = getenv ("NOTIFY_SOCKET");
449 if (notifysocket == NULL)
450 return 0;
452 if ((strlen (notifysocket) < 2)
453 || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
454 {
455 ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
456 return 0;
457 }
458 NOTICE ("Systemd detected, trying to signal readyness.");
460 unsetenv ("NOTIFY_SOCKET");
462 fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
463 if (fd < 0) {
464 char errbuf[1024];
465 ERROR ("creating UNIX socket failed: %s",
466 sstrerror (errno, errbuf, sizeof (errbuf)));
467 return 0;
468 }
470 memset (&su, 0, sizeof (su));
471 su.sun_family = AF_UNIX;
472 if (notifysocket[0] != '@')
473 {
474 /* regular UNIX socket */
475 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
476 su_size = sizeof (su);
477 }
478 else
479 {
480 #if KERNEL_LINUX
481 /* Linux abstract namespace socket: specify address as "\0foo", i.e.
482 * start with a null byte. Since null bytes have no special meaning in
483 * that case, we have to set su_size correctly to cover only the bytes
484 * that are part of the address. */
485 sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
486 su.sun_path[0] = 0;
487 su_size = sizeof (sa_family_t) + strlen (notifysocket);
488 if (su_size > sizeof (su))
489 su_size = sizeof (su);
490 #else
491 ERROR ("Systemd socket uses Linux abstract namespace notation (\"%s\"), "
492 "but I don't appear to be running on Linux.", notifysocket);
493 return 0;
494 #endif
495 }
497 if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
498 {
499 char errbuf[1024];
500 ERROR ("sendto(\"%s\") failed: %s", notifysocket,
501 sstrerror (errno, errbuf, sizeof (errbuf)));
502 close(fd);
503 return 0;
504 }
506 close(fd);
507 return 1;
508 }
509 #endif /* KERNEL_LINUX */
511 int main (int argc, char **argv)
512 {
513 struct sigaction sig_int_action;
514 struct sigaction sig_term_action;
515 struct sigaction sig_usr1_action;
516 struct sigaction sig_pipe_action;
517 char *configfile = CONFIGFILE;
518 int test_config = 0;
519 int test_readall = 0;
520 const char *basedir;
521 #if COLLECT_DAEMON
522 struct sigaction sig_chld_action;
523 pid_t pid;
524 int daemonize = 1;
525 #endif
526 int exit_status = 0;
528 /* read options */
529 while (1)
530 {
531 int c;
533 c = getopt (argc, argv, "htTC:"
534 #if COLLECT_DAEMON
535 "fP:"
536 #endif
537 );
539 if (c == -1)
540 break;
542 switch (c)
543 {
544 case 'C':
545 configfile = optarg;
546 break;
547 case 't':
548 test_config = 1;
549 break;
550 case 'T':
551 test_readall = 1;
552 global_option_set ("ReadThreads", "-1");
553 #if COLLECT_DAEMON
554 daemonize = 0;
555 #endif /* COLLECT_DAEMON */
556 break;
557 #if COLLECT_DAEMON
558 case 'P':
559 global_option_set ("PIDFile", optarg);
560 pidfile_from_cli = 1;
561 break;
562 case 'f':
563 daemonize = 0;
564 break;
565 #endif /* COLLECT_DAEMON */
566 case 'h':
567 exit_usage (0);
568 break;
569 default:
570 exit_usage (1);
571 } /* switch (c) */
572 } /* while (1) */
574 if (optind < argc)
575 exit_usage (1);
577 plugin_init_ctx ();
579 /*
580 * Read options from the config file, the environment and the command
581 * line (in that order, with later options overwriting previous ones in
582 * general).
583 * Also, this will automatically load modules.
584 */
585 if (cf_read (configfile))
586 {
587 fprintf (stderr, "Error: Reading the config file failed!\n"
588 "Read the syslog for details.\n");
589 return (1);
590 }
592 /*
593 * Change directory. We do this _after_ reading the config and loading
594 * modules to relative paths work as expected.
595 */
596 if ((basedir = global_option_get ("BaseDir")) == NULL)
597 {
598 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
599 return (1);
600 }
601 else if (change_basedir (basedir))
602 {
603 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
604 return (1);
605 }
607 /*
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
611 * something wrong.
612 */
613 if (init_global_variables () != 0)
614 return (1);
616 if (test_config)
617 return (0);
619 #if COLLECT_DAEMON
620 /*
621 * fork off child
622 */
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);
627 /*
628 * Only daemonize if we're not being supervised
629 * by upstart or systemd (when using Linux).
630 */
631 if (daemonize
632 #ifdef KERNEL_LINUX
633 && notify_upstart() == 0 && notify_systemd() == 0
634 #endif
635 )
636 {
637 if ((pid = fork ()) == -1)
638 {
639 /* error */
640 char errbuf[1024];
641 fprintf (stderr, "fork: %s",
642 sstrerror (errno, errbuf,
643 sizeof (errbuf)));
644 return (1);
645 }
646 else if (pid != 0)
647 {
648 /* parent */
649 /* printf ("Running (PID %i)\n", pid); */
650 return (0);
651 }
653 /* Detach from session */
654 setsid ();
656 /* Write pidfile */
657 if (pidfile_create ())
658 exit (2);
660 /* close standard descriptors */
661 close (2);
662 close (1);
663 close (0);
665 if (open ("/dev/null", O_RDWR) != 0)
666 {
667 ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
668 return (1);
669 }
670 if (dup (0) != 1)
671 {
672 ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
673 return (1);
674 }
675 if (dup (0) != 2)
676 {
677 ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
678 return (1);
679 }
680 } /* if (daemonize) */
681 #endif /* COLLECT_DAEMON */
683 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
684 sig_pipe_action.sa_handler = SIG_IGN;
685 sigaction (SIGPIPE, &sig_pipe_action, NULL);
687 /*
688 * install signal handlers
689 */
690 memset (&sig_int_action, '\0', sizeof (sig_int_action));
691 sig_int_action.sa_handler = sig_int_handler;
692 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
693 char errbuf[1024];
694 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
695 sstrerror (errno, errbuf, sizeof (errbuf)));
696 return (1);
697 }
699 memset (&sig_term_action, '\0', sizeof (sig_term_action));
700 sig_term_action.sa_handler = sig_term_handler;
701 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
702 char errbuf[1024];
703 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
704 sstrerror (errno, errbuf, sizeof (errbuf)));
705 return (1);
706 }
708 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
709 sig_usr1_action.sa_handler = sig_usr1_handler;
710 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
711 char errbuf[1024];
712 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
713 sstrerror (errno, errbuf, sizeof (errbuf)));
714 return (1);
715 }
717 /*
718 * run the actual loops
719 */
720 do_init ();
722 if (test_readall)
723 {
724 if (plugin_read_all_once () != 0)
725 exit_status = 1;
726 }
727 else
728 {
729 INFO ("Initialization complete, entering read-loop.");
730 do_loop ();
731 }
733 /* close syslog */
734 INFO ("Exiting normally.");
736 do_shutdown ();
738 #if COLLECT_DAEMON
739 if (daemonize)
740 pidfile_remove ();
741 #endif /* COLLECT_DAEMON */
743 return (exit_status);
744 } /* int main */