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