Merge branch 'pr/2004'
[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
30 #include "common.h"
31 #include "plugin.h"
32 #include "configfile.h"
33
34 #include <sys/types.h>
35 #include <sys/un.h>
36 #include <netdb.h>
37
38 #if HAVE_LOCALE_H
39 # include <locale.h>
40 #endif
41
42 #if HAVE_STATGRAB_H
43 # include <statgrab.h>
44 #endif
45
46 #ifndef COLLECTD_LOCALE
47 # define COLLECTD_LOCALE "C"
48 #endif
49
50 /*
51  * Global variables
52  */
53 char hostname_g[DATA_MAX_NAME_LEN];
54 cdtime_t interval_g;
55 int  timeout_g;
56 #if HAVE_LIBKSTAT
57 kstat_ctl_t *kc;
58 #endif /* HAVE_LIBKSTAT */
59
60 static int loop = 0;
61
62 static void *do_flush (void __attribute__((unused)) *arg)
63 {
64         INFO ("Flushing all data.");
65         plugin_flush (/* plugin = */ NULL,
66                         /* timeout = */ 0,
67                         /* ident = */ NULL);
68         INFO ("Finished flushing all data.");
69         pthread_exit (NULL);
70         return NULL;
71 }
72
73 static void sig_int_handler (int __attribute__((unused)) signal)
74 {
75         loop++;
76 }
77
78 static void sig_term_handler (int __attribute__((unused)) signal)
79 {
80         loop++;
81 }
82
83 static void sig_usr1_handler (int __attribute__((unused)) signal)
84 {
85         pthread_t      thread;
86         pthread_attr_t attr;
87
88         /* flushing the data might take a while,
89          * so it should be done asynchronously */
90         pthread_attr_init (&attr);
91         pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
92         pthread_create (&thread, &attr, do_flush, NULL);
93         pthread_attr_destroy (&attr);
94 }
95
96 static int init_hostname (void)
97 {
98         const char *str;
99
100         struct addrinfo *ai_list;
101         int status;
102
103         str = global_option_get ("Hostname");
104         if ((str != NULL) && (str[0] != 0))
105         {
106                 sstrncpy (hostname_g, str, sizeof (hostname_g));
107                 return (0);
108         }
109
110         if (gethostname (hostname_g, sizeof (hostname_g)) != 0)
111         {
112                 fprintf (stderr, "`gethostname' failed and no "
113                                 "hostname was configured.\n");
114                 return (-1);
115         }
116
117         str = global_option_get ("FQDNLookup");
118         if (IS_FALSE (str))
119                 return (0);
120
121         struct addrinfo ai_hints = {
122                 .ai_flags = AI_CANONNAME
123         };
124
125         status = getaddrinfo (hostname_g, NULL, &ai_hints, &ai_list);
126         if (status != 0)
127         {
128                 ERROR ("Looking up \"%s\" failed. You have set the "
129                                 "\"FQDNLookup\" option, but I cannot resolve "
130                                 "my hostname to a fully qualified domain "
131                                 "name. Please fix the network "
132                                 "configuration.", hostname_g);
133                 return (-1);
134         }
135
136         for (struct addrinfo *ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
137         {
138                 if (ai_ptr->ai_canonname == NULL)
139                         continue;
140
141                 sstrncpy (hostname_g, ai_ptr->ai_canonname, sizeof (hostname_g));
142                 break;
143         }
144
145         freeaddrinfo (ai_list);
146         return (0);
147 } /* int init_hostname */
148
149 static int init_global_variables (void)
150 {
151         char const *str;
152
153         interval_g = cf_get_default_interval ();
154         assert (interval_g > 0);
155         DEBUG ("interval_g = %.3f;", CDTIME_T_TO_DOUBLE (interval_g));
156
157         str = global_option_get ("Timeout");
158         if (str == NULL)
159                 str = "2";
160         timeout_g = atoi (str);
161         if (timeout_g <= 1)
162         {
163                 fprintf (stderr, "Cannot set the timeout to a correct value.\n"
164                                 "Please check your settings.\n");
165                 return (-1);
166         }
167         DEBUG ("timeout_g = %i;", timeout_g);
168
169         if (init_hostname () != 0)
170                 return (-1);
171         DEBUG ("hostname_g = %s;", hostname_g);
172
173         return (0);
174 } /* int init_global_variables */
175
176 static int change_basedir (const char *orig_dir)
177 {
178         char *dir;
179         size_t dirlen;
180         int status;
181
182         dir = strdup (orig_dir);
183         if (dir == NULL)
184         {
185                 char errbuf[1024];
186                 ERROR ("strdup failed: %s",
187                                 sstrerror (errno, errbuf, sizeof (errbuf)));
188                 return (-1);
189         }
190
191         dirlen = strlen (dir);
192         while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
193                 dir[--dirlen] = '\0';
194
195         if (dirlen == 0) {
196                 free (dir);
197                 return (-1);
198         }
199
200         status = chdir (dir);
201         if (status == 0)
202         {
203                 free (dir);
204                 return (0);
205         }
206         else if (errno != ENOENT)
207         {
208                 char errbuf[1024];
209                 ERROR ("change_basedir: chdir (%s): %s", dir,
210                                 sstrerror (errno, errbuf, sizeof (errbuf)));
211                 free (dir);
212                 return (-1);
213         }
214
215         status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
216         if (status != 0)
217         {
218                 char errbuf[1024];
219                 ERROR ("change_basedir: mkdir (%s): %s", dir,
220                                 sstrerror (errno, errbuf, sizeof (errbuf)));
221                 free (dir);
222                 return (-1);
223         }
224
225         status = chdir (dir);
226         if (status != 0)
227         {
228                 char errbuf[1024];
229                 ERROR ("change_basedir: chdir (%s): %s", dir,
230                                 sstrerror (errno, errbuf, sizeof (errbuf)));
231                 free (dir);
232                 return (-1);
233         }
234
235         free (dir);
236         return (0);
237 } /* static int change_basedir (char *dir) */
238
239 #if HAVE_LIBKSTAT
240 static void update_kstat (void)
241 {
242         if (kc == NULL)
243         {
244                 if ((kc = kstat_open ()) == NULL)
245                         ERROR ("Unable to open kstat control structure");
246         }
247         else
248         {
249                 kid_t kid;
250                 kid = kstat_chain_update (kc);
251                 if (kid > 0)
252                 {
253                         INFO ("kstat chain has been updated");
254                         plugin_init_all ();
255                 }
256                 else if (kid < 0)
257                         ERROR ("kstat chain update failed");
258                 /* else: everything works as expected */
259         }
260
261         return;
262 } /* static void update_kstat (void) */
263 #endif /* HAVE_LIBKSTAT */
264
265 /* TODO
266  * Remove all settings but `-f' and `-C'
267  */
268 __attribute__((noreturn))
269 static void exit_usage (int status)
270 {
271         printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
272
273                         "Available options:\n"
274                         "  General:\n"
275                         "    -C <file>       Configuration file.\n"
276                         "                    Default: "CONFIGFILE"\n"
277                         "    -t              Test config and exit.\n"
278                         "    -T              Test plugin read and exit.\n"
279                         "    -P <file>       PID-file.\n"
280                         "                    Default: "PIDFILE"\n"
281 #if COLLECT_DAEMON
282                         "    -f              Don't fork to the background.\n"
283 #endif
284                         "    -h              Display help (this message)\n"
285                         "\nBuiltin defaults:\n"
286                         "  Config file       "CONFIGFILE"\n"
287                         "  PID file          "PIDFILE"\n"
288                         "  Plugin directory  "PLUGINDIR"\n"
289                         "  Data directory    "PKGLOCALSTATEDIR"\n"
290                         "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
291                         "by Florian octo Forster <octo@collectd.org>\n"
292                         "for contributions see `AUTHORS'\n");
293         exit (status);
294 } /* static void exit_usage (int status) */
295
296 static int do_init (void)
297 {
298 #if HAVE_SETLOCALE
299         if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
300                 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
301
302         /* Update the environment, so that libraries that are calling
303          * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
304         unsetenv ("LC_ALL");
305         setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
306 #endif
307
308 #if HAVE_LIBKSTAT
309         kc = NULL;
310         update_kstat ();
311 #endif
312
313 #if HAVE_LIBSTATGRAB
314         if (sg_init (
315 # if HAVE_LIBSTATGRAB_0_90
316                     0
317 # endif
318                     ))
319         {
320                 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
321                 return (-1);
322         }
323
324         if (sg_drop_privileges ())
325         {
326                 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
327                 return (-1);
328         }
329 #endif
330
331         return plugin_init_all ();
332 } /* int do_init () */
333
334
335 static int do_loop (void)
336 {
337         cdtime_t interval = cf_get_default_interval ();
338         cdtime_t wait_until;
339
340         wait_until = cdtime () + interval;
341
342         while (loop == 0)
343         {
344                 cdtime_t now;
345
346 #if HAVE_LIBKSTAT
347                 update_kstat ();
348 #endif
349
350                 /* Issue all plugins */
351                 plugin_read_all ();
352
353                 now = cdtime ();
354                 if (now >= wait_until)
355                 {
356                         WARNING ("Not sleeping because the next interval is "
357                                         "%.3f seconds in the past!",
358                                         CDTIME_T_TO_DOUBLE (now - wait_until));
359                         wait_until = now + interval;
360                         continue;
361                 }
362
363                 struct timespec ts_wait = CDTIME_T_TO_TIMESPEC (wait_until - now);
364                 wait_until = wait_until + interval;
365
366                 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
367                 {
368                         if (errno != EINTR)
369                         {
370                                 char errbuf[1024];
371                                 ERROR ("nanosleep failed: %s",
372                                                 sstrerror (errno, errbuf,
373                                                         sizeof (errbuf)));
374                                 return (-1);
375                         }
376                 }
377         } /* while (loop == 0) */
378
379         return (0);
380 } /* int do_loop */
381
382 static int do_shutdown (void)
383 {
384         return plugin_shutdown_all ();
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         if (file == NULL)
411                 return 0;
412
413         return (unlink (file));
414 } /* static int pidfile_remove (const char *file) */
415 #endif /* COLLECT_DAEMON */
416
417 #ifdef KERNEL_LINUX
418 static int notify_upstart (void)
419 {
420     char const *upstart_job = getenv("UPSTART_JOB");
421
422     if (upstart_job == NULL)
423         return 0;
424
425     if (strcmp(upstart_job, "collectd") != 0)
426     {
427         WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
428         return 0;
429     }
430
431     NOTICE("Upstart detected, stopping now to signal readyness.");
432     raise(SIGSTOP);
433     unsetenv("UPSTART_JOB");
434
435     return 1;
436 }
437
438 static int notify_systemd (void)
439 {
440     int                  fd;
441     const char          *notifysocket;
442     struct sockaddr_un   su = { 0 };
443     size_t               su_size;
444     char                 buffer[] = "READY=1\n";
445
446     notifysocket = getenv ("NOTIFY_SOCKET");
447     if (notifysocket == NULL)
448         return 0;
449
450     if ((strlen (notifysocket) < 2)
451         || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
452     {
453         ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
454         return 0;
455     }
456     NOTICE ("Systemd detected, trying to signal readyness.");
457
458     unsetenv ("NOTIFY_SOCKET");
459
460 #if defined(SOCK_CLOEXEC)
461     fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
462 #else
463     fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
464 #endif
465     if (fd < 0) {
466         char errbuf[1024];
467         ERROR ("creating UNIX socket failed: %s",
468                  sstrerror (errno, errbuf, sizeof (errbuf)));
469         return 0;
470     }
471
472     su.sun_family = AF_UNIX;
473     if (notifysocket[0] != '@')
474     {
475         /* regular UNIX socket */
476         sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
477         su_size = sizeof (su);
478     }
479     else
480     {
481         /* Linux abstract namespace socket: specify address as "\0foo", i.e.
482          * start with a null byte. Since null bytes have no special meaning in
483          * that case, we have to set su_size correctly to cover only the bytes
484          * that are part of the address. */
485         sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
486         su.sun_path[0] = 0;
487         su_size = sizeof (sa_family_t) + strlen (notifysocket);
488         if (su_size > sizeof (su))
489             su_size = sizeof (su);
490     }
491
492     if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
493     {
494         char errbuf[1024];
495         ERROR ("sendto(\"%s\") failed: %s", notifysocket,
496                  sstrerror (errno, errbuf, sizeof (errbuf)));
497         close(fd);
498         return 0;
499     }
500
501     unsetenv ("NOTIFY_SOCKET");
502     close(fd);
503     return 1;
504 }
505 #endif /* KERNEL_LINUX */
506
507 int main (int argc, char **argv)
508 {
509         const char *configfile = CONFIGFILE;
510         int test_config  = 0;
511         int test_readall = 0;
512         const char *basedir;
513 #if COLLECT_DAEMON
514         pid_t pid;
515         int daemonize    = 1;
516 #endif
517         int exit_status = 0;
518
519         /* read options */
520         while (1)
521         {
522                 int c;
523
524                 c = getopt (argc, argv, "htTC:"
525 #if COLLECT_DAEMON
526                                 "fP:"
527 #endif
528                 );
529
530                 if (c == -1)
531                         break;
532
533                 switch (c)
534                 {
535                         case 'C':
536                                 configfile = optarg;
537                                 break;
538                         case 't':
539                                 test_config = 1;
540                                 break;
541                         case 'T':
542                                 test_readall = 1;
543                                 global_option_set ("ReadThreads", "-1", 1);
544 #if COLLECT_DAEMON
545                                 daemonize = 0;
546 #endif /* COLLECT_DAEMON */
547                                 break;
548 #if COLLECT_DAEMON
549                         case 'P':
550                                 global_option_set ("PIDFile", optarg, 1);
551                                 break;
552                         case 'f':
553                                 daemonize = 0;
554                                 break;
555 #endif /* COLLECT_DAEMON */
556                         case 'h':
557                                 exit_usage (0);
558                                 break;
559                         default:
560                                 exit_usage (1);
561                 } /* switch (c) */
562         } /* while (1) */
563
564         if (optind < argc)
565                 exit_usage (1);
566
567         plugin_init_ctx ();
568
569         /*
570          * Read options from the config file, the environment and the command
571          * line (in that order, with later options overwriting previous ones in
572          * general).
573          * Also, this will automatically load modules.
574          */
575         if (cf_read (configfile))
576         {
577                 fprintf (stderr, "Error: Reading the config file failed!\n"
578                                 "Read the syslog for details.\n");
579                 return (1);
580         }
581
582         /*
583          * Change directory. We do this _after_ reading the config and loading
584          * modules to relative paths work as expected.
585          */
586         if ((basedir = global_option_get ("BaseDir")) == NULL)
587         {
588                 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
589                 return (1);
590         }
591         else if (change_basedir (basedir))
592         {
593                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
594                 return (1);
595         }
596
597         /*
598          * Set global variables or, if that failes, exit. We cannot run with
599          * them being uninitialized. If nothing is configured, then defaults
600          * are being used. So this means that the user has actually done
601          * something wrong.
602          */
603         if (init_global_variables () != 0)
604                 exit (EXIT_FAILURE);
605
606         if (test_config)
607                 return (0);
608
609 #if COLLECT_DAEMON
610         /*
611          * fork off child
612          */
613         struct sigaction sig_chld_action = {
614                 .sa_handler = SIG_IGN
615         };
616
617         sigaction (SIGCHLD, &sig_chld_action, NULL);
618
619     /*
620      * Only daemonize if we're not being supervised
621      * by upstart or systemd (when using Linux).
622      */
623         if (daemonize
624 #ifdef KERNEL_LINUX
625             && notify_upstart() == 0 && notify_systemd() == 0
626 #endif
627         )
628         {
629                 int status;
630
631                 if ((pid = fork ()) == -1)
632                 {
633                         /* error */
634                         char errbuf[1024];
635                         fprintf (stderr, "fork: %s",
636                                         sstrerror (errno, errbuf,
637                                                 sizeof (errbuf)));
638                         return (1);
639                 }
640                 else if (pid != 0)
641                 {
642                         /* parent */
643                         /* printf ("Running (PID %i)\n", pid); */
644                         return (0);
645                 }
646
647                 /* Detach from session */
648                 setsid ();
649
650                 /* Write pidfile */
651                 if (pidfile_create ())
652                         exit (2);
653
654                 /* close standard descriptors */
655                 close (2);
656                 close (1);
657                 close (0);
658
659                 status = open ("/dev/null", O_RDWR);
660                 if (status != 0)
661                 {
662                         ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
663                         return (1);
664                 }
665
666                 status = dup (0);
667                 if (status != 1)
668                 {
669                         ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
670                         return (1);
671                 }
672
673                 status = dup (0);
674                 if (status != 2)
675                 {
676                         ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
677                         return (1);
678                 }
679         } /* if (daemonize) */
680 #endif /* COLLECT_DAEMON */
681
682         struct sigaction sig_pipe_action = {
683                 .sa_handler = SIG_IGN
684         };
685
686         sigaction (SIGPIPE, &sig_pipe_action, NULL);
687
688         /*
689          * install signal handlers
690          */
691         struct sigaction sig_int_action = {
692                 .sa_handler = sig_int_handler
693         };
694
695         if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
696                 char errbuf[1024];
697                 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
698                                 sstrerror (errno, errbuf, sizeof (errbuf)));
699                 return (1);
700         }
701
702         struct sigaction sig_term_action = {
703                 .sa_handler = sig_term_handler
704         };
705
706         if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
707                 char errbuf[1024];
708                 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
709                                 sstrerror (errno, errbuf, sizeof (errbuf)));
710                 return (1);
711         }
712
713         struct sigaction sig_usr1_action = {
714                 .sa_handler = sig_usr1_handler
715         };
716
717         if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
718                 char errbuf[1024];
719                 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
720                                 sstrerror (errno, errbuf, sizeof (errbuf)));
721                 return (1);
722         }
723
724         /*
725          * run the actual loops
726          */
727         if (do_init () != 0)
728         {
729                 ERROR ("Error: one or more plugin init callbacks failed.");
730                 exit_status = 1;
731         }
732
733         if (test_readall)
734         {
735                 if (plugin_read_all_once () != 0)
736                 {
737                         ERROR ("Error: one or more plugin read callbacks failed.");
738                         exit_status = 1;
739                 }
740         }
741         else
742         {
743                 INFO ("Initialization complete, entering read-loop.");
744                 do_loop ();
745         }
746
747         /* close syslog */
748         INFO ("Exiting normally.");
749
750         if (do_shutdown () != 0)
751         {
752                 ERROR ("Error: one or more plugin shutdown callbacks failed.");
753                 exit_status = 1;
754         }
755
756 #if COLLECT_DAEMON
757         if (daemonize)
758                 pidfile_remove ();
759 #endif /* COLLECT_DAEMON */
760
761         return (exit_status);
762 } /* int main */