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