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