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