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