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