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