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