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