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