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