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