svn merge -r523:547 branches/config-step trunk
[collectd.git] / src / collectd.c
1 /**
2  * collectd - src/collectd.c
3  * Copyright (C) 2005  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; either version 2 of the License, or (at your
8  * option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
18  *
19  * Authors:
20  *   Florian octo Forster <octo at verplant.org>
21  *   Alvaro Barcellos <alvaro.barcellos at gmail.com>
22  **/
23
24 #include "collectd.h"
25 #include "common.h"
26 #include "utils_debug.h"
27
28 #include "network.h"
29 #include "plugin.h"
30 #include "configfile.h"
31
32 #include "ping.h"
33
34 static int loop = 0;
35
36 #if HAVE_LIBKSTAT
37 kstat_ctl_t *kc;
38 #endif /* HAVE_LIBKSTAT */
39
40 /*
41  * exported variables
42  */
43 time_t curtime;
44
45 #if HAVE_LIBRRD
46 int operating_mode;
47 #endif
48
49 static void sigIntHandler (int signal)
50 {
51         loop++;
52 }
53
54 static void sigTermHandler (int signal)
55 {
56         loop++;
57 }
58
59 static int change_basedir (char *dir)
60 {
61         int dirlen = strlen (dir);
62         
63         while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
64                 dir[--dirlen] = '\0';
65
66         if (dirlen <= 0)
67                 return (-1);
68
69         if (chdir (dir) == -1)
70         {
71                 if (errno == ENOENT)
72                 {
73                         if (mkdir (dir, 0755) == -1)
74                         {
75                                 syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
76                                 return (-1);
77                         }
78                         else if (chdir (dir) == -1)
79                         {
80                                 syslog (LOG_ERR, "chdir (%s): %s", dir, strerror (errno));
81                                 return (-1);
82                         }
83                 }
84                 else
85                 {
86                         syslog (LOG_ERR, "chdir: %s", strerror (errno));
87                         return (-1);
88                 }
89         }
90
91         return (0);
92 } /* static int change_basedir (char *dir) */
93
94 #if HAVE_LIBKSTAT
95 static void update_kstat (void)
96 {
97         if (kc == NULL)
98         {
99                 if ((kc = kstat_open ()) == NULL)
100                         syslog (LOG_ERR, "Unable to open kstat control structure");
101         }
102         else
103         {
104                 kid_t kid;
105                 kid = kstat_chain_update (kc);
106                 if (kid > 0)
107                 {
108                         syslog (LOG_INFO, "kstat chain has been updated");
109                         plugin_init_all ();
110                 }
111                 else if (kid < 0)
112                         syslog (LOG_ERR, "kstat chain update failed");
113                 /* else: everything works as expected */
114         }
115
116         return;
117 } /* static void update_kstat (void) */
118 #endif /* HAVE_LIBKSTAT */
119
120 /* TODO
121  * Remove all settings but `-f' and `-C'
122  */
123 static void exit_usage (char *name)
124 {
125         printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
126                         
127                         "Available options:\n"
128                         "  General:\n"
129                         "    -C <file>       Configuration file.\n"
130                         "                    Default: "CONFIGFILE"\n"
131 #if COLLECT_DAEMON
132                         "    -f              Don't fork to the background.\n"
133 #endif
134                         "\nBuiltin defaults:\n"
135                         "  Config-File       "CONFIGFILE"\n"
136                         "  PID-File          "PIDFILE"\n"
137                         "  Data-Directory    "PKGLOCALSTATEDIR"\n"
138 #if COLLECT_DEBUG
139                         "  Log-File          "LOGFILE"\n"
140 #endif
141                         "  Step              "COLLECTD_STEP" seconds\n"
142                         "  Heartbeat         "COLLECTD_HEARTBEAT" seconds\n"
143                         "\n"PACKAGE" "VERSION", http://verplant.org/collectd/\n"
144                         "by Florian octo Forster <octo@verplant.org>\n"
145                         "for contributions see `AUTHORS'\n");
146         exit (0);
147 } /* static void exit_usage (char *name) */
148
149 static int start_client (void)
150 {
151         int step;
152
153         struct timeval tv_now;
154         struct timeval tv_next;
155         struct timespec ts_wait;
156
157         step = atoi (COLLECTD_STEP);
158         if (step <= 0)
159                 step = 10;
160
161 #if HAVE_LIBKSTAT
162         kc = NULL;
163         update_kstat ();
164 #endif
165
166 #if HAVE_LIBSTATGRAB
167         if (sg_init ())
168         {
169                 syslog (LOG_ERR, "sg_init: %s", sg_str_error (sg_get_error ()));
170                 return (-1);
171         }
172
173         if (sg_drop_privileges ())
174         {
175                 syslog (LOG_ERR, "sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
176                 return (-1);
177         }
178 #endif
179
180         plugin_init_all ();
181
182         while (loop == 0)
183         {
184                 if (gettimeofday (&tv_next, NULL) < 0)
185                 {
186                         syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
187                         return (-1);
188                 }
189                 tv_next.tv_sec += step;
190
191 #if HAVE_LIBKSTAT
192                 update_kstat ();
193 #endif
194                 /* `curtime' is used by many (all?) plugins as the
195                  * data-sample-time passed to RRDTool */
196                 curtime = time (NULL);
197
198                 /* Issue all plugins */
199                 plugin_read_all ();
200
201                 if (gettimeofday (&tv_now, NULL) < 0)
202                 {
203                         syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
204                         return (-1);
205                 }
206
207                 if (timeval_sub_timespec (&tv_next, &tv_now, &ts_wait) != 0)
208                 {
209                         syslog (LOG_WARNING, "No sleeping because `timeval_sub_timespec' returned non-zero!");
210                         continue;
211                 }
212
213                 while (nanosleep (&ts_wait, &ts_wait) == -1)
214                 {
215                         if (errno != EINTR)
216                         {
217                                 syslog (LOG_ERR, "nanosleep failed: %s", strerror (errno));
218                                 break;
219                         }
220                 }
221         }
222
223         return (0);
224 } /* static int start_client (void) */
225
226 #if HAVE_LIBRRD
227 static int start_server (void)
228 {
229         /* FIXME use stack here! */
230         char *host;
231         char *type;
232         char *instance;
233         char *values;
234
235         while (loop == 0)
236         {
237                 if (network_receive (&host, &type, &instance, &values) == 0)
238                         plugin_write (host, type, instance, values);
239
240                 if (host     != NULL) free (host);     host     = NULL;
241                 if (type     != NULL) free (type);     type     = NULL;
242                 if (instance != NULL) free (instance); instance = NULL;
243                 if (values   != NULL) free (values);   values   = NULL;
244         }
245         
246         return (0);
247 } /* static int start_server (void) */
248 #endif /* HAVE_LIBRRD */
249
250 #if COLLECT_DAEMON
251 static int pidfile_create (const char *file)
252 {
253         FILE *fh;
254
255         if (file == NULL)
256                 file = PIDFILE;
257
258         if ((fh = fopen (file, "w")) == NULL)
259         {
260                 syslog (LOG_ERR, "fopen (%s): %s", file, strerror (errno));
261                 return (1);
262         }
263
264         fprintf (fh, "%d\n", getpid());
265         fclose(fh);
266
267         return (0);
268 } /* static int pidfile_create (const char *file) */
269 #endif /* COLLECT_DAEMON */
270
271 #if COLLECT_DAEMON
272 static int pidfile_remove (const char *file)
273 {
274         if (file == NULL) {
275                 file = PIDFILE;
276         }
277         return (unlink (file));
278 } /* static int pidfile_remove (const char *file) */
279 #endif /* COLLECT_DAEMON */
280
281 int main (int argc, char **argv)
282 {
283         struct sigaction sigIntAction;
284         struct sigaction sigTermAction;
285         char *datadir    = PKGLOCALSTATEDIR;
286         char *configfile = CONFIGFILE;
287 #if COLLECT_DAEMON
288         struct sigaction sigChldAction;
289         char *pidfile    = PIDFILE;
290         pid_t pid;
291         int daemonize    = 1;
292 #endif
293 #if COLLECT_DEBUG
294         char *logfile    = LOGFILE;
295 #endif
296
297 #if HAVE_LIBRRD
298         operating_mode = MODE_LOCAL;
299 #endif
300
301         /* open syslog */
302         openlog (PACKAGE, LOG_CONS | LOG_PID, LOG_DAEMON);
303
304         /* read options */
305         while (1)
306         {
307                 int c;
308
309                 c = getopt (argc, argv, "hC:"
310 #if COLLECT_DAEMON
311                                 "f"
312 #endif
313                 );
314
315                 if (c == -1)
316                         break;
317
318                 switch (c)
319                 {
320                         case 'C':
321                                 configfile = optarg;
322                                 break;
323 #if COLLECT_DAEMON
324                         case 'f':
325                                 daemonize = 0;
326                                 break;
327 #endif /* COLLECT_DAEMON */
328                         case 'h':
329                         default:
330                                 exit_usage (argv[0]);
331                 } /* switch (c) */
332         } /* while (1) */
333
334 #if COLLECT_DEBUG
335         if ((logfile = cf_get_option ("LogFile", LOGFILE)) != NULL)
336                 DBG_STARTFILE (logfile, "Debug file opened.");
337 #endif
338
339         /*
340          * Read options from the config file, the environment and the command
341          * line (in that order, with later options overwriting previous ones in
342          * general).
343          * Also, this will automatically load modules.
344          */
345         if (cf_read (configfile))
346         {
347                 fprintf (stderr, "Error: Reading the config file failed!\n"
348                                 "Read the syslog for details.\n");
349                 return (1);
350         }
351
352         /*
353          * Change directory. We do this _after_ reading the config and loading
354          * modules to relative paths work as expected.
355          */
356         if ((datadir = cf_get_option ("DataDir", PKGLOCALSTATEDIR)) == NULL)
357         {
358                 fprintf (stderr, "Don't have a datadir to use. This should not happen. Ever.");
359                 return (1);
360         }
361         if (change_basedir (datadir))
362         {
363                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", datadir);
364                 return (1);
365         }
366
367 #if COLLECT_DAEMON
368         /*
369          * fork off child
370          */
371         sigChldAction.sa_handler = SIG_IGN;
372         sigaction (SIGCHLD, &sigChldAction, NULL);
373
374         if ((pidfile = cf_get_option ("PIDFile", PIDFILE)) == NULL)
375         {
376                 fprintf (stderr, "Cannot obtain pidfile. This shoud not happen. Ever.");
377                 return (1);
378         }
379
380         if (daemonize)
381         {
382                 if ((pid = fork ()) == -1)
383                 {
384                         /* error */
385                         fprintf (stderr, "fork: %s", strerror (errno));
386                         return (1);
387                 }
388                 else if (pid != 0)
389                 {
390                         /* parent */
391                         /* printf ("Running (PID %i)\n", pid); */
392                         return (0);
393                 }
394
395                 /* Detach from session */
396                 setsid ();
397
398                 /* Write pidfile */
399                 if (pidfile_create (pidfile))
400                         exit (2);
401
402                 /* close standard descriptors */
403                 close (2);
404                 close (1);
405                 close (0);
406
407                 if (open ("/dev/null", O_RDWR) != 0)
408                 {
409                         syslog (LOG_ERR, "Error: Could not connect `STDIN' to `/dev/null'");
410                         return (1);
411                 }
412                 if (dup (0) != 1)
413                 {
414                         syslog (LOG_ERR, "Error: Could not connect `STDOUT' to `/dev/null'");
415                         return (1);
416                 }
417                 if (dup (0) != 2)
418                 {
419                         syslog (LOG_ERR, "Error: Could not connect `STDERR' to `/dev/null'");
420                         return (1);
421                 }
422         } /* if (daemonize) */
423 #endif /* COLLECT_DAEMON */
424
425         /*
426          * install signal handlers
427          */
428         sigIntAction.sa_handler = sigIntHandler;
429         sigaction (SIGINT, &sigIntAction, NULL);
430
431         sigTermAction.sa_handler = sigTermHandler;
432         sigaction (SIGTERM, &sigTermAction, NULL);
433
434         /*
435          * run the actual loops
436          */
437 #if HAVE_LIBRRD
438         if (operating_mode == MODE_SERVER)
439                 start_server ();
440         else /* if (operating_mode == MODE_CLIENT || operating_mode == MODE_LOCAL) */
441 #endif
442                 start_client ();
443
444 #if COLLECT_DEBUG
445         if (logfile != NULL)
446                 DBG_STOPFILE("debug file closed.");
447 #endif
448
449         /* close syslog */
450         syslog (LOG_INFO, "Exiting normally");
451         closelog ();
452
453 #if COLLECT_DAEMON
454         if (daemonize)
455                 pidfile_remove (pidfile);
456 #endif /* COLLECT_DAEMON */
457
458         return (0);
459 } /* int main (int argc, char **argv) */