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