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