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