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