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