]> arthur.barton.de Git - netdata.git/blob - src/main.c
Command line: Follow IEEE Std 1003.1, 2013 Edition
[netdata.git] / src / main.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <errno.h>
5 #include <getopt.h>
6 #include <pthread.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/mman.h>
12 #include <sys/prctl.h>
13 #include <sys/wait.h>
14 #include <syslog.h>
15 #include <unistd.h>
16
17 #include "appconfig.h"
18 #include "common.h"
19 #include "daemon.h"
20 #include "log.h"
21 #include "popen.h"
22 #include "rrd.h"
23 #include "rrd2json.h"
24 #include "web_client.h"
25 #include "web_server.h"
26
27 #include "unit_test.h"
28
29 #include "plugin_checks.h"
30 #include "plugin_idlejitter.h"
31 #include "plugin_nfacct.h"
32 #include "registry.h"
33 #include "plugin_proc.h"
34 #include "plugin_tc.h"
35 #include "plugins_d.h"
36
37 #include "main.h"
38
39 extern void *cgroups_main(void *ptr);
40
41 volatile sig_atomic_t netdata_exit = 0;
42
43 void netdata_cleanup_and_exit(int ret)
44 {
45         netdata_exit = 1;
46         rrdset_save_all();
47         // kill_childs();
48
49         // let it log a few more error messages
50         error_log_limit_reset();
51
52         if(pidfd != -1) {
53                 if(ftruncate(pidfd, 0) != 0)
54                         error("Cannot truncate pidfile '%s'.", pidfile);
55
56                 close(pidfd);
57                 pidfd = -1;
58         }
59
60         if(pidfile[0]) {
61                 if(unlink(pidfile) != 0)
62                         error("Cannot unlink pidfile '%s'.", pidfile);
63         }
64
65         info("NetData exiting. Bye bye...");
66         exit(ret);
67 }
68
69 struct netdata_static_thread {
70         char *name;
71
72         char *config_section;
73         char *config_name;
74
75         int enabled;
76
77         pthread_t *thread;
78
79         void (*init_routine) (void);
80         void *(*start_routine) (void *);
81 };
82
83 struct netdata_static_thread static_threads[] = {
84         {"tc",                  "plugins",      "tc",                   1, NULL, NULL,  tc_main},
85         {"idlejitter",  "plugins",      "idlejitter",   1, NULL, NULL,  cpuidlejitter_main},
86         {"proc",                "plugins",      "proc",                 1, NULL, NULL,  proc_main},
87         {"cgroups",             "plugins",      "cgroups",              1, NULL, NULL,  cgroups_main},
88
89 #ifdef INTERNAL_PLUGIN_NFACCT
90         // nfacct requires root access
91         // so, we build it as an external plugin with setuid to root
92         {"nfacct",              "plugins",      "nfacct",               1, NULL, NULL,  nfacct_main},
93 #endif
94
95         {"plugins.d",   NULL,           NULL,                   1, NULL, NULL,  pluginsd_main},
96         {"check",               "plugins",      "checks",               0, NULL, NULL,  checks_main},
97         {"web",                 NULL,           NULL,                   1, NULL, NULL,  socket_listen_main},
98         {NULL,                  NULL,           NULL,                   0, NULL, NULL,  NULL}
99 };
100
101 int killpid(pid_t pid, int sig)
102 {
103         int ret = -1;
104         debug(D_EXIT, "Request to kill pid %d", pid);
105
106         errno = 0;
107         if(kill(pid, 0) == -1) {
108                 switch(errno) {
109                         case ESRCH:
110                                 error("Request to kill pid %d, but it is not running.", pid);
111                                 break;
112
113                         case EPERM:
114                                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
115                                 break;
116
117                         default:
118                                 error("Request to kill pid %d, but I received an error.", pid);
119                                 break;
120                 }
121         }
122         else {
123                 errno = 0;
124                 ret = kill(pid, sig);
125                 if(ret == -1) {
126                         switch(errno) {
127                                 case ESRCH:
128                                         error("Cannot kill pid %d, but it is not running.", pid);
129                                         break;
130
131                                 case EPERM:
132                                         error("Cannot kill pid %d, but I do not have enough permissions.", pid);
133                                         break;
134
135                                 default:
136                                         error("Cannot kill pid %d, but I received an error.", pid);
137                                         break;
138                         }
139                 }
140         }
141
142         return ret;
143 }
144
145 void kill_childs()
146 {
147         siginfo_t info;
148
149         struct web_client *w;
150         for(w = web_clients; w ; w = w->next) {
151                 debug(D_EXIT, "Stopping web client %s", w->client_ip);
152                 pthread_cancel(w->thread);
153                 pthread_join(w->thread, NULL);
154         }
155
156         int i;
157         for (i = 0; static_threads[i].name != NULL ; i++) {
158                 if(static_threads[i].thread) {
159                         debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
160                         pthread_cancel(*static_threads[i].thread);
161                         pthread_join(*static_threads[i].thread, NULL);
162                         static_threads[i].thread = NULL;
163                 }
164         }
165
166         if(tc_child_pid) {
167                 info("Killing tc-qos-helper procees");
168                 if(killpid(tc_child_pid, SIGTERM) != -1)
169                         waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
170         }
171         tc_child_pid = 0;
172
173         struct plugind *cd;
174         for(cd = pluginsd_root ; cd ; cd = cd->next) {
175                 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
176                 pthread_cancel(cd->thread);
177                 pthread_join(cd->thread, NULL);
178
179                 if(cd->pid && !cd->obsolete) {
180                         debug(D_EXIT, "killing %s plugin process", cd->id);
181                         if(killpid(cd->pid, SIGTERM) != -1)
182                                 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
183                 }
184         }
185
186         // if, for any reason there is any child exited
187         // catch it here
188         waitid(P_PID, 0, &info, WEXITED|WNOHANG);
189
190         debug(D_EXIT, "All threads/childs stopped.");
191 }
192
193 struct option_def options[] = {
194         // opt description                                                       arg name                     default value
195         {'c', "Load alternate configuration file",                               "config_file",                          CONFIG_DIR "/" CONFIG_FILENAME},
196         {'D', "Disable fork into background",                                    NULL,                                   NULL},
197         {'h', "Display help message",                                            NULL,                                   NULL},
198         {'P', "File to save a pid while running",                                "FILE",                                 NULL},
199         {'p', "Port to listen. Can be from 1 to 65535.",                         "port_number",                          "19999"},
200         {'s', "Path to access host /proc and /sys when running in a container.", "PATH",                                 NULL},
201         {'t', "The frequency in seconds, for data collection. \
202                 Same as 'update every' config file option.",                         "seconds",                              "1"},
203         {'l', "The number of entries the netdata daemon will keep in memory \
204                 for each chart dimension. Same as 'history config file option.",     "lines_to_save",                        NULL},
205         {'u', "System username to run as.",                                      "username",                             "netdata"},
206         {'v', "Version of the program",                                          NULL,                                   NULL},
207         {'W', "vendor options.",                                                 "stacksize=<size>|unittest|debug_flag", NULL},
208 };
209
210 void help(int exitcode) {
211         FILE *stream;
212         if(exitcode == 0)
213                 stream = stdout;
214         else
215                 stream = stderr;
216
217         int num_opts = sizeof(options) / sizeof(struct option_def);
218         int i;
219         int max_len_arg = 0;
220
221         // Compute maximum argument length
222         for( i = 0; i < num_opts; i++ ) {
223                 if(options[i].arg_name) {
224                         int len_arg = strlen(options[i].arg_name);
225                         if(len_arg > max_len_arg) max_len_arg = len_arg;
226                 }
227         }
228
229         fprintf(stream, "SYNOPSIS: netdata [options]\n");
230         fprintf(stream, "\n");
231         fprintf(stream, "Options:\n");
232
233         // Output options description.
234         for( i = 0; i < num_opts; i++ ) {
235                 fprintf(stream, "  -%c %-*s  %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
236                 if(options[i].default_value) {
237                         fprintf(stream, " Default: %s\n", options[i].default_value);
238                 } else {
239                         fprintf(stream, "\n");
240                 }
241         }
242
243         fflush(stream);
244         exit(exitcode);
245 }
246
247
248 int main(int argc, char **argv)
249 {
250         int i;
251         int config_loaded = 0;
252         int dont_fork = 0;
253         size_t wanted_stacksize = 0, stacksize = 0;
254         pthread_attr_t attr;
255
256         // global initialization
257         get_HZ();
258
259         // set the name for logging
260         program_name = "netdata";
261
262         // parse command line.
263
264         // parse depercated options
265         // TODO: Remove this block with the next major release.
266         {
267                 void remove_option(int opt_index, int *argc, char **argv) {
268                         int i = opt_index;
269                         // remove the options.
270                         do {
271                                 *argc = *argc - 1;
272                                 for(i = opt_index; i < *argc; i++) {
273                                         argv[i] = argv[i+1];
274                                 }
275                                 i = opt_index;
276                         } while(argv[i][0] != '-' && opt_index >= *argc);
277                 }
278
279                 i = 1;
280                 while(i < argc) {
281                         if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
282                                 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
283                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -P instead.\n", argv[0], argv[i]);
284                                 remove_option(i, &argc, argv);
285                         }
286                         else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
287                                 dont_fork = 1;
288                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
289                                 remove_option(i, &argc, argv);
290                         }
291                         else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
292                                 config_set("global", "host access prefix", argv[i+1]);
293                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -s instead.\n", argv[0], argv[i]);
294                                 remove_option(i, &argc, argv);
295                         }
296                         else i++;
297                 }
298         }
299
300         // parse options
301         {
302                 int num_opts = sizeof(options) / sizeof(struct option_def);
303                 char optstring[(num_opts * 2) + 1];
304
305                 int string_i = 0;
306                 for( i = 0; i < num_opts; i++ ) {
307                         optstring[string_i] = options[i].val;
308                         string_i++;
309                         if(options[i].arg_name) {
310                                 optstring[string_i] = ':';
311                                 string_i++;
312                         }
313                 }
314
315                 int opt;
316                 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
317                         switch(opt) {
318                                 case 'c':
319                                         if(load_config(optarg, 1) != 1) {
320                                                 error("Cannot load configuration file %s.", optarg);
321                                                 exit(1);
322                                         }
323                                         else {
324                                                 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
325                                                 config_loaded = 1;
326                                         }
327                                         break;
328                                 case 'D':
329                                         dont_fork = 1;
330                                         break;
331                                 case 'h':
332                                         help(0);
333                                         break;
334                                 case 'P':
335                                         strncpy(pidfile, optarg, FILENAME_MAX);
336                                         pidfile[FILENAME_MAX] = '\0';
337                                         break;
338                                 case 'p':
339                                         config_set("global", "port", optarg);
340                                         break;
341                                 case 's':
342                                         config_set("global", "host access prefix", optarg);
343                                         break;
344                                 case 't':
345                                         config_set("global", "update every", optarg);
346                                         break;
347                                 case 'u':
348                                         config_set("global", "run as user", optarg);
349                                         break;
350                                 case 'v':
351                                         // TODO: Outsource version to makefile which can compute version from git.
352                                         printf("netdata 1.1.0\n");
353                                         return 0;
354                                         break;
355                                 case 'l':
356                                         config_set("global", "history", optarg);
357                                         break;
358                                 case 'W': 
359                                         {
360                                                 char* stacksize = "stacksize=";
361                                                 char* debug_flags_string = "debug_flags=";
362                                                 if(strcmp(optarg, "unittest") == 0) {
363                                                         rrd_update_every = 1;
364                                                         if(run_all_mockup_tests()) exit(1);
365                                                         if(unit_test_storage()) exit(1);
366                                                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
367                                                         exit(0);
368                                                 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
369                                                         optarg += strlen(stacksize);
370                                                         config_set("global", "pthread stack size", optarg);
371                                                 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
372                                                         optarg += strlen(debug_flags_string);
373                                                         config_set("global", "debug flags",  optarg);
374                                                         debug_flags = strtoull(optarg, NULL, 0);
375                                                 }
376                                         }
377                                         break;
378                                 default: /* ? */
379                                         help(1);
380                                         break;
381                         }
382                 } 
383         }
384
385         if(!config_loaded) load_config(NULL, 0);
386
387         // prepare configuration environment variables for the plugins
388         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
389         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
390         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
391         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
392         setenv("NETDATA_LIB_DIR"    , config_get("global", "lib directory"      , VARLIB_DIR) , 1);
393         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
394         setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);
395         setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);
396
397         // avoid extended to stat(/etc/localtime)
398         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
399         setenv("TZ", ":/etc/localtime", 0);
400
401         // cd to /tmp to avoid any plugins writing files at random places
402         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
403
404         char *input_log_file = NULL;
405         char *output_log_file = NULL;
406         char *error_log_file = NULL;
407         char *access_log_file = NULL;
408         char *user = NULL;
409         {
410                 char buffer[1024];
411
412                 // --------------------------------------------------------------------
413
414                 sprintf(buffer, "0x%08llx", 0ULL);
415                 char *flags = config_get("global", "debug flags", buffer);
416                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
417
418                 debug_flags = strtoull(flags, NULL, 0);
419                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
420
421                 if(debug_flags != 0) {
422                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
423                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
424                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
425                         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
426                 }
427
428                 // --------------------------------------------------------------------
429
430 #ifdef MADV_MERGEABLE
431                 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
432 #else
433 #warning "Kernel memory deduplication (KSM) is not available"
434 #endif
435
436                 // --------------------------------------------------------------------
437
438
439                 global_host_prefix = config_get("global", "host access prefix", "");
440                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
441
442                 // --------------------------------------------------------------------
443
444                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
445                 if(strcmp(output_log_file, "syslog") == 0) {
446                         output_log_syslog = 1;
447                         output_log_file = NULL;
448                 }
449                 else if(strcmp(output_log_file, "none") == 0) {
450                         output_log_syslog = 0;
451                         output_log_file = NULL;
452                 }
453                 else output_log_syslog = 0;
454
455                 // --------------------------------------------------------------------
456
457                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
458                 if(strcmp(error_log_file, "syslog") == 0) {
459                         error_log_syslog = 1;
460                         error_log_file = NULL;
461                 }
462                 else if(strcmp(error_log_file, "none") == 0) {
463                         error_log_syslog = 0;
464                         error_log_file = NULL;
465                         // optimization - do not even generate debug log entries
466                 }
467                 else error_log_syslog = 0;
468
469                 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
470                 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
471
472                 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
473                 setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
474
475                 // --------------------------------------------------------------------
476
477                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
478                 if(strcmp(access_log_file, "syslog") == 0) {
479                         access_log_syslog = 1;
480                         access_log_file = NULL;
481                 }
482                 else if(strcmp(access_log_file, "none") == 0) {
483                         access_log_syslog = 0;
484                         access_log_file = NULL;
485                 }
486                 else access_log_syslog = 0;
487
488                 // --------------------------------------------------------------------
489
490                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
491
492                 // --------------------------------------------------------------------
493
494                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
495                         error("WARNING: Cannot get machine hostname.");
496                 hostname = config_get("global", "hostname", buffer);
497                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
498
499                 // --------------------------------------------------------------------
500
501                 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
502                 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
503                         info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
504                         rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
505                 }
506                 else {
507                         debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
508                 }
509
510                 // --------------------------------------------------------------------
511
512                 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
513                 if(rrd_update_every < 1 || rrd_update_every > 600) {
514                         info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
515                         rrd_update_every = UPDATE_EVERY;
516                 }
517                 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
518
519                 // let the plugins know the min update_every
520                 {
521                         char buf[51];
522                         snprintfz(buf, 50, "%d", rrd_update_every);
523                         setenv("NETDATA_UPDATE_EVERY", buf, 1);
524                 }
525
526                 // --------------------------------------------------------------------
527
528                 // block signals while initializing threads.
529                 // this causes the threads to block signals.
530                 sigset_t sigset;
531                 sigfillset(&sigset);
532
533                 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
534                         error("Could not block signals for threads");
535                 }
536
537                 // Catch signals which we want to use to quit savely
538                 struct sigaction sa;
539                 sigemptyset(&sa.sa_mask);
540                 sigaddset(&sa.sa_mask, SIGHUP);
541                 sigaddset(&sa.sa_mask, SIGINT);
542                 sigaddset(&sa.sa_mask, SIGTERM);
543                 sa.sa_handler = sig_handler;
544                 sa.sa_flags = 0;
545                 if(sigaction(SIGHUP, &sa, NULL) == -1) {
546                         error("Failed to change signal handler for SIGHUP");
547                 }
548                 if(sigaction(SIGINT, &sa, NULL) == -1) {
549                         error("Failed to change signal handler for SIGINT");
550                 }
551                 if(sigaction(SIGTERM, &sa, NULL) == -1) {
552                         error("Failed to change signal handler for SIGTERM");
553                 }
554                 // Ignore SIGPIPE completely.
555                 // INFO: If we add signals here we have to unblock them
556                 // at popen.c when running a external plugin.
557                 sa.sa_handler = SIG_IGN;
558                 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
559                         error("Failed to change signal handler for SIGTERM");
560                 }
561
562                 // --------------------------------------------------------------------
563
564                 i = pthread_attr_init(&attr);
565                 if(i != 0)
566                         fatal("pthread_attr_init() failed with code %d.", i);
567
568                 i = pthread_attr_getstacksize(&attr, &stacksize);
569                 if(i != 0)
570                         fatal("pthread_attr_getstacksize() failed with code %d.", i);
571                 else
572                         debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
573
574                 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
575
576                 // --------------------------------------------------------------------
577
578                 for (i = 0; static_threads[i].name != NULL ; i++) {
579                         struct netdata_static_thread *st = &static_threads[i];
580
581                         if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
582                         if(st->enabled && st->init_routine) st->init_routine();
583                 }
584
585                 // --------------------------------------------------------------------
586
587                 // get the user we should run
588                 // IMPORTANT: this is required before web_files_uid()
589                 user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
590
591                 // IMPORTANT: these have to run once, while single threaded
592                 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
593                 web_files_gid();
594
595                 // --------------------------------------------------------------------
596
597                 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
598
599                 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
600                 if(listen_port < 1 || listen_port > 65535) {
601                         info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
602                         listen_port = LISTEN_PORT;
603                 }
604                 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
605
606                 int ip = 0;
607                 char *ipv = config_get("global", "ip version", "any");
608                 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
609                 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
610                 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
611                 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
612
613                 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
614                 if(listen_fd < 0) {
615                         listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
616                         if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
617                 }
618
619                 if(listen_fd < 0) fatal("Cannot listen socket.");
620         }
621
622         // never become a problem
623         if(nice(20) == -1) error("Cannot lower my CPU priority.");
624
625         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
626                 fatal("Cannot demonize myself.");
627
628 #ifdef NETDATA_INTERNAL_CHECKS
629         if(debug_flags != 0) {
630                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
631                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
632                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
633                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
634         }
635 #endif /* NETDATA_INTERNAL_CHECKS */
636
637         if(output_log_syslog || error_log_syslog || access_log_syslog)
638                 openlog("netdata", LOG_PID, LOG_DAEMON);
639
640         info("NetData started on pid %d", getpid());
641
642
643         // ------------------------------------------------------------------------
644         // get default pthread stack size
645
646         if(stacksize < wanted_stacksize) {
647                 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
648                 if(i != 0)
649                         fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
650                 else
651                         info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
652         }
653
654         // --------------------------------------------------------------------
655         // initialize the registry
656
657         registry_init();
658
659         // ------------------------------------------------------------------------
660         // spawn the threads
661
662         for (i = 0; static_threads[i].name != NULL ; i++) {
663                 struct netdata_static_thread *st = &static_threads[i];
664
665                 if(st->enabled) {
666                         st->thread = malloc(sizeof(pthread_t));
667                         if(!st->thread)
668                                 fatal("Cannot allocate pthread_t memory");
669
670                         info("Starting thread %s.", st->name);
671
672                         if(pthread_create(st->thread, &attr, st->start_routine, NULL))
673                                 error("failed to create new thread for %s.", st->name);
674
675                         else if(pthread_detach(*st->thread))
676                                 error("Cannot request detach of newly created %s thread.", st->name);
677                 }
678                 else info("Not starting thread %s.", st->name);
679         }
680
681         // ------------------------------------------------------------------------
682         // block signals while initializing threads.
683         sigset_t sigset;
684         sigfillset(&sigset);
685
686         if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
687                 error("Could not unblock signals for threads");
688         }
689
690         // Handle flags set in the signal handler.
691         while(1) {
692                 pause();
693                 if(netdata_exit) {
694                         info("Exit main loop of netdata.");
695                         netdata_cleanup_and_exit(0);
696                         exit(0);
697                 }
698         }
699 }