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