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