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