Code

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