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