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