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