6e711108f78699fdf560655536482b49e54acf14
[collectd.git] / src / collectd.c
1 /**
2  * collectd - src/collectd.c
3  * Copyright (C) 2005,2006  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 static int loop = 0;
33
34 #if HAVE_LIBKSTAT
35 kstat_ctl_t *kc;
36 #endif /* HAVE_LIBKSTAT */
37
38 /*
39  * exported variables
40  */
41 time_t curtime;
42 int    operating_mode;
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 change_basedir (char *dir)
55 {
56         int dirlen = strlen (dir);
57         
58         while ((dirlen > 0) && (dir[dirlen - 1] == '/'))
59                 dir[--dirlen] = '\0';
60
61         if (dirlen <= 0)
62                 return (-1);
63
64         if (chdir (dir) == -1)
65         {
66                 if (errno == ENOENT)
67                 {
68                         if (mkdir (dir, 0755) == -1)
69                         {
70                                 syslog (LOG_ERR, "mkdir (%s): %s", dir, strerror (errno));
71                                 return (-1);
72                         }
73                         else if (chdir (dir) == -1)
74                         {
75                                 syslog (LOG_ERR, "chdir (%s): %s", dir, strerror (errno));
76                                 return (-1);
77                         }
78                 }
79                 else
80                 {
81                         syslog (LOG_ERR, "chdir: %s", strerror (errno));
82                         return (-1);
83                 }
84         }
85
86         return (0);
87 } /* static int change_basedir (char *dir) */
88
89 #if HAVE_LIBKSTAT
90 static void update_kstat (void)
91 {
92         if (kc == NULL)
93         {
94                 if ((kc = kstat_open ()) == NULL)
95                         syslog (LOG_ERR, "Unable to open kstat control structure");
96         }
97         else
98         {
99                 kid_t kid;
100                 kid = kstat_chain_update (kc);
101                 if (kid > 0)
102                 {
103                         syslog (LOG_INFO, "kstat chain has been updated");
104                         plugin_init_all ();
105                 }
106                 else if (kid < 0)
107                         syslog (LOG_ERR, "kstat chain update failed");
108                 /* else: everything works as expected */
109         }
110
111         return;
112 } /* static void update_kstat (void) */
113 #endif /* HAVE_LIBKSTAT */
114
115 /* TODO
116  * Remove all settings but `-f' and `-C'
117  */
118 static void exit_usage (char *name)
119 {
120         printf ("Usage: "PACKAGE" [OPTIONS]\n\n"
121                         
122                         "Available options:\n"
123                         "  General:\n"
124                         "    -C <file>       Configuration file.\n"
125                         "                    Default: "CONFIGFILE"\n"
126                         "    -P <file>       PID-file.\n"
127                         "                    Default: "PIDFILE"\n"
128 #if COLLECT_DAEMON
129                         "    -f              Don't fork to the background.\n"
130 #endif
131                         "\nBuiltin defaults:\n"
132                         "  Config-File       "CONFIGFILE"\n"
133                         "  PID-File          "PIDFILE"\n"
134                         "  Data-Directory    "PKGLOCALSTATEDIR"\n"
135 #if COLLECT_DEBUG
136                         "  Log-File          "LOGFILE"\n"
137 #endif
138                         "  Step              "COLLECTD_STEP" seconds\n"
139                         "  Heartbeat         "COLLECTD_HEARTBEAT" seconds\n"
140                         "\n"PACKAGE" "VERSION", http://collectd.org/\n"
141                         "by Florian octo Forster <octo@verplant.org>\n"
142                         "for contributions see `AUTHORS'\n");
143         exit (0);
144 } /* static void exit_usage (char *name) */
145
146 static int start_client (void)
147 {
148         int step;
149
150         struct timeval tv_now;
151         struct timeval tv_next;
152         struct timespec ts_wait;
153
154         step = atoi (COLLECTD_STEP);
155         if (step <= 0)
156                 step = 10;
157
158 #if HAVE_LIBKSTAT
159         kc = NULL;
160         update_kstat ();
161 #endif
162
163 #if HAVE_LIBSTATGRAB
164         if (sg_init ())
165         {
166                 syslog (LOG_ERR, "sg_init: %s", sg_str_error (sg_get_error ()));
167                 return (-1);
168         }
169
170         if (sg_drop_privileges ())
171         {
172                 syslog (LOG_ERR, "sg_drop_privileges: %s", sg_str_error (sg_get_error ()));
173                 return (-1);
174         }
175 #endif
176
177         plugin_init_all ();
178
179         while (loop == 0)
180         {
181                 if (gettimeofday (&tv_next, NULL) < 0)
182                 {
183                         syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
184                         return (-1);
185                 }
186                 tv_next.tv_sec += step;
187
188 #if HAVE_LIBKSTAT
189                 update_kstat ();
190 #endif
191                 /* `curtime' is used by many (all?) plugins as the
192                  * data-sample-time passed to RRDTool */
193                 curtime = time (NULL);
194
195                 /* Issue all plugins */
196                 plugin_read_all (&loop);
197
198                 if (gettimeofday (&tv_now, NULL) < 0)
199                 {
200                         syslog (LOG_ERR, "gettimeofday failed: %s", strerror (errno));
201                         return (-1);
202                 }
203
204                 if (timeval_sub_timespec (&tv_next, &tv_now, &ts_wait) != 0)
205                 {
206                         syslog (LOG_WARNING, "Not sleeping because `timeval_sub_timespec' returned non-zero!");
207                         continue;
208                 }
209
210                 while ((loop == 0) && (nanosleep (&ts_wait, &ts_wait) == -1))
211                 {
212                         if (errno != EINTR)
213                         {
214                                 syslog (LOG_ERR, "nanosleep failed: %s", strerror (errno));
215                                 break;
216                         }
217                 }
218         }
219
220         return (0);
221 } /* static int start_client (void) */
222
223 #if HAVE_LIBRRD
224 static int start_server (void)
225 {
226         /* FIXME use stack here! */
227         /* FIXME */
228 #if 0
229         char *host;
230         char *type;
231         char *instance;
232         char *values;
233
234         while (loop == 0)
235         {
236                 if (network_receive (&host, &type, &instance, &values) == 0)
237                         plugin_write (host, type, instance, values);
238
239                 if (host     != NULL) free (host);     host     = NULL;
240                 if (type     != NULL) free (type);     type     = NULL;
241                 if (instance != NULL) free (instance); instance = NULL;
242                 if (values   != NULL) free (values);   values   = NULL;
243         }
244         
245 #endif
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, "%i\n", (int) 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    = NULL;
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 #else
300         operating_mode = MODE_CLIENT;
301 #endif
302
303         /* open syslog */
304         openlog (PACKAGE, LOG_CONS | LOG_PID, LOG_DAEMON);
305
306         /* read options */
307         while (1)
308         {
309                 int c;
310
311                 c = getopt (argc, argv, "hC:"
312 #if COLLECT_DAEMON
313                                 "fP:"
314 #endif
315                 );
316
317                 if (c == -1)
318                         break;
319
320                 switch (c)
321                 {
322                         case 'C':
323                                 configfile = optarg;
324                                 break;
325 #if COLLECT_DAEMON
326                         case 'P':
327                                 pidfile = optarg;
328                                 break;
329                         case 'f':
330                                 daemonize = 0;
331                                 break;
332 #endif /* COLLECT_DAEMON */
333                         case 'h':
334                         default:
335                                 exit_usage (argv[0]);
336                 } /* switch (c) */
337         } /* while (1) */
338
339 #if COLLECT_DEBUG
340         if ((logfile = cf_get_option ("LogFile", LOGFILE)) != NULL)
341                 DBG_STARTFILE (logfile, "Debug file opened.");
342 #endif
343
344         /*
345          * Read options from the config file, the environment and the command
346          * line (in that order, with later options overwriting previous ones in
347          * general).
348          * Also, this will automatically load modules.
349          */
350         if (cf_read (configfile))
351         {
352                 fprintf (stderr, "Error: Reading the config file failed!\n"
353                                 "Read the syslog for details.\n");
354                 return (1);
355         }
356
357         /*
358          * Change directory. We do this _after_ reading the config and loading
359          * modules to relative paths work as expected.
360          */
361         if ((datadir = cf_get_option ("DataDir", PKGLOCALSTATEDIR)) == NULL)
362         {
363                 fprintf (stderr, "Don't have a datadir to use. This should not happen. Ever.");
364                 return (1);
365         }
366         if (change_basedir (datadir))
367         {
368                 fprintf (stderr, "Error: Unable to change to directory `%s'.\n", datadir);
369                 return (1);
370         }
371
372 #if COLLECT_DAEMON
373         /*
374          * fork off child
375          */
376         sigChldAction.sa_handler = SIG_IGN;
377         sigaction (SIGCHLD, &sigChldAction, NULL);
378
379         if ((pidfile == NULL)
380                         && ((pidfile = cf_get_option ("PIDFile", PIDFILE)) == NULL))
381         {
382                 fprintf (stderr, "Cannot obtain pidfile. This shoud not happen. Ever.");
383                 return (1);
384         }
385
386         if (daemonize)
387         {
388                 if ((pid = fork ()) == -1)
389                 {
390                         /* error */
391                         fprintf (stderr, "fork: %s", strerror (errno));
392                         return (1);
393                 }
394                 else if (pid != 0)
395                 {
396                         /* parent */
397                         /* printf ("Running (PID %i)\n", pid); */
398                         return (0);
399                 }
400
401                 /* Detach from session */
402                 setsid ();
403
404                 /* Write pidfile */
405                 if (pidfile_create (pidfile))
406                         exit (2);
407
408                 /* close standard descriptors */
409                 close (2);
410                 close (1);
411                 close (0);
412
413                 if (open ("/dev/null", O_RDWR) != 0)
414                 {
415                         syslog (LOG_ERR, "Error: Could not connect `STDIN' to `/dev/null'");
416                         return (1);
417                 }
418                 if (dup (0) != 1)
419                 {
420                         syslog (LOG_ERR, "Error: Could not connect `STDOUT' to `/dev/null'");
421                         return (1);
422                 }
423                 if (dup (0) != 2)
424                 {
425                         syslog (LOG_ERR, "Error: Could not connect `STDERR' to `/dev/null'");
426                         return (1);
427                 }
428         } /* if (daemonize) */
429 #endif /* COLLECT_DAEMON */
430
431         /*
432          * install signal handlers
433          */
434         sigIntAction.sa_handler = sigIntHandler;
435         sigaction (SIGINT, &sigIntAction, NULL);
436
437         sigTermAction.sa_handler = sigTermHandler;
438         sigaction (SIGTERM, &sigTermAction, NULL);
439
440         /*
441          * run the actual loops
442          */
443 #if HAVE_LIBRRD
444         if (operating_mode == MODE_SERVER)
445                 start_server ();
446         else /* if (operating_mode == MODE_CLIENT || operating_mode == MODE_LOCAL || operating_mode == MODE_LOG) */
447 #endif
448                 start_client ();
449
450         plugin_shutdown_all ();
451
452 #if COLLECT_DEBUG
453         if (logfile != NULL)
454                 DBG_STOPFILE("debug file closed.");
455 #endif
456
457         /* close syslog */
458         syslog (LOG_INFO, "Exiting normally");
459         closelog ();
460
461 #if COLLECT_DAEMON
462         if (daemonize)
463                 pidfile_remove (pidfile);
464 #endif /* COLLECT_DAEMON */
465
466         return (0);
467 } /* int main (int argc, char **argv) */