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