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