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