1 /**
2 * collectd - src/collectd.c
3 * Copyright (C) 2005-2007 Florian octo Forster
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17 *
18 * Authors:
19 * Florian octo Forster <octo at verplant.org>
20 * Alvaro Barcellos <alvaro.barcellos at gmail.com>
21 **/
23 #include "collectd.h"
24 #include "common.h"
26 #include <sys/types.h>
27 #include <sys/socket.h>
28 #include <netdb.h>
30 #include <pthread.h>
32 #include "plugin.h"
33 #include "configfile.h"
35 #if HAVE_STATGRAB_H
36 # include <statgrab.h>
37 #endif
39 /*
40 * Global variables
41 */
42 char hostname_g[DATA_MAX_NAME_LEN];
43 cdtime_t interval_g;
44 int timeout_g;
45 #if HAVE_LIBKSTAT
46 kstat_ctl_t *kc;
47 #endif /* HAVE_LIBKSTAT */
49 static int loop = 0;
51 static void *do_flush (void __attribute__((unused)) *arg)
52 {
53 INFO ("Flushing all data.");
54 plugin_flush (/* plugin = */ NULL,
55 /* timeout = */ 0,
56 /* ident = */ NULL);
57 INFO ("Finished flushing all data.");
58 pthread_exit (NULL);
59 return NULL;
60 }
62 static void sig_int_handler (int __attribute__((unused)) signal)
63 {
64 loop++;
65 }
67 static void sig_term_handler (int __attribute__((unused)) signal)
68 {
69 loop++;
70 }
72 static void sig_usr1_handler (int __attribute__((unused)) signal)
73 {
74 pthread_t thread;
75 pthread_attr_t attr;
77 /* flushing the data might take a while,
78 * so it should be done asynchronously */
79 pthread_attr_init (&attr);
80 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
81 pthread_create (&thread, &attr, do_flush, NULL);
82 }
84 static int init_hostname (void)
85 {
86 const char *str;
88 struct addrinfo ai_hints;
89 struct addrinfo *ai_list;
90 struct addrinfo *ai_ptr;
91 int status;
93 str = global_option_get ("Hostname");
94 if (str != NULL)
95 {
96 sstrncpy (hostname_g, str, sizeof (hostname_g));
97 return (0);
98 }
100 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
101 {
102 fprintf (stderr, "`gethostname' failed and no "
103 "hostname was configured.\n");
104 return (-1);
105 }
107 str = global_option_get ("FQDNLookup");
108 if (IS_FALSE (str))
109 return (0);
111 memset (&ai_hints, '\0', sizeof (ai_hints));
112 ai_hints.ai_flags = AI_CANONNAME;
114 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
115 if (status != 0)
116 {
117 ERROR ("Looking up \"%s\" failed. You have set the "
118 "\"FQDNLookup\" option, but I cannot resolve "
119 "my hostname to a fully qualified domain "
120 "name. Please fix you network "
121 "configuration.", hostname_g);
122 return (-1);
123 }
125 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
126 {
127 if (ai_ptr->ai_canonname == NULL)
128 continue;
130 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
131 break;
132 }
134 freeaddrinfo (ai_list);
135 return (0);
136 } /* int init_hostname */
138 static int init_global_variables (void)
139 {
140 char const *str;
142 interval_g = cf_get_default_interval ();
143 assert (interval_g > 0);
144 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
146 str = global_option_get ("Timeout");
147 if (str == NULL)
148 str = "2";
149 timeout_g = atoi (str);
150 if (timeout_g <= 1)
151 {
152 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
153 "Please check your settings.\n");
154 return (-1);
155 }
156 DEBUG ("timeout_g = %i;", timeout_g);
158 if (init_hostname () != 0)
159 return (-1);
160 DEBUG ("hostname_g = %s;", hostname_g);
162 return (0);
163 } /* int init_global_variables */
165 static int change_basedir (const char *orig_dir)
166 {
167 char *dir = strdup (orig_dir);
168 int dirlen;
169 int status;
171 if (dir == NULL)
172 {
173 char errbuf[1024];
174 ERROR ("strdup failed: %s",
175 sstrerror (errno, errbuf, sizeof (errbuf)));
176 return (-1);
177 }
179 dirlen = strlen (dir);
180 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
181 dir[--dirlen] = '\0';
183 if (dirlen <= 0)
184 return (-1);
186 status = chdir (dir);
187 free (dir);
189 if (status != 0)
190 {
191 if (errno == ENOENT)
192 {
193 if (mkdir (orig_dir, 0755) == -1)
194 {
195 char errbuf[1024];
196 ERROR ("change_basedir: mkdir (%s): %s", orig_dir,
197 sstrerror (errno, errbuf,
198 sizeof (errbuf)));
199 return (-1);
200 }
201 else if (chdir (orig_dir) == -1)
202 {
203 char errbuf[1024];
204 ERROR ("chdir (%s): %s", orig_dir,
205 sstrerror (errno, errbuf,
206 sizeof (errbuf)));
207 return (-1);
208 }
209 }
210 else
211 {
212 char errbuf[1024];
213 ERROR ("chdir (%s): %s", orig_dir,
214 sstrerror (errno, errbuf,
215 sizeof (errbuf)));
216 return (-1);
217 }
218 }
220 return (0);
221 } /* static int change_basedir (char *dir) */
223 #if HAVE_LIBKSTAT
224 static void update_kstat (void)
225 {
226 if (kc == NULL)
227 {
228 if ((kc = kstat_open ()) == NULL)
229 ERROR ("Unable to open kstat control structure");
230 }
231 else
232 {
233 kid_t kid;
234 kid = kstat_chain_update (kc);
235 if (kid > 0)
236 {
237 INFO ("kstat chain has been updated");
238 plugin_init_all ();
239 }
240 else if (kid < 0)
241 ERROR ("kstat chain update failed");
242 /* else: everything works as expected */
243 }
245 return;
246 } /* static void update_kstat (void) */
247 #endif /* HAVE_LIBKSTAT */
249 /* TODO
250 * Remove all settings but `-f' and `-C'
251 */
252 static void exit_usage (int status)
253 {
254 printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
256 "Available options:\n"
257 " General:\n"
258 " -C <file> Configuration file.\n"
259 " Default: "CONFIGFILE"\n"
260 " -t Test config and exit.\n"
261 " -T Test plugin read and exit.\n"
262 " -P <file> PID-file.\n"
263 " Default: "PIDFILE"\n"
264 #if COLLECT_DAEMON
265 " -f Don't fork to the background.\n"
266 #endif
267 " -h Display help (this message)\n"
268 "\nBuiltin defaults:\n"
269 " Config file "CONFIGFILE"\n"
270 " PID file "PIDFILE"\n"
271 " Plugin directory "PLUGINDIR"\n"
272 " Data directory "PKGLOCALSTATEDIR"\n"
273 "\n"PACKAGE" "VERSION", http://collectd.org/\n"
274 "by Florian octo Forster <octo@verplant.org>\n"
275 "for contributions see `AUTHORS'\n");
276 exit (status);
277 } /* static void exit_usage (int status) */
279 static int do_init (void)
280 {
281 #if HAVE_LIBKSTAT
282 kc = NULL;
283 update_kstat ();
284 #endif
286 #if HAVE_LIBSTATGRAB
287 if (sg_init ())
288 {
289 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
290 return (-1);
291 }
293 if (sg_drop_privileges ())
294 {
295 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
296 return (-1);
297 }
298 #endif
300 plugin_init_all ();
302 return (0);
303 } /* int do_init () */
306 static int do_loop (void)
307 {
308 cdtime_t interval = cf_get_default_interval ();
309 cdtime_t wait_until;
311 wait_until = cdtime () + interval;
313 while (loop == 0)
314 {
315 struct timespec ts_wait = { 0, 0 };
316 cdtime_t now;
318 #if HAVE_LIBKSTAT
319 update_kstat ();
320 #endif
322 /* Issue all plugins */
323 plugin_read_all ();
325 now = cdtime ();
326 if (now >= wait_until)
327 {
328 WARNING ("Not sleeping because the next interval is "
329 "%.3f seconds in the past!",
330 CDTIME_T_TO_DOUBLE (now - wait_until));
331 wait_until = now + interval;
332 continue;
333 }
335 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
336 wait_until = wait_until + interval;
338 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
339 {
340 if (errno != EINTR)
341 {
342 char errbuf[1024];
343 ERROR ("nanosleep failed: %s",
344 sstrerror (errno, errbuf,
345 sizeof (errbuf)));
346 return (-1);
347 }
348 }
349 } /* while (loop == 0) */
351 return (0);
352 } /* int do_loop */
354 static int do_shutdown (void)
355 {
356 plugin_shutdown_all ();
357 return (0);
358 } /* int do_shutdown */
360 #if COLLECT_DAEMON
361 static int pidfile_create (void)
362 {
363 FILE *fh;
364 const char *file = global_option_get ("PIDFile");
366 if ((fh = fopen (file, "w")) == NULL)
367 {
368 char errbuf[1024];
369 ERROR ("fopen (%s): %s", file,
370 sstrerror (errno, errbuf, sizeof (errbuf)));
371 return (1);
372 }
374 fprintf (fh, "%i\n", (int) getpid ());
375 fclose(fh);
377 return (0);
378 } /* static int pidfile_create (const char *file) */
380 static int pidfile_remove (void)
381 {
382 const char *file = global_option_get ("PIDFile");
384 DEBUG ("unlink (%s)", (file != NULL) ? file : "<null>");
385 return (unlink (file));
386 } /* static int pidfile_remove (const char *file) */
387 #endif /* COLLECT_DAEMON */
389 int main (int argc, char **argv)
390 {
391 struct sigaction sig_int_action;
392 struct sigaction sig_term_action;
393 struct sigaction sig_usr1_action;
394 struct sigaction sig_pipe_action;
395 char *configfile = CONFIGFILE;
396 int test_config = 0;
397 int test_readall = 0;
398 const char *basedir;
399 #if COLLECT_DAEMON
400 struct sigaction sig_chld_action;
401 pid_t pid;
402 int daemonize = 1;
403 #endif
404 int exit_status = 0;
406 /* read options */
407 while (1)
408 {
409 int c;
411 c = getopt (argc, argv, "htTC:"
412 #if COLLECT_DAEMON
413 "fP:"
414 #endif
415 );
417 if (c == -1)
418 break;
420 switch (c)
421 {
422 case 'C':
423 configfile = optarg;
424 break;
425 case 't':
426 test_config = 1;
427 break;
428 case 'T':
429 test_readall = 1;
430 global_option_set ("ReadThreads", "-1");
431 #if COLLECT_DAEMON
432 daemonize = 0;
433 #endif /* COLLECT_DAEMON */
434 break;
435 #if COLLECT_DAEMON
436 case 'P':
437 global_option_set ("PIDFile", optarg);
438 break;
439 case 'f':
440 daemonize = 0;
441 break;
442 #endif /* COLLECT_DAEMON */
443 case 'h':
444 exit_usage (0);
445 break;
446 default:
447 exit_usage (1);
448 } /* switch (c) */
449 } /* while (1) */
451 if (optind < argc)
452 exit_usage (1);
454 plugin_init_ctx ();
456 /*
457 * Read options from the config file, the environment and the command
458 * line (in that order, with later options overwriting previous ones in
459 * general).
460 * Also, this will automatically load modules.
461 */
462 if (cf_read (configfile))
463 {
464 fprintf (stderr, "Error: Reading the config file failed!\n"
465 "Read the syslog for details.\n");
466 return (1);
467 }
469 /*
470 * Change directory. We do this _after_ reading the config and loading
471 * modules to relative paths work as expected.
472 */
473 if ((basedir = global_option_get ("BaseDir")) == NULL)
474 {
475 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
476 return (1);
477 }
478 else if (change_basedir (basedir))
479 {
480 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
481 return (1);
482 }
484 /*
485 * Set global variables or, if that failes, exit. We cannot run with
486 * them being uninitialized. If nothing is configured, then defaults
487 * are being used. So this means that the user has actually done
488 * something wrong.
489 */
490 if (init_global_variables () != 0)
491 return (1);
493 if (test_config)
494 return (0);
496 #if COLLECT_DAEMON
497 /*
498 * fork off child
499 */
500 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
501 sig_chld_action.sa_handler = SIG_IGN;
502 sigaction (SIGCHLD, &sig_chld_action, NULL);
504 if (daemonize)
505 {
506 if ((pid = fork ()) == -1)
507 {
508 /* error */
509 char errbuf[1024];
510 fprintf (stderr, "fork: %s",
511 sstrerror (errno, errbuf,
512 sizeof (errbuf)));
513 return (1);
514 }
515 else if (pid != 0)
516 {
517 /* parent */
518 /* printf ("Running (PID %i)\n", pid); */
519 return (0);
520 }
522 /* Detach from session */
523 setsid ();
525 /* Write pidfile */
526 if (pidfile_create ())
527 exit (2);
529 /* close standard descriptors */
530 close (2);
531 close (1);
532 close (0);
534 if (open ("/dev/null", O_RDWR) != 0)
535 {
536 ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
537 return (1);
538 }
539 if (dup (0) != 1)
540 {
541 ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
542 return (1);
543 }
544 if (dup (0) != 2)
545 {
546 ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
547 return (1);
548 }
549 } /* if (daemonize) */
550 #endif /* COLLECT_DAEMON */
552 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
553 sig_pipe_action.sa_handler = SIG_IGN;
554 sigaction (SIGPIPE, &sig_pipe_action, NULL);
556 /*
557 * install signal handlers
558 */
559 memset (&sig_int_action, '\0', sizeof (sig_int_action));
560 sig_int_action.sa_handler = sig_int_handler;
561 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
562 char errbuf[1024];
563 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
564 sstrerror (errno, errbuf, sizeof (errbuf)));
565 return (1);
566 }
568 memset (&sig_term_action, '\0', sizeof (sig_term_action));
569 sig_term_action.sa_handler = sig_term_handler;
570 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
571 char errbuf[1024];
572 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
573 sstrerror (errno, errbuf, sizeof (errbuf)));
574 return (1);
575 }
577 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
578 sig_usr1_action.sa_handler = sig_usr1_handler;
579 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
580 char errbuf[1024];
581 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
582 sstrerror (errno, errbuf, sizeof (errbuf)));
583 return (1);
584 }
586 /*
587 * run the actual loops
588 */
589 do_init ();
591 if (test_readall)
592 {
593 if (plugin_read_all_once () != 0)
594 exit_status = 1;
595 }
596 else
597 {
598 INFO ("Initialization complete, entering read-loop.");
599 do_loop ();
600 }
602 /* close syslog */
603 INFO ("Exiting normally.");
605 do_shutdown ();
607 #if COLLECT_DAEMON
608 if (daemonize)
609 pidfile_remove ();
610 #endif /* COLLECT_DAEMON */
612 return (exit_status);
613 } /* int main */