Merge remote-tracking branch 'github/pr/734'
[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         {
312                 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
313                 return (-1);
314         }
315
316         if (sg_drop_privileges ())
317         {
318                 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
319                 return (-1);
320         }
321 #endif
322
323         plugin_init_all ();
324
325         return (0);
326 } /* int do_init () */
327
328
329 static int do_loop (void)
330 {
331         cdtime_t interval = cf_get_default_interval ();
332         cdtime_t wait_until;
333
334         wait_until = cdtime () + interval;
335
336         while (loop == 0)
337         {
338                 struct timespec ts_wait = { 0, 0 };
339                 cdtime_t now;
340
341 #if HAVE_LIBKSTAT
342                 update_kstat ();
343 #endif
344
345                 /* Issue all plugins */
346                 plugin_read_all ();
347
348                 now = cdtime ();
349                 if (now >= wait_until)
350                 {
351                         WARNING ("Not sleeping because the next interval is "
352                                         "%.3f seconds in the past!",
353                                         CDTIME_T_TO_DOUBLE (now - wait_until));
354                         wait_until = now + interval;
355                         continue;
356                 }
357
358                 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
359                 wait_until = wait_until + interval;
360
361                 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
362                 {
363                         if (errno != EINTR)
364                         {
365                                 char errbuf[1024];
366                                 ERROR ("nanosleep failed: %s",
367                                                 sstrerror (errno, errbuf,
368                                                         sizeof (errbuf)));
369                                 return (-1);
370                         }
371                 }
372         } /* while (loop == 0) */
373
374         return (0);
375 } /* int do_loop */
376
377 static int do_shutdown (void)
378 {
379         plugin_shutdown_all ();
380         return (0);
381 } /* int do_shutdown */
382
383 #if COLLECT_DAEMON
384 static int pidfile_create (void)
385 {
386         FILE *fh;
387         const char *file = global_option_get ("PIDFile");
388
389         if ((fh = fopen (file, "w")) == NULL)
390         {
391                 char errbuf[1024];
392                 ERROR ("fopen (%s): %s", file,
393                                 sstrerror (errno, errbuf, sizeof (errbuf)));
394                 return (1);
395         }
396
397         fprintf (fh, "%i\n", (int) getpid ());
398         fclose(fh);
399
400         return (0);
401 } /* static int pidfile_create (const char *file) */
402
403 static int pidfile_remove (void)
404 {
405         const char *file = global_option_get ("PIDFile");
406
407         DEBUG ("unlink (%s)", (file != NULL) ? file : "<null>");
408         return (unlink (file));
409 } /* static int pidfile_remove (const char *file) */
410 #endif /* COLLECT_DAEMON */
411
412 int main (int argc, char **argv)
413 {
414         struct sigaction sig_int_action;
415         struct sigaction sig_term_action;
416         struct sigaction sig_usr1_action;
417         struct sigaction sig_pipe_action;
418         char *configfile = CONFIGFILE;
419         int test_config  = 0;
420         int test_readall = 0;
421         const char *basedir;
422 #if COLLECT_DAEMON
423         struct sigaction sig_chld_action;
424         pid_t pid;
425         int daemonize    = 1;
426 #endif
427         int exit_status = 0;
428
429         /* read options */
430         while (1)
431         {
432                 int c;
433
434                 c = getopt (argc, argv, "htTC:"
435 #if COLLECT_DAEMON
436                                 "fP:"
437 #endif
438                 );
439
440                 if (c == -1)
441                         break;
442
443                 switch (c)
444                 {
445                         case 'C':
446                                 configfile = optarg;
447                                 break;
448                         case 't':
449                                 test_config = 1;
450                                 break;
451                         case 'T':
452                                 test_readall = 1;
453                                 global_option_set ("ReadThreads", "-1");
454 #if COLLECT_DAEMON
455                                 daemonize = 0;
456 #endif /* COLLECT_DAEMON */
457                                 break;
458 #if COLLECT_DAEMON
459                         case 'P':
460                                 global_option_set ("PIDFile", optarg);
461                                 pidfile_from_cli = 1;
462                                 break;
463                         case 'f':
464                                 daemonize = 0;
465                                 break;
466 #endif /* COLLECT_DAEMON */
467                         case 'h':
468                                 exit_usage (0);
469                                 break;
470                         default:
471                                 exit_usage (1);
472                 } /* switch (c) */
473         } /* while (1) */
474
475         if (optind < argc)
476                 exit_usage (1);
477
478         plugin_init_ctx ();
479
480         /*
481          * Read options from the config file, the environment and the command
482          * line (in that order, with later options overwriting previous ones in
483          * general).
484          * Also, this will automatically load modules.
485          */
486         if (cf_read (configfile))
487         {
488                 fprintf (stderr, "Error: Reading the config file failed!\n"
489                                 "Read the syslog for details.\n");
490                 return (1);
491         }
492
493         /*
494          * Change directory. We do this _after_ reading the config and loading
495          * modules to relative paths work as expected.
496          */
497         if ((basedir = global_option_get ("BaseDir")) == NULL)
498         {
499                 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
500                 return (1);
501         }
502         else if (change_basedir (basedir))
503         {
504                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
505                 return (1);
506         }
507
508         /*
509          * Set global variables or, if that failes, exit. We cannot run with
510          * them being uninitialized. If nothing is configured, then defaults
511          * are being used. So this means that the user has actually done
512          * something wrong.
513          */
514         if (init_global_variables () != 0)
515                 return (1);
516
517         if (test_config)
518                 return (0);
519
520 #if COLLECT_DAEMON
521         /*
522          * fork off child
523          */
524         memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
525         sig_chld_action.sa_handler = SIG_IGN;
526         sigaction (SIGCHLD, &sig_chld_action, NULL);
527
528         if (daemonize)
529         {
530                 if ((pid = fork ()) == -1)
531                 {
532                         /* error */
533                         char errbuf[1024];
534                         fprintf (stderr, "fork: %s",
535                                         sstrerror (errno, errbuf,
536                                                 sizeof (errbuf)));
537                         return (1);
538                 }
539                 else if (pid != 0)
540                 {
541                         /* parent */
542                         /* printf ("Running (PID %i)\n", pid); */
543                         return (0);
544                 }
545
546                 /* Detach from session */
547                 setsid ();
548
549                 /* Write pidfile */
550                 if (pidfile_create ())
551                         exit (2);
552
553                 /* close standard descriptors */
554                 close (2);
555                 close (1);
556                 close (0);
557
558                 if (open ("/dev/null", O_RDWR) != 0)
559                 {
560                         ERROR ("Error: Could not connect `STDIN' to `/dev/null'");
561                         return (1);
562                 }
563                 if (dup (0) != 1)
564                 {
565                         ERROR ("Error: Could not connect `STDOUT' to `/dev/null'");
566                         return (1);
567                 }
568                 if (dup (0) != 2)
569                 {
570                         ERROR ("Error: Could not connect `STDERR' to `/dev/null'");
571                         return (1);
572                 }
573         } /* if (daemonize) */
574 #endif /* COLLECT_DAEMON */
575
576         memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
577         sig_pipe_action.sa_handler = SIG_IGN;
578         sigaction (SIGPIPE, &sig_pipe_action, NULL);
579
580         /*
581          * install signal handlers
582          */
583         memset (&sig_int_action, '\0', sizeof (sig_int_action));
584         sig_int_action.sa_handler = sig_int_handler;
585         if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
586                 char errbuf[1024];
587                 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
588                                 sstrerror (errno, errbuf, sizeof (errbuf)));
589                 return (1);
590         }
591
592         memset (&sig_term_action, '\0', sizeof (sig_term_action));
593         sig_term_action.sa_handler = sig_term_handler;
594         if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
595                 char errbuf[1024];
596                 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
597                                 sstrerror (errno, errbuf, sizeof (errbuf)));
598                 return (1);
599         }
600
601         memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
602         sig_usr1_action.sa_handler = sig_usr1_handler;
603         if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
604                 char errbuf[1024];
605                 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
606                                 sstrerror (errno, errbuf, sizeof (errbuf)));
607                 return (1);
608         }
609
610         /*
611          * run the actual loops
612          */
613         do_init ();
614
615         if (test_readall)
616         {
617                 if (plugin_read_all_once () != 0)
618                         exit_status = 1;
619         }
620         else
621         {
622                 INFO ("Initialization complete, entering read-loop.");
623                 do_loop ();
624         }
625
626         /* close syslog */
627         INFO ("Exiting normally.");
628
629         do_shutdown ();
630
631 #if COLLECT_DAEMON
632         if (daemonize)
633                 pidfile_remove ();
634 #endif /* COLLECT_DAEMON */
635
636         return (exit_status);
637 } /* int main */