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