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