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 pthread_attr_destroy (&attr);
83 }
85 static int init_hostname (void)
86 {
87 const char *str;
89 struct addrinfo ai_hints;
90 struct addrinfo *ai_list;
91 struct addrinfo *ai_ptr;
92 int status;
94 str = global_option_get ("Hostname");
95 if (str != NULL)
96 {
97 sstrncpy (hostname_g, str, sizeof (hostname_g));
98 return (0);
99 }
101 if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
102 {
103 fprintf (stderr, "`gethostname' failed and no "
104 "hostname was configured.\n");
105 return (-1);
106 }
108 str = global_option_get ("FQDNLookup");
109 if (IS_FALSE (str))
110 return (0);
112 memset (&ai_hints, '\0', sizeof (ai_hints));
113 ai_hints.ai_flags = AI_CANONNAME;
115 status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
116 if (status != 0)
117 {
118 ERROR ("Looking up \"%s\" failed. You have set the "
119 "\"FQDNLookup\" option, but I cannot resolve "
120 "my hostname to a fully qualified domain "
121 "name. Please fix the network "
122 "configuration.", hostname_g);
123 return (-1);
124 }
126 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
127 {
128 if (ai_ptr->ai_canonname == NULL)
129 continue;
131 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
132 break;
133 }
135 freeaddrinfo (ai_list);
136 return (0);
137 } /* int init_hostname */
139 static int init_global_variables (void)
140 {
141 char const *str;
143 interval_g = cf_get_default_interval ();
144 assert (interval_g > 0);
145 DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
147 str = global_option_get ("Timeout");
148 if (str == NULL)
149 str = "2";
150 timeout_g = atoi (str);
151 if (timeout_g <= 1)
152 {
153 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
154 "Please check your settings.\n");
155 return (-1);
156 }
157 DEBUG ("timeout_g = %i;", timeout_g);
159 if (init_hostname () != 0)
160 return (-1);
161 DEBUG ("hostname_g = %s;", hostname_g);
163 return (0);
164 } /* int init_global_variables */
166 static int change_basedir (const char *orig_dir)
167 {
168 char *dir;
169 size_t dirlen;
170 int status;
172 dir = strdup (orig_dir);
173 if (dir == NULL)
174 {
175 char errbuf[1024];
176 ERROR ("strdup failed: %s",
177 sstrerror (errno, errbuf, sizeof (errbuf)));
178 return (-1);
179 }
181 dirlen = strlen (dir);
182 while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
183 dir[--dirlen] = '\0';
185 if (dirlen <= 0) {
186 free (dir);
187 return (-1);
188 }
190 status = chdir (dir);
191 if (status == 0)
192 {
193 free (dir);
194 return (0);
195 }
196 else if (errno != ENOENT)
197 {
198 char errbuf[1024];
199 ERROR ("change_basedir: chdir (%s): %s", dir,
200 sstrerror (errno, errbuf, sizeof (errbuf)));
201 free (dir);
202 return (-1);
203 }
205 status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
206 if (status != 0)
207 {
208 char errbuf[1024];
209 ERROR ("change_basedir: mkdir (%s): %s", dir,
210 sstrerror (errno, errbuf, sizeof (errbuf)));
211 free (dir);
212 return (-1);
213 }
215 status = chdir (dir);
216 if (status != 0)
217 {
218 char errbuf[1024];
219 ERROR ("change_basedir: chdir (%s): %s", dir,
220 sstrerror (errno, errbuf, sizeof (errbuf)));
221 free (dir);
222 return (-1);
223 }
225 free (dir);
226 return (0);
227 } /* static int change_basedir (char *dir) */
229 #if HAVE_LIBKSTAT
230 static void update_kstat (void)
231 {
232 if (kc == NULL)
233 {
234 if ((kc = kstat_open ()) == NULL)
235 ERROR ("Unable to open kstat control structure");
236 }
237 else
238 {
239 kid_t kid;
240 kid = kstat_chain_update (kc);
241 if (kid > 0)
242 {
243 INFO ("kstat chain has been updated");
244 plugin_init_all ();
245 }
246 else if (kid < 0)
247 ERROR ("kstat chain update failed");
248 /* else: everything works as expected */
249 }
251 return;
252 } /* static void update_kstat (void) */
253 #endif /* HAVE_LIBKSTAT */
255 /* TODO
256 * Remove all settings but `-f' and `-C'
257 */
258 static void exit_usage (int status)
259 {
260 printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
262 "Available options:\n"
263 " General:\n"
264 " -C <file> Configuration file.\n"
265 " Default: "CONFIGFILE"\n"
266 " -t Test config and exit.\n"
267 " -T Test plugin read and exit.\n"
268 " -P <file> PID-file.\n"
269 " Default: "PIDFILE"\n"
270 #if COLLECT_DAEMON
271 " -f Don't fork to the background.\n"
272 #endif
273 " -h Display help (this message)\n"
274 "\nBuiltin defaults:\n"
275 " Config file "CONFIGFILE"\n"
276 " PID file "PIDFILE"\n"
277 " Plugin directory "PLUGINDIR"\n"
278 " Data directory "PKGLOCALSTATEDIR"\n"
279 "\n"PACKAGE" "VERSION", http://collectd.org/\n"
280 "by Florian octo Forster <octo@verplant.org>\n"
281 "for contributions see `AUTHORS'\n");
282 exit (status);
283 } /* static void exit_usage (int status) */
285 static int do_init (void)
286 {
287 #if HAVE_LIBKSTAT
288 kc = NULL;
289 update_kstat ();
290 #endif
292 #if HAVE_LIBSTATGRAB
293 if (sg_init ())
294 {
295 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
296 return (-1);
297 }
299 if (sg_drop_privileges ())
300 {
301 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
302 return (-1);
303 }
304 #endif
306 plugin_init_all ();
308 return (0);
309 } /* int do_init () */
312 static int do_loop (void)
313 {
314 cdtime_t interval = cf_get_default_interval ();
315 cdtime_t wait_until;
317 wait_until = cdtime () + interval;
319 while (loop == 0)
320 {
321 struct timespec ts_wait = { 0, 0 };
322 cdtime_t now;
324 #if HAVE_LIBKSTAT
325 update_kstat ();
326 #endif
328 /* Issue all plugins */
329 plugin_read_all ();
331 now = cdtime ();
332 if (now >= wait_until)
333 {
334 WARNING ("Not sleeping because the next interval is "
335 "%.3f seconds in the past!",
336 CDTIME_T_TO_DOUBLE (now - wait_until));
337 wait_until = now + interval;
338 continue;
339 }
341 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
342 wait_until = wait_until + interval;
344 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
345 {
346 if (errno != EINTR)
347 {
348 char errbuf[1024];
349 ERROR ("nanosleep failed: %s",
350 sstrerror (errno, errbuf,
351 sizeof (errbuf)));
352 return (-1);
353 }
354 }
355 } /* while (loop == 0) */
357 return (0);
358 } /* int do_loop */
360 static int do_shutdown (void)
361 {
362 plugin_shutdown_all ();
363 return (0);
364 } /* int do_shutdown */
366 #if COLLECT_DAEMON
367 static int pidfile_create (void)
368 {
369 FILE *fh;
370 const char *file = global_option_get ("PIDFile");
372 if ((fh = fopen (file, "w")) == NULL)
373 {
374 char errbuf[1024];
375 ERROR ("fopen (%s): %s", file,
376 sstrerror (errno, errbuf, sizeof (errbuf)));
377 return (1);
378 }
380 fprintf (fh, "%i\n", (int) getpid ());
381 fclose(fh);
383 return (0);
384 } /* static int pidfile_create (const char *file) */
386 static int pidfile_remove (void)
387 {
388 const char *file = global_option_get ("PIDFile");
389 if (file == NULL)
390 return 0;
392 return (unlink (file));
393 } /* static int pidfile_remove (const char *file) */
394 #endif /* COLLECT_DAEMON */
396 int main (int argc, char **argv)
397 {
398 struct sigaction sig_int_action;
399 struct sigaction sig_term_action;
400 struct sigaction sig_usr1_action;
401 struct sigaction sig_pipe_action;
402 char *configfile = CONFIGFILE;
403 int test_config = 0;
404 int test_readall = 0;
405 const char *basedir;
406 #if COLLECT_DAEMON
407 struct sigaction sig_chld_action;
408 pid_t pid;
409 int daemonize = 1;
410 #endif
411 int exit_status = 0;
413 /* read options */
414 while (1)
415 {
416 int c;
418 c = getopt (argc, argv, "htTC:"
419 #if COLLECT_DAEMON
420 "fP:"
421 #endif
422 );
424 if (c == -1)
425 break;
427 switch (c)
428 {
429 case 'C':
430 configfile = optarg;
431 break;
432 case 't':
433 test_config = 1;
434 break;
435 case 'T':
436 test_readall = 1;
437 global_option_set ("ReadThreads", "-1");
438 #if COLLECT_DAEMON
439 daemonize = 0;
440 #endif /* COLLECT_DAEMON */
441 break;
442 #if COLLECT_DAEMON
443 case 'P':
444 global_option_set ("PIDFile", optarg);
445 break;
446 case 'f':
447 daemonize = 0;
448 break;
449 #endif /* COLLECT_DAEMON */
450 case 'h':
451 exit_usage (0);
452 break;
453 default:
454 exit_usage (1);
455 } /* switch (c) */
456 } /* while (1) */
458 if (optind < argc)
459 exit_usage (1);
461 plugin_init_ctx ();
463 /*
464 * Read options from the config file, the environment and the command
465 * line (in that order, with later options overwriting previous ones in
466 * general).
467 * Also, this will automatically load modules.
468 */
469 if (cf_read (configfile))
470 {
471 fprintf (stderr, "Error: Reading the config file failed!\n"
472 "Read the syslog for details.\n");
473 return (1);
474 }
476 /*
477 * Change directory. We do this _after_ reading the config and loading
478 * modules to relative paths work as expected.
479 */
480 if ((basedir = global_option_get ("BaseDir")) == NULL)
481 {
482 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
483 return (1);
484 }
485 else if (change_basedir (basedir))
486 {
487 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
488 return (1);
489 }
491 /*
492 * Set global variables or, if that failes, exit. We cannot run with
493 * them being uninitialized. If nothing is configured, then defaults
494 * are being used. So this means that the user has actually done
495 * something wrong.
496 */
497 if (init_global_variables () != 0)
498 return (1);
500 if (test_config)
501 return (0);
503 #if COLLECT_DAEMON
504 /*
505 * fork off child
506 */
507 memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
508 sig_chld_action.sa_handler = SIG_IGN;
509 sigaction (SIGCHLD, &sig_chld_action, NULL);
511 if (daemonize)
512 {
513 if ((pid = fork ()) == -1)
514 {
515 /* error */
516 char errbuf[1024];
517 fprintf (stderr, "fork: %s",
518 sstrerror (errno, errbuf,
519 sizeof (errbuf)));
520 return (1);
521 }
522 else if (pid != 0)
523 {
524 /* parent */
525 /* printf ("Running (PID %i)\n", pid); */
526 return (0);
527 }
529 /* Detach from session */
530 setsid ();
532 /* Write pidfile */
533 if (pidfile_create ())
534 exit (2);
536 /* close standard descriptors */
537 close (2);
538 close (1);
539 close (0);
541 if (open ("/dev/null", O_RDWR) != 0)
542 {
543 ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
544 return (1);
545 }
546 if (dup (0) != 1)
547 {
548 ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
549 return (1);
550 }
551 if (dup (0) != 2)
552 {
553 ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
554 return (1);
555 }
556 } /* if (daemonize) */
557 #endif /* COLLECT_DAEMON */
559 memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
560 sig_pipe_action.sa_handler = SIG_IGN;
561 sigaction (SIGPIPE, &sig_pipe_action, NULL);
563 /*
564 * install signal handlers
565 */
566 memset (&sig_int_action, '\0', sizeof (sig_int_action));
567 sig_int_action.sa_handler = sig_int_handler;
568 if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
569 char errbuf[1024];
570 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
571 sstrerror (errno, errbuf, sizeof (errbuf)));
572 return (1);
573 }
575 memset (&sig_term_action, '\0', sizeof (sig_term_action));
576 sig_term_action.sa_handler = sig_term_handler;
577 if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
578 char errbuf[1024];
579 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
580 sstrerror (errno, errbuf, sizeof (errbuf)));
581 return (1);
582 }
584 memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
585 sig_usr1_action.sa_handler = sig_usr1_handler;
586 if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
587 char errbuf[1024];
588 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
589 sstrerror (errno, errbuf, sizeof (errbuf)));
590 return (1);
591 }
593 /*
594 * run the actual loops
595 */
596 do_init ();
598 if (test_readall)
599 {
600 if (plugin_read_all_once () != 0)
601 exit_status = 1;
602 }
603 else
604 {
605 INFO ("Initialization complete, entering read-loop.");
606 do_loop ();
607 }
609 /* close syslog */
610 INFO ("Exiting normally.");
612 do_shutdown ();
614 #if COLLECT_DAEMON
615 if (daemonize)
616 pidfile_remove ();
617 #endif /* COLLECT_DAEMON */
619 return (exit_status);
620 } /* int main */