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