]> arthur.barton.de Git - netdata.git/blob - src/main.c
Merge pull request #421 from simonnagl/feature/command_line
[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         {'i', "The IP address to listen to.",                                    "address",                              "All addresses"},
200         {'p', "Port to listen. Can be from 1 to 65535.",                         "port_number",                          "19999"},
201         {'s', "Path to access host /proc and /sys when running in a container.", "PATH",                                 NULL},
202         {'t', "The frequency in seconds, for data collection. \
203 Same as 'update every' config file option.",                                 "seconds",                              "1"},
204         {'u', "System username to run as.",                                      "username",                             "netdata"},
205         {'v', "Version of the program",                                          NULL,                                   NULL},
206         {'W', "vendor options.",                                                 "stacksize=<size>|unittest|debug_flag", NULL},
207 };
208
209 void help(int exitcode) {
210         FILE *stream;
211         if(exitcode == 0)
212                 stream = stdout;
213         else
214                 stream = stderr;
215
216         int num_opts = sizeof(options) / sizeof(struct option_def);
217         int i;
218         int max_len_arg = 0;
219
220         // Compute maximum argument length
221         for( i = 0; i < num_opts; i++ ) {
222                 if(options[i].arg_name) {
223                         int len_arg = strlen(options[i].arg_name);
224                         if(len_arg > max_len_arg) max_len_arg = len_arg;
225                 }
226         }
227
228         fprintf(stream, "SYNOPSIS: netdata [options]\n");
229         fprintf(stream, "\n");
230         fprintf(stream, "Options:\n");
231
232         // Output options description.
233         for( i = 0; i < num_opts; i++ ) {
234                 fprintf(stream, "  -%c %-*s  %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
235                 if(options[i].default_value) {
236                         fprintf(stream, " Default: %s\n", options[i].default_value);
237                 } else {
238                         fprintf(stream, "\n");
239                 }
240         }
241
242         fflush(stream);
243         exit(exitcode);
244 }
245
246 // TODO: Remove this function with the nix major release.
247 void remove_option(int opt_index, int *argc, char **argv) {
248         int i = opt_index;
249         // remove the options.
250         do {
251                 *argc = *argc - 1;
252                 for(i = opt_index; i < *argc; i++) {
253                         argv[i] = argv[i+1];
254                 }
255                 i = opt_index;
256         } while(argv[i][0] != '-' && opt_index >= *argc);
257 }
258
259
260 int main(int argc, char **argv)
261 {
262         int i;
263         int config_loaded = 0;
264         int dont_fork = 0;
265         size_t wanted_stacksize = 0, stacksize = 0;
266         pthread_attr_t attr;
267
268         // global initialization
269         get_HZ();
270
271         // set the name for logging
272         program_name = "netdata";
273
274         // parse command line.
275
276         // parse depercated options
277         // TODO: Remove this block with the next major release.
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 if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
297                                 config_set("global", "history", argv[i+1]);
298                                 fprintf(stderr, "%s: deprecate option -- %s -- This option will be rmoved with V2.*.\n", argv[0], argv[i]);
299                                 remove_option(i, &argc, argv);
300                         }
301                         else i++;
302                 }
303         }
304
305         // parse options
306         {
307                 int num_opts = sizeof(options) / sizeof(struct option_def);
308                 char optstring[(num_opts * 2) + 1];
309
310                 int string_i = 0;
311                 for( i = 0; i < num_opts; i++ ) {
312                         optstring[string_i] = options[i].val;
313                         string_i++;
314                         if(options[i].arg_name) {
315                                 optstring[string_i] = ':';
316                                 string_i++;
317                         }
318                 }
319
320                 int opt;
321                 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
322                         switch(opt) {
323                                 case 'c':
324                                         if(load_config(optarg, 1) != 1) {
325                                                 error("Cannot load configuration file %s.", optarg);
326                                                 exit(1);
327                                         }
328                                         else {
329                                                 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
330                                                 config_loaded = 1;
331                                         }
332                                         break;
333                                 case 'D':
334                                         dont_fork = 1;
335                                         break;
336                                 case 'h':
337                                         help(0);
338                                         break;
339                                 case 'i':
340                                         config_set("global", "bind socket to IP", optarg);
341                                         break;
342                                 case 'P':
343                                         strncpy(pidfile, optarg, FILENAME_MAX);
344                                         pidfile[FILENAME_MAX] = '\0';
345                                         break;
346                                 case 'p':
347                                         config_set("global", "port", optarg);
348                                         break;
349                                 case 's':
350                                         config_set("global", "host access prefix", optarg);
351                                         break;
352                                 case 't':
353                                         config_set("global", "update every", optarg);
354                                         break;
355                                 case 'u':
356                                         config_set("global", "run as user", optarg);
357                                         break;
358                                 case 'v':
359                                         // TODO: Outsource version to makefile which can compute version from git.
360                                         printf("netdata 1.1.0\n");
361                                         return 0;
362                                         break;
363                                 case 'W': 
364                                         {
365                                                 char* stacksize = "stacksize=";
366                                                 char* debug_flags_string = "debug_flags=";
367                                                 if(strcmp(optarg, "unittest") == 0) {
368                                                         rrd_update_every = 1;
369                                                         if(run_all_mockup_tests()) exit(1);
370                                                         if(unit_test_storage()) exit(1);
371                                                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
372                                                         exit(0);
373                                                 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
374                                                         optarg += strlen(stacksize);
375                                                         config_set("global", "pthread stack size", optarg);
376                                                 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
377                                                         optarg += strlen(debug_flags_string);
378                                                         config_set("global", "debug flags",  optarg);
379                                                         debug_flags = strtoull(optarg, NULL, 0);
380                                                 }
381                                         }
382                                         break;
383                                 default: /* ? */
384                                         help(1);
385                                         break;
386                         }
387                 } 
388         }
389
390         if(!config_loaded) load_config(NULL, 0);
391
392         // prepare configuration environment variables for the plugins
393         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
394         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
395         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
396         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
397         setenv("NETDATA_LIB_DIR"    , config_get("global", "lib directory"      , VARLIB_DIR) , 1);
398         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
399         setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);
400         setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);
401
402         // avoid extended to stat(/etc/localtime)
403         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
404         setenv("TZ", ":/etc/localtime", 0);
405
406         // cd to /tmp to avoid any plugins writing files at random places
407         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
408
409         char *input_log_file = NULL;
410         char *output_log_file = NULL;
411         char *error_log_file = NULL;
412         char *access_log_file = NULL;
413         char *user = NULL;
414         {
415                 char buffer[1024];
416
417                 // --------------------------------------------------------------------
418
419                 sprintf(buffer, "0x%08llx", 0ULL);
420                 char *flags = config_get("global", "debug flags", buffer);
421                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
422
423                 debug_flags = strtoull(flags, NULL, 0);
424                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
425
426                 if(debug_flags != 0) {
427                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
428                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
429                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
430                         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
431                 }
432
433                 // --------------------------------------------------------------------
434
435 #ifdef MADV_MERGEABLE
436                 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
437 #else
438 #warning "Kernel memory deduplication (KSM) is not available"
439 #endif
440
441                 // --------------------------------------------------------------------
442
443
444                 global_host_prefix = config_get("global", "host access prefix", "");
445                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
446
447                 // --------------------------------------------------------------------
448
449                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
450                 if(strcmp(output_log_file, "syslog") == 0) {
451                         output_log_syslog = 1;
452                         output_log_file = NULL;
453                 }
454                 else if(strcmp(output_log_file, "none") == 0) {
455                         output_log_syslog = 0;
456                         output_log_file = NULL;
457                 }
458                 else output_log_syslog = 0;
459
460                 // --------------------------------------------------------------------
461
462                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
463                 if(strcmp(error_log_file, "syslog") == 0) {
464                         error_log_syslog = 1;
465                         error_log_file = NULL;
466                 }
467                 else if(strcmp(error_log_file, "none") == 0) {
468                         error_log_syslog = 0;
469                         error_log_file = NULL;
470                         // optimization - do not even generate debug log entries
471                 }
472                 else error_log_syslog = 0;
473
474                 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
475                 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
476
477                 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
478                 setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
479
480                 // --------------------------------------------------------------------
481
482                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
483                 if(strcmp(access_log_file, "syslog") == 0) {
484                         access_log_syslog = 1;
485                         access_log_file = NULL;
486                 }
487                 else if(strcmp(access_log_file, "none") == 0) {
488                         access_log_syslog = 0;
489                         access_log_file = NULL;
490                 }
491                 else access_log_syslog = 0;
492
493                 // --------------------------------------------------------------------
494
495                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
496
497                 // --------------------------------------------------------------------
498
499                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
500                         error("WARNING: Cannot get machine hostname.");
501                 hostname = config_get("global", "hostname", buffer);
502                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
503
504                 // --------------------------------------------------------------------
505
506                 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
507                 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
508                         info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
509                         rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
510                 }
511                 else {
512                         debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
513                 }
514
515                 // --------------------------------------------------------------------
516
517                 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
518                 if(rrd_update_every < 1 || rrd_update_every > 600) {
519                         info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
520                         rrd_update_every = UPDATE_EVERY;
521                 }
522                 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
523
524                 // let the plugins know the min update_every
525                 {
526                         char buf[51];
527                         snprintfz(buf, 50, "%d", rrd_update_every);
528                         setenv("NETDATA_UPDATE_EVERY", buf, 1);
529                 }
530
531                 // --------------------------------------------------------------------
532
533                 // block signals while initializing threads.
534                 // this causes the threads to block signals.
535                 sigset_t sigset;
536                 sigfillset(&sigset);
537
538                 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
539                         error("Could not block signals for threads");
540                 }
541
542                 // Catch signals which we want to use to quit savely
543                 struct sigaction sa;
544                 sigemptyset(&sa.sa_mask);
545                 sigaddset(&sa.sa_mask, SIGHUP);
546                 sigaddset(&sa.sa_mask, SIGINT);
547                 sigaddset(&sa.sa_mask, SIGTERM);
548                 sa.sa_handler = sig_handler;
549                 sa.sa_flags = 0;
550                 if(sigaction(SIGHUP, &sa, NULL) == -1) {
551                         error("Failed to change signal handler for SIGHUP");
552                 }
553                 if(sigaction(SIGINT, &sa, NULL) == -1) {
554                         error("Failed to change signal handler for SIGINT");
555                 }
556                 if(sigaction(SIGTERM, &sa, NULL) == -1) {
557                         error("Failed to change signal handler for SIGTERM");
558                 }
559                 // Ignore SIGPIPE completely.
560                 // INFO: If we add signals here we have to unblock them
561                 // at popen.c when running a external plugin.
562                 sa.sa_handler = SIG_IGN;
563                 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
564                         error("Failed to change signal handler for SIGTERM");
565                 }
566
567                 // --------------------------------------------------------------------
568
569                 i = pthread_attr_init(&attr);
570                 if(i != 0)
571                         fatal("pthread_attr_init() failed with code %d.", i);
572
573                 i = pthread_attr_getstacksize(&attr, &stacksize);
574                 if(i != 0)
575                         fatal("pthread_attr_getstacksize() failed with code %d.", i);
576                 else
577                         debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
578
579                 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
580
581                 // --------------------------------------------------------------------
582
583                 for (i = 0; static_threads[i].name != NULL ; i++) {
584                         struct netdata_static_thread *st = &static_threads[i];
585
586                         if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
587                         if(st->enabled && st->init_routine) st->init_routine();
588                 }
589
590                 // --------------------------------------------------------------------
591
592                 // get the user we should run
593                 // IMPORTANT: this is required before web_files_uid()
594                 user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
595
596                 // IMPORTANT: these have to run once, while single threaded
597                 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
598                 web_files_gid();
599
600                 // --------------------------------------------------------------------
601
602                 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
603
604                 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
605                 if(listen_port < 1 || listen_port > 65535) {
606                         info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
607                         listen_port = LISTEN_PORT;
608                 }
609                 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
610
611                 int ip = 0;
612                 char *ipv = config_get("global", "ip version", "any");
613                 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
614                 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
615                 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
616                 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
617
618                 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
619                 if(listen_fd < 0) {
620                         listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
621                         if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
622                 }
623
624                 if(listen_fd < 0) fatal("Cannot listen socket.");
625         }
626
627         // never become a problem
628         if(nice(20) == -1) error("Cannot lower my CPU priority.");
629
630         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
631                 fatal("Cannot demonize myself.");
632
633 #ifdef NETDATA_INTERNAL_CHECKS
634         if(debug_flags != 0) {
635                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
636                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
637                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
638                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
639         }
640 #endif /* NETDATA_INTERNAL_CHECKS */
641
642         if(output_log_syslog || error_log_syslog || access_log_syslog)
643                 openlog("netdata", LOG_PID, LOG_DAEMON);
644
645         info("NetData started on pid %d", getpid());
646
647
648         // ------------------------------------------------------------------------
649         // get default pthread stack size
650
651         if(stacksize < wanted_stacksize) {
652                 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
653                 if(i != 0)
654                         fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
655                 else
656                         info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
657         }
658
659         // --------------------------------------------------------------------
660         // initialize the registry
661
662         registry_init();
663
664         // ------------------------------------------------------------------------
665         // spawn the threads
666
667         for (i = 0; static_threads[i].name != NULL ; i++) {
668                 struct netdata_static_thread *st = &static_threads[i];
669
670                 if(st->enabled) {
671                         st->thread = malloc(sizeof(pthread_t));
672                         if(!st->thread)
673                                 fatal("Cannot allocate pthread_t memory");
674
675                         info("Starting thread %s.", st->name);
676
677                         if(pthread_create(st->thread, &attr, st->start_routine, NULL))
678                                 error("failed to create new thread for %s.", st->name);
679
680                         else if(pthread_detach(*st->thread))
681                                 error("Cannot request detach of newly created %s thread.", st->name);
682                 }
683                 else info("Not starting thread %s.", st->name);
684         }
685
686         // ------------------------------------------------------------------------
687         // block signals while initializing threads.
688         sigset_t sigset;
689         sigfillset(&sigset);
690
691         if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
692                 error("Could not unblock signals for threads");
693         }
694
695         // Handle flags set in the signal handler.
696         while(1) {
697                 pause();
698                 if(netdata_exit) {
699                         info("Exit main loop of netdata.");
700                         netdata_cleanup_and_exit(0);
701                         exit(0);
702                 }
703         }
704 }