]> arthur.barton.de Git - netdata.git/blob - src/main.c
11d69cdb1591b3b3070f0ad7dc78ed354da48c5e
[netdata.git] / src / main.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <signal.h>
8 #include <syslog.h>
9 #include <pthread.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/time.h>
15 #include <sys/resource.h>
16
17 #include "common.h"
18 #include "log.h"
19 #include "daemon.h"
20 #include "web_server.h"
21 #include "popen.h"
22 #include "appconfig.h"
23 #include "web_client.h"
24 #include "rrd.h"
25 #include "rrd2json.h"
26
27 #include "unit_test.h"
28
29 #include "plugins_d.h"
30 #include "plugin_idlejitter.h"
31 #include "plugin_tc.h"
32 #include "plugin_checks.h"
33 #include "plugin_proc.h"
34 #include "plugin_nfacct.h"
35
36 #include "main.h"
37
38 int netdata_exit = 0;
39
40 void netdata_cleanup_and_exit(int ret)
41 {
42         kill_childs();
43         rrdset_free_all();
44         //unlink("/var/run/netdata.pid");
45         info("NetData exiting. Bye bye...");
46         exit(ret);
47 }
48
49 struct netdata_static_thread {
50         char *name;
51
52         char *config_section;
53         char *config_name;
54
55         int enabled;
56
57         pthread_t *thread;
58
59         void (*init_routine) (void);
60         void *(*start_routine) (void *);
61 };
62
63 struct netdata_static_thread static_threads[] = {
64         {"tc",                  "plugins",      "tc",                   1, NULL, NULL,  tc_main},
65         {"idlejitter",  "plugins",      "idlejitter",   1, NULL, NULL,  cpuidlejitter_main},
66         {"proc",                "plugins",      "proc",                 1, NULL, NULL,  proc_main},
67
68 #ifdef INTERNAL_PLUGIN_NFACCT
69         // nfacct requires root access
70         // so, we build it as an external plugin with setuid to root
71         {"nfacct",              "plugins",      "nfacct",               1, NULL, NULL,  nfacct_main},
72 #endif
73
74         {"plugins.d",   NULL,           NULL,                   1, NULL, NULL,  pluginsd_main},
75         {"check",               "plugins",      "checks",               0, NULL, NULL,  checks_main},
76         {"web",                 NULL,           NULL,                   1, NULL, NULL,  socket_listen_main},
77         {NULL,                  NULL,           NULL,                   0, NULL, NULL,  NULL}
78 };
79
80 int killpid(pid_t pid, int sig)
81 {
82         int ret = -1;
83         debug(D_EXIT, "Request to kill pid %d", pid);
84
85         errno = 0;
86         if(kill(pid, 0) == -1) {
87                 switch(errno) {
88                         case ESRCH:
89                                 error("Request to kill pid %d, but it is not running.", pid);
90                                 break;
91
92                         case EPERM:
93                                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
94                                 break;
95
96                         default:
97                                 error("Request to kill pid %d, but I received an error.", pid);
98                                 break;
99                 }
100         }
101         else {
102                 errno = 0;
103
104                 void (*old)(int);
105                 old = signal(sig, SIG_IGN);
106                 if(old == SIG_ERR) {
107                         error("Cannot overwrite signal handler for signal %d", sig);
108                         old = sig_handler;
109                 }
110
111                 ret = kill(pid, sig);
112
113                 if(signal(sig, old) == SIG_ERR)
114                         error("Cannot restore signal handler for signal %d", sig);
115
116                 if(ret == -1) {
117                         switch(errno) {
118                                 case ESRCH:
119                                         error("Cannot kill pid %d, but it is not running.", pid);
120                                         break;
121
122                                 case EPERM:
123                                         error("Cannot kill pid %d, but I do not have enough permissions.", pid);
124                                         break;
125
126                                 default:
127                                         error("Cannot kill pid %d, but I received an error.", pid);
128                                         break;
129                         }
130                 }
131         }
132
133         return ret;
134 }
135
136 void kill_childs()
137 {
138         siginfo_t info;
139
140         struct web_client *w;
141         for(w = web_clients; w ; w = w->next) {
142                 debug(D_EXIT, "Stopping web client %s", w->client_ip);
143                 pthread_cancel(w->thread);
144                 pthread_join(w->thread, NULL);
145         }
146
147         int i;
148         for (i = 0; static_threads[i].name != NULL ; i++) {
149                 if(static_threads[i].thread) {
150                         debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
151                         pthread_cancel(*static_threads[i].thread);
152                         pthread_join(*static_threads[i].thread, NULL);
153                         static_threads[i].thread = NULL;
154                 }
155         }
156
157         if(tc_child_pid) {
158                 info("Killing tc-qos-helper procees");
159                 if(killpid(tc_child_pid, SIGTERM) != -1)
160                         waitid(P_PID, tc_child_pid, &info, WEXITED);
161         }
162         tc_child_pid = 0;
163
164         struct plugind *cd;
165         for(cd = pluginsd_root ; cd ; cd = cd->next) {
166                 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
167                 pthread_cancel(cd->thread);
168                 pthread_join(cd->thread, NULL);
169
170                 if(cd->pid && !cd->obsolete) {
171                         debug(D_EXIT, "killing %s plugin process", cd->id);
172                         if(killpid(cd->pid, SIGTERM) != -1)
173                                 waitid(P_PID, cd->pid, &info, WEXITED);
174                 }
175         }
176
177         // if, for any reason there is any child exited
178         // catch it here
179         waitid(P_PID, 0, &info, WEXITED|WNOHANG);
180
181         debug(D_EXIT, "All threads/childs stopped.");
182 }
183
184
185 int main(int argc, char **argv)
186 {
187         int i;
188         int config_loaded = 0;
189         int dont_fork = 0;
190
191         // global initialization
192         get_HZ();
193
194         // set the name for logging
195         program_name = "netdata";
196
197         // parse  the arguments
198         for(i = 1; i < argc ; i++) {
199                 if(strcmp(argv[i], "-c") == 0 && (i+1) < argc) {
200                         if(load_config(argv[i+1], 1) != 1) {
201                                 error("Cannot load configuration file %s.", argv[i+1]);
202                                 exit(1);
203                         }
204                         else {
205                                 debug(D_OPTIONS, "Configuration loaded from %s.", argv[i+1]);
206                                 config_loaded = 1;
207                         }
208                         i++;
209                 }
210                 else if(strcmp(argv[i], "-df") == 0 && (i+1) < argc) { config_set("global", "debug flags",  argv[i+1]); i++; }
211                 else if(strcmp(argv[i], "-p")  == 0 && (i+1) < argc) { config_set("global", "port",         argv[i+1]); i++; }
212                 else if(strcmp(argv[i], "-u")  == 0 && (i+1) < argc) { config_set("global", "run as user",  argv[i+1]); i++; }
213                 else if(strcmp(argv[i], "-l")  == 0 && (i+1) < argc) { config_set("global", "history",      argv[i+1]); i++; }
214                 else if(strcmp(argv[i], "-t")  == 0 && (i+1) < argc) { config_set("global", "update every", argv[i+1]); i++; }
215                 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) { config_set("global", "host access prefix", argv[i+1]); i++; }
216                 else if(strcmp(argv[i], "-nodeamon") == 0 || strcmp(argv[i], "-nd") == 0) dont_fork = 1;
217                 else if(strcmp(argv[i], "--unittest")  == 0) {
218                         if(unit_test_storage()) exit(1);
219                         exit(0);
220                         rrd_update_every = 1;
221                         if(unit_test(1000000, 0)) exit(1);
222                         if(unit_test(1000000, 500000)) exit(1);
223                         if(unit_test(1000000, 100000)) exit(1);
224                         if(unit_test(1000000, 900000)) exit(1);
225                         if(unit_test(2000000, 0)) exit(1);
226                         if(unit_test(2000000, 500000)) exit(1);
227                         if(unit_test(2000000, 100000)) exit(1);
228                         if(unit_test(2000000, 900000)) exit(1);
229                         if(unit_test(500000, 500000)) exit(1);
230                         //if(unit_test(500000, 100000)) exit(1); // FIXME: the expected numbers are wrong
231                         //if(unit_test(500000, 900000)) exit(1); // FIXME: the expected numbers are wrong
232                         if(unit_test(500000, 0)) exit(1);
233                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
234                         exit(0);
235                 }
236                 else {
237                         fprintf(stderr, "Cannot understand option '%s'.\n", argv[i]);
238                         fprintf(stderr, "\nUSAGE: %s [-d] [-l LINES_TO_SAVE] [-u UPDATE_TIMER] [-p LISTEN_PORT] [-dl debug log file] [-df debug flags].\n\n", argv[0]);
239                         fprintf(stderr, "  -c CONFIG FILE the configuration file to load. Default: %s.\n", CONFIG_DIR "/" CONFIG_FILENAME);
240                         fprintf(stderr, "  -l LINES_TO_SAVE can be from 5 to %d lines in JSON data. Default: %d.\n", RRD_HISTORY_ENTRIES_MAX, RRD_DEFAULT_HISTORY_ENTRIES);
241                         fprintf(stderr, "  -t UPDATE_TIMER can be from 1 to %d seconds. Default: %d.\n", UPDATE_EVERY_MAX, UPDATE_EVERY);
242                         fprintf(stderr, "  -p LISTEN_PORT can be from 1 to %d. Default: %d.\n", 65535, LISTEN_PORT);
243                         fprintf(stderr, "  -u USERNAME can be any system username to run as. Default: none.\n");
244                         fprintf(stderr, "  -ch path to access host /proc and /sys when running in a container. Default: empty.\n");
245                         fprintf(stderr, "  -nd or -nodeamon to disable forking in the background. Default: unset.\n");
246                         fprintf(stderr, "  -df FLAGS debug options. Default: 0x%08llx.\n", debug_flags);
247                         exit(1);
248                 }
249         }
250
251         if(!config_loaded) load_config(NULL, 0);
252
253         // prepare configuration environment variables for the plugins
254         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
255         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
256         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
257         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
258         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
259
260         // avoid extended to stat(/etc/localtime)
261         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
262         setenv("TZ", ":/etc/localtime", 0);
263
264         // cd to /tmp to avoid any plugins writing files at random places
265         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
266
267         char *input_log_file = NULL;
268         char *output_log_file = NULL;
269         char *error_log_file = NULL;
270         char *access_log_file = NULL;
271         char *user = NULL;
272         {
273                 char buffer[1024];
274
275                 // --------------------------------------------------------------------
276
277                 sprintf(buffer, "0x%08llx", 0ULL);
278                 char *flags = config_get("global", "debug flags", buffer);
279                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
280
281                 debug_flags = strtoull(flags, NULL, 0);
282                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
283
284                 if(debug_flags != 0) {
285                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
286                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
287                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
288                 }
289
290                 // --------------------------------------------------------------------
291
292                 global_host_prefix = config_get("global", "host access prefix", "");
293                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
294
295                 // --------------------------------------------------------------------
296
297                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
298                 if(strcmp(output_log_file, "syslog") == 0) {
299                         output_log_syslog = 1;
300                         output_log_file = NULL;
301                 }
302                 else if(strcmp(output_log_file, "none") == 0) {
303                         output_log_syslog = 0;
304                         output_log_file = NULL;
305                 }
306                 else output_log_syslog = 0;
307
308                 // --------------------------------------------------------------------
309
310                 silent = 0;
311                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
312                 if(strcmp(error_log_file, "syslog") == 0) {
313                         error_log_syslog = 1;
314                         error_log_file = NULL;
315                 }
316                 else if(strcmp(error_log_file, "none") == 0) {
317                         error_log_syslog = 0;
318                         error_log_file = NULL;
319                         silent = 1; // optimization - do not even generate debug log entries
320                 }
321                 else error_log_syslog = 0;
322
323                 // --------------------------------------------------------------------
324
325                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
326                 if(strcmp(access_log_file, "syslog") == 0) {
327                         access_log_syslog = 1;
328                         access_log_file = NULL;
329                 }
330                 else if(strcmp(access_log_file, "none") == 0) {
331                         access_log_syslog = 0;
332                         access_log_file = NULL;
333                 }
334                 else access_log_syslog = 0;
335
336                 // --------------------------------------------------------------------
337
338                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
339
340                 // --------------------------------------------------------------------
341
342                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
343                         error("WARNING: Cannot get machine hostname.");
344                 hostname = config_get("global", "hostname", buffer);
345                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
346
347                 // --------------------------------------------------------------------
348
349                 rrd_default_history_entries = config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
350                 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
351                         fprintf(stderr, "Invalid save lines %d given. Defaulting to %d.\n", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
352                         rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
353                 }
354                 else {
355                         debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
356                 }
357
358                 // --------------------------------------------------------------------
359
360                 rrd_update_every = config_get_number("global", "update every", UPDATE_EVERY);
361                 if(rrd_update_every < 1 || rrd_update_every > 600) {
362                         fprintf(stderr, "Invalid update timer %d given. Defaulting to %d.\n", rrd_update_every, UPDATE_EVERY_MAX);
363                         rrd_update_every = UPDATE_EVERY;
364                 }
365                 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
366
367                 // let the plugins know the min update_every
368                 {
369                         char buffer[50];
370                         snprintf(buffer, 50, "%d", rrd_update_every);
371                         setenv("NETDATA_UPDATE_EVERY", buffer, 1);
372                 }
373
374                 // --------------------------------------------------------------------
375
376                 for (i = 0; static_threads[i].name != NULL ; i++) {
377                         struct netdata_static_thread *st = &static_threads[i];
378
379                         if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
380                         if(st->enabled && st->init_routine) st->init_routine();
381                 }
382
383                 // --------------------------------------------------------------------
384
385                 prepare_rundir();
386                 user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
387                 web_files_uid();
388
389                 // --------------------------------------------------------------------
390
391                 listen_backlog = config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
392
393                 listen_port = config_get_number("global", "port", LISTEN_PORT);
394                 if(listen_port < 1 || listen_port > 65535) {
395                         fprintf(stderr, "Invalid listen port %d given. Defaulting to %d.\n", listen_port, LISTEN_PORT);
396                         listen_port = LISTEN_PORT;
397                 }
398                 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
399
400                 int ip = 0;
401                 char *ipv = config_get("global", "ip version", "any");
402                 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
403                 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
404                 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
405                 else fprintf(stderr, "Cannot understand ip version '%s'. Assumming 'any'.", ipv);
406
407                 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(listen_port, listen_backlog);
408                 if(listen_fd < 0) {
409                         listen_fd = create_listen_socket4(listen_port, listen_backlog);
410                         if(listen_fd >= 0 && ip != 4) fprintf(stderr, "Managed to open an IPv4 socket on port %d.", listen_port);
411                 }
412
413                 if(listen_fd < 0) fatal("Cannot listen socket.");
414         }
415
416         // never become a problem
417         if(nice(20) == -1) error("Cannot lower my CPU priority.");
418
419         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1) {
420                 fatal("Cannot demonize myself.");
421                 exit(1);
422         }
423
424         if(output_log_syslog || error_log_syslog || access_log_syslog)
425                 openlog("netdata", LOG_PID, LOG_DAEMON);
426
427         info("NetData started on pid %d", getpid());
428
429
430         // catch all signals
431         for (i = 1 ; i < 65 ;i++) {
432                 switch(i) {
433                         case SIGKILL: // not catchable
434                         case SIGSTOP: // not catchable
435                                 break;
436
437                         case SIGSEGV:
438                         case SIGFPE:
439                         case SIGCHLD:
440                                 signal(i, SIG_DFL);
441                                 break;
442
443                         default:
444                                 signal(i,  sig_handler);
445                                 break;
446                 }
447         }
448
449         for (i = 0; static_threads[i].name != NULL ; i++) {
450                 struct netdata_static_thread *st = &static_threads[i];
451
452                 if(st->enabled) {
453                         st->thread = malloc(sizeof(pthread_t));
454
455                         info("Starting thread %s.", st->name);
456
457                         if(pthread_create(st->thread, NULL, st->start_routine, NULL))
458                                 error("failed to create new thread for %s.", st->name);
459
460                         else if(pthread_detach(*st->thread))
461                                 error("Cannot request detach of newly created %s thread.", st->name);
462                 }
463                 else info("Not starting thread %s.", st->name);
464         }
465
466         // for future use - the main thread
467         while(1) {
468                 if(netdata_exit != 0) {
469                         netdata_exit++;
470
471                         if(netdata_exit > 5) {
472                                 netdata_cleanup_and_exit(0);
473                                 exit(0);
474                         }
475                 }
476                 sleep(2);
477         }
478
479         exit(0);
480 }