Merge branch 'collectd-5.5'
[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/un.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                 free (dir);
201                 return (-1);
202         }
203
204         status = chdir (dir);
205         if (status == 0)
206         {
207                 free (dir);
208                 return (0);
209         }
210         else if (errno != ENOENT)
211         {
212                 char errbuf[1024];
213                 ERROR ("change_basedir: chdir (%s): %s", dir,
214                                 sstrerror (errno, errbuf, sizeof (errbuf)));
215                 free (dir);
216                 return (-1);
217         }
218
219         status = mkdir (dir, S_IRWXU | S_IRWXG | S_IRWXO);
220         if (status != 0)
221         {
222                 char errbuf[1024];
223                 ERROR ("change_basedir: mkdir (%s): %s", dir,
224                                 sstrerror (errno, errbuf, sizeof (errbuf)));
225                 free (dir);
226                 return (-1);
227         }
228
229         status = chdir (dir);
230         if (status != 0)
231         {
232                 char errbuf[1024];
233                 ERROR ("change_basedir: chdir (%s): %s", dir,
234                                 sstrerror (errno, errbuf, sizeof (errbuf)));
235                 free (dir);
236                 return (-1);
237         }
238
239         free (dir);
240         return (0);
241 } /* static int change_basedir (char *dir) */
242
243 #if HAVE_LIBKSTAT
244 static void update_kstat (void)
245 {
246         if (kc == NULL)
247         {
248                 if ((kc = kstat_open ()) == NULL)
249                         ERROR ("Unable to open kstat control structure");
250         }
251         else
252         {
253                 kid_t kid;
254                 kid = kstat_chain_update (kc);
255                 if (kid > 0)
256                 {
257                         INFO ("kstat chain has been updated");
258                         plugin_init_all ();
259                 }
260                 else if (kid < 0)
261                         ERROR ("kstat chain update failed");
262                 /* else: everything works as expected */
263         }
264
265         return;
266 } /* static void update_kstat (void) */
267 #endif /* HAVE_LIBKSTAT */
268
269 /* TODO
270  * Remove all settings but `-f' and `-C'
271  */
272 static void exit_usage (int status)
273 {
274         printf ("Usage: "PACKAGE_NAME" [OPTIONS]\n\n"
275
276                         "Available options:\n"
277                         "  General:\n"
278                         "    -C <file>       Configuration file.\n"
279                         "                    Default: "CONFIGFILE"\n"
280                         "    -t              Test config and exit.\n"
281                         "    -T              Test plugin read and exit.\n"
282                         "    -P <file>       PID-file.\n"
283                         "                    Default: "PIDFILE"\n"
284 #if COLLECT_DAEMON
285                         "    -f              Don't fork to the background.\n"
286 #endif
287                         "    -h              Display help (this message)\n"
288                         "\nBuiltin defaults:\n"
289                         "  Config file       "CONFIGFILE"\n"
290                         "  PID file          "PIDFILE"\n"
291                         "  Plugin directory  "PLUGINDIR"\n"
292                         "  Data directory    "PKGLOCALSTATEDIR"\n"
293                         "\n"PACKAGE_NAME" "PACKAGE_VERSION", http://collectd.org/\n"
294                         "by Florian octo Forster <octo@collectd.org>\n"
295                         "for contributions see `AUTHORS'\n");
296         exit (status);
297 } /* static void exit_usage (int status) */
298
299 static int do_init (void)
300 {
301 #if HAVE_SETLOCALE
302         if (setlocale (LC_NUMERIC, COLLECTD_LOCALE) == NULL)
303                 WARNING ("setlocale (\"%s\") failed.", COLLECTD_LOCALE);
304
305         /* Update the environment, so that libraries that are calling
306          * setlocale(LC_NUMERIC, "") don't accidentally revert these changes. */
307         unsetenv ("LC_ALL");
308         setenv ("LC_NUMERIC", COLLECTD_LOCALE, /* overwrite = */ 1);
309 #endif
310
311 #if HAVE_LIBKSTAT
312         kc = NULL;
313         update_kstat ();
314 #endif
315
316 #if HAVE_LIBSTATGRAB
317         if (sg_init (
318 # if HAVE_LIBSTATGRAB_0_90
319                     0
320 # endif
321                     ))
322         {
323                 ERROR ("sg_init: %s", sg_str_error (sg_get_error ()));
324                 return (-1);
325         }
326
327         if (sg_drop_privileges ())
328         {
329                 ERROR ("sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
330                 return (-1);
331         }
332 #endif
333
334         plugin_init_all ();
335
336         return (0);
337 } /* int do_init () */
338
339
340 static int do_loop (void)
341 {
342         cdtime_t interval = cf_get_default_interval ();
343         cdtime_t wait_until;
344
345         wait_until = cdtime () + interval;
346
347         while (loop == 0)
348         {
349                 struct timespec ts_wait = { 0, 0 };
350                 cdtime_t now;
351
352 #if HAVE_LIBKSTAT
353                 update_kstat ();
354 #endif
355
356                 /* Issue all plugins */
357                 plugin_read_all ();
358
359                 now = cdtime ();
360                 if (now >= wait_until)
361                 {
362                         WARNING ("Not sleeping because the next interval is "
363                                         "%.3f seconds in the past!",
364                                         CDTIME_T_TO_DOUBLE (now - wait_until));
365                         wait_until = now + interval;
366                         continue;
367                 }
368
369                 CDTIME_T_TO_TIMESPEC (wait_until - now, &ts_wait);
370                 wait_until = wait_until + interval;
371
372                 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) != 0))
373                 {
374                         if (errno != EINTR)
375                         {
376                                 char errbuf[1024];
377                                 ERROR ("nanosleep failed: %s",
378                                                 sstrerror (errno, errbuf,
379                                                         sizeof (errbuf)));
380                                 return (-1);
381                         }
382                 }
383         } /* while (loop == 0) */
384
385         return (0);
386 } /* int do_loop */
387
388 static int do_shutdown (void)
389 {
390         plugin_shutdown_all ();
391         return (0);
392 } /* int do_shutdown */
393
394 #if COLLECT_DAEMON
395 static int pidfile_create (void)
396 {
397         FILE *fh;
398         const char *file = global_option_get ("PIDFile");
399
400         if ((fh = fopen (file, "w")) == NULL)
401         {
402                 char errbuf[1024];
403                 ERROR ("fopen (%s): %s", file,
404                                 sstrerror (errno, errbuf, sizeof (errbuf)));
405                 return (1);
406         }
407
408         fprintf (fh, "%i\n", (int) getpid ());
409         fclose(fh);
410
411         return (0);
412 } /* static int pidfile_create (const char *file) */
413
414 static int pidfile_remove (void)
415 {
416         const char *file = global_option_get ("PIDFile");
417         if (file == NULL)
418                 return 0;
419
420         return (unlink (file));
421 } /* static int pidfile_remove (const char *file) */
422 #endif /* COLLECT_DAEMON */
423
424 #ifdef KERNEL_LINUX
425 static int notify_upstart (void)
426 {
427     char const *upstart_job = getenv("UPSTART_JOB");
428
429     if (upstart_job == NULL)
430         return 0;
431
432     if (strcmp(upstart_job, "collectd") != 0)
433     {
434         WARNING ("Environment specifies unexpected UPSTART_JOB=\"%s\", expected \"collectd\". Ignoring the variable.", upstart_job);
435         return 0;
436     }
437
438     NOTICE("Upstart detected, stopping now to signal readyness.");
439     raise(SIGSTOP);
440     unsetenv("UPSTART_JOB");
441
442     return 1;
443 }
444
445 static int notify_systemd (void)
446 {
447     int                  fd;
448     const char          *notifysocket;
449     struct sockaddr_un   su;
450     size_t               su_size;
451     char                 buffer[] = "READY=1\n";
452
453     notifysocket = getenv ("NOTIFY_SOCKET");
454     if (notifysocket == NULL)
455         return 0;
456
457     if ((strlen (notifysocket) < 2)
458         || ((notifysocket[0] != '@') && (notifysocket[0] != '/')))
459     {
460         ERROR ("invalid notification socket NOTIFY_SOCKET=\"%s\": path must be absolute", notifysocket);
461         return 0;
462     }
463     NOTICE ("Systemd detected, trying to signal readyness.");
464
465     unsetenv ("NOTIFY_SOCKET");
466
467 #if defined(SOCK_CLOEXEC)
468     fd = socket (AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, /* protocol = */ 0);
469 #else
470     fd = socket (AF_UNIX, SOCK_DGRAM, /* protocol = */ 0);
471 #endif
472     if (fd < 0) {
473         char errbuf[1024];
474         ERROR ("creating UNIX socket failed: %s",
475                  sstrerror (errno, errbuf, sizeof (errbuf)));
476         return 0;
477     }
478
479     memset (&su, 0, sizeof (su));
480     su.sun_family = AF_UNIX;
481     if (notifysocket[0] != '@')
482     {
483         /* regular UNIX socket */
484         sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
485         su_size = sizeof (su);
486     }
487     else
488     {
489         /* Linux abstract namespace socket: specify address as "\0foo", i.e.
490          * start with a null byte. Since null bytes have no special meaning in
491          * that case, we have to set su_size correctly to cover only the bytes
492          * that are part of the address. */
493         sstrncpy (su.sun_path, notifysocket, sizeof (su.sun_path));
494         su.sun_path[0] = 0;
495         su_size = sizeof (sa_family_t) + strlen (notifysocket);
496         if (su_size > sizeof (su))
497             su_size = sizeof (su);
498     }
499
500     if (sendto (fd, buffer, strlen (buffer), MSG_NOSIGNAL, (void *) &su, (socklen_t) su_size) < 0)
501     {
502         char errbuf[1024];
503         ERROR ("sendto(\"%s\") failed: %s", notifysocket,
504                  sstrerror (errno, errbuf, sizeof (errbuf)));
505         close(fd);
506         return 0;
507     }
508
509     unsetenv ("NOTIFY_SOCKET");
510     close(fd);
511     return 1;
512 }
513 #endif /* KERNEL_LINUX */
514
515 int main (int argc, char **argv)
516 {
517         struct sigaction sig_int_action;
518         struct sigaction sig_term_action;
519         struct sigaction sig_usr1_action;
520         struct sigaction sig_pipe_action;
521         char *configfile = CONFIGFILE;
522         int test_config  = 0;
523         int test_readall = 0;
524         const char *basedir;
525 #if COLLECT_DAEMON
526         struct sigaction sig_chld_action;
527         pid_t pid;
528         int daemonize    = 1;
529 #endif
530         int exit_status = 0;
531
532         /* read options */
533         while (1)
534         {
535                 int c;
536
537                 c = getopt (argc, argv, "htTC:"
538 #if COLLECT_DAEMON
539                                 "fP:"
540 #endif
541                 );
542
543                 if (c == -1)
544                         break;
545
546                 switch (c)
547                 {
548                         case 'C':
549                                 configfile = optarg;
550                                 break;
551                         case 't':
552                                 test_config = 1;
553                                 break;
554                         case 'T':
555                                 test_readall = 1;
556                                 global_option_set ("ReadThreads", "-1");
557 #if COLLECT_DAEMON
558                                 daemonize = 0;
559 #endif /* COLLECT_DAEMON */
560                                 break;
561 #if COLLECT_DAEMON
562                         case 'P':
563                                 global_option_set ("PIDFile", optarg);
564                                 pidfile_from_cli = 1;
565                                 break;
566                         case 'f':
567                                 daemonize = 0;
568                                 break;
569 #endif /* COLLECT_DAEMON */
570                         case 'h':
571                                 exit_usage (0);
572                                 break;
573                         default:
574                                 exit_usage (1);
575                 } /* switch (c) */
576         } /* while (1) */
577
578         if (optind < argc)
579                 exit_usage (1);
580
581         plugin_init_ctx ();
582
583         /*
584          * Read options from the config file, the environment and the command
585          * line (in that order, with later options overwriting previous ones in
586          * general).
587          * Also, this will automatically load modules.
588          */
589         if (cf_read (configfile))
590         {
591                 fprintf (stderr, "Error: Reading the config file failed!\n"
592                                 "Read the syslog for details.\n");
593                 return (1);
594         }
595
596         /*
597          * Change directory. We do this _after_ reading the config and loading
598          * modules to relative paths work as expected.
599          */
600         if ((basedir = global_option_get ("BaseDir")) == NULL)
601         {
602                 fprintf (stderr, "Don't have a basedir to use. This should not happen. Ever.");
603                 return (1);
604         }
605         else if (change_basedir (basedir))
606         {
607                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", basedir);
608                 return (1);
609         }
610
611         /*
612          * Set global variables or, if that failes, exit. We cannot run with
613          * them being uninitialized. If nothing is configured, then defaults
614          * are being used. So this means that the user has actually done
615          * something wrong.
616          */
617         if (init_global_variables () != 0)
618                 return (1);
619
620         if (test_config)
621                 return (0);
622
623 #if COLLECT_DAEMON
624         /*
625          * fork off child
626          */
627         memset (&sig_chld_action, '\0', sizeof (sig_chld_action));
628         sig_chld_action.sa_handler = SIG_IGN;
629         sigaction (SIGCHLD, &sig_chld_action, NULL);
630
631     /*
632      * Only daemonize if we're not being supervised
633      * by upstart or systemd (when using Linux).
634      */
635         if (daemonize
636 #ifdef KERNEL_LINUX
637             && notify_upstart() == 0 && notify_systemd() == 0
638 #endif
639         )
640         {
641                 int status;
642
643                 if ((pid = fork ()) == -1)
644                 {
645                         /* error */
646                         char errbuf[1024];
647                         fprintf (stderr, "fork: %s",
648                                         sstrerror (errno, errbuf,
649                                                 sizeof (errbuf)));
650                         return (1);
651                 }
652                 else if (pid != 0)
653                 {
654                         /* parent */
655                         /* printf ("Running (PID %i)\n", pid); */
656                         return (0);
657                 }
658
659                 /* Detach from session */
660                 setsid ();
661
662                 /* Write pidfile */
663                 if (pidfile_create ())
664                         exit (2);
665
666                 /* close standard descriptors */
667                 close (2);
668                 close (1);
669                 close (0);
670
671                 status = open ("/dev/null", O_RDWR);
672                 if (status != 0)
673                 {
674                         ERROR ("Error: Could not connect `STDIN' to `/dev/null' (status %d)", status);
675                         return (1);
676                 }
677
678                 status = dup (0);
679                 if (status != 1)
680                 {
681                         ERROR ("Error: Could not connect `STDOUT' to `/dev/null' (status %d)", status);
682                         return (1);
683                 }
684
685                 status = dup (0);
686                 if (status != 2)
687                 {
688                         ERROR ("Error: Could not connect `STDERR' to `/dev/null', (status %d)", status);
689                         return (1);
690                 }
691         } /* if (daemonize) */
692 #endif /* COLLECT_DAEMON */
693
694         memset (&sig_pipe_action, '\0', sizeof (sig_pipe_action));
695         sig_pipe_action.sa_handler = SIG_IGN;
696         sigaction (SIGPIPE, &sig_pipe_action, NULL);
697
698         /*
699          * install signal handlers
700          */
701         memset (&sig_int_action, '\0', sizeof (sig_int_action));
702         sig_int_action.sa_handler = sig_int_handler;
703         if (0 != sigaction (SIGINT, &sig_int_action, NULL)) {
704                 char errbuf[1024];
705                 ERROR ("Error: Failed to install a signal handler for signal INT: %s",
706                                 sstrerror (errno, errbuf, sizeof (errbuf)));
707                 return (1);
708         }
709
710         memset (&sig_term_action, '\0', sizeof (sig_term_action));
711         sig_term_action.sa_handler = sig_term_handler;
712         if (0 != sigaction (SIGTERM, &sig_term_action, NULL)) {
713                 char errbuf[1024];
714                 ERROR ("Error: Failed to install a signal handler for signal TERM: %s",
715                                 sstrerror (errno, errbuf, sizeof (errbuf)));
716                 return (1);
717         }
718
719         memset (&sig_usr1_action, '\0', sizeof (sig_usr1_action));
720         sig_usr1_action.sa_handler = sig_usr1_handler;
721         if (0 != sigaction (SIGUSR1, &sig_usr1_action, NULL)) {
722                 char errbuf[1024];
723                 ERROR ("Error: Failed to install a signal handler for signal USR1: %s",
724                                 sstrerror (errno, errbuf, sizeof (errbuf)));
725                 return (1);
726         }
727
728         /*
729          * run the actual loops
730          */
731         do_init ();
732
733         if (test_readall)
734         {
735                 if (plugin_read_all_once () != 0)
736                         exit_status = 1;
737         }
738         else
739         {
740                 INFO ("Initialization complete, entering read-loop.");
741                 do_loop ();
742         }
743
744         /* close syslog */
745         INFO ("Exiting normally.");
746
747         do_shutdown ();
748
749 #if COLLECT_DAEMON
750         if (daemonize)
751                 pidfile_remove ();
752 #endif /* COLLECT_DAEMON */
753
754         return (exit_status);
755 } /* int main */