]> arthur.barton.de Git - netdata.git/blob - src/main.c
added configuration options for controlling web compression level and strategy and...
[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 {
45         netdata_exit = 1;
46         rrdset_save_all();
47         // kill_childs();
48
49         // let it log a few more error messages
50         error_log_limit_reset();
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 #ifdef NETDATA_WITH_ZLIB
106         web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
107
108         char *s = config_get("global", "web compression strategy", "default");
109         if(!strcmp(s, "default"))
110                 web_gzip_strategy = Z_DEFAULT_STRATEGY;
111         else if(!strcmp(s, "filtered"))
112                 web_gzip_strategy = Z_FILTERED;
113         else if(!strcmp(s, "huffman only"))
114                 web_gzip_strategy = Z_HUFFMAN_ONLY;
115         else if(!strcmp(s, "rle"))
116                 web_gzip_strategy = Z_RLE;
117         else if(!strcmp(s, "fixed"))
118                 web_gzip_strategy = Z_FIXED;
119         else {
120                 error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.");
121                 web_gzip_strategy = Z_DEFAULT_STRATEGY;
122         }
123
124         web_gzip_level = (int)config_get_number("global", "web compression level", 3);
125         if(web_gzip_level < 1) {
126                 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).");
127                 web_gzip_level = 1;
128         }
129         else if(web_gzip_level > 9) {
130                 error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).");
131                 web_gzip_level = 9;
132         }
133 #endif /* NETDATA_WITH_ZLIB */
134 }
135
136
137 int killpid(pid_t pid, int sig)
138 {
139         int ret = -1;
140         debug(D_EXIT, "Request to kill pid %d", pid);
141
142         errno = 0;
143         if(kill(pid, 0) == -1) {
144                 switch(errno) {
145                         case ESRCH:
146                                 error("Request to kill pid %d, but it is not running.", pid);
147                                 break;
148
149                         case EPERM:
150                                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
151                                 break;
152
153                         default:
154                                 error("Request to kill pid %d, but I received an error.", pid);
155                                 break;
156                 }
157         }
158         else {
159                 errno = 0;
160                 ret = kill(pid, sig);
161                 if(ret == -1) {
162                         switch(errno) {
163                                 case ESRCH:
164                                         error("Cannot kill pid %d, but it is not running.", pid);
165                                         break;
166
167                                 case EPERM:
168                                         error("Cannot kill pid %d, but I do not have enough permissions.", pid);
169                                         break;
170
171                                 default:
172                                         error("Cannot kill pid %d, but I received an error.", pid);
173                                         break;
174                         }
175                 }
176         }
177
178         return ret;
179 }
180
181 void kill_childs()
182 {
183         siginfo_t info;
184
185         struct web_client *w;
186         for(w = web_clients; w ; w = w->next) {
187                 debug(D_EXIT, "Stopping web client %s", w->client_ip);
188                 pthread_cancel(w->thread);
189                 pthread_join(w->thread, NULL);
190         }
191
192         int i;
193         for (i = 0; static_threads[i].name != NULL ; i++) {
194                 if(static_threads[i].thread) {
195                         debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
196                         pthread_cancel(*static_threads[i].thread);
197                         pthread_join(*static_threads[i].thread, NULL);
198                         static_threads[i].thread = NULL;
199                 }
200         }
201
202         if(tc_child_pid) {
203                 info("Killing tc-qos-helper procees");
204                 if(killpid(tc_child_pid, SIGTERM) != -1)
205                         waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
206         }
207         tc_child_pid = 0;
208
209         struct plugind *cd;
210         for(cd = pluginsd_root ; cd ; cd = cd->next) {
211                 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
212                 pthread_cancel(cd->thread);
213                 pthread_join(cd->thread, NULL);
214
215                 if(cd->pid && !cd->obsolete) {
216                         debug(D_EXIT, "killing %s plugin process", cd->id);
217                         if(killpid(cd->pid, SIGTERM) != -1)
218                                 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
219                 }
220         }
221
222         // if, for any reason there is any child exited
223         // catch it here
224         waitid(P_PID, 0, &info, WEXITED|WNOHANG);
225
226         debug(D_EXIT, "All threads/childs stopped.");
227 }
228
229 struct option_def options[] = {
230         // opt description                                                       arg name                     default value
231         {'c', "Load alternate configuration file",                               "config_file",                          CONFIG_DIR "/" CONFIG_FILENAME},
232         {'D', "Disable fork into background",                                    NULL,                                   NULL},
233         {'h', "Display help message",                                            NULL,                                   NULL},
234         {'P', "File to save a pid while running",                                "FILE",                                 NULL},
235         {'i', "The IP address to listen to.",                                    "address",                              "All addresses"},
236         {'p', "Port to listen. Can be from 1 to 65535.",                         "port_number",                          "19999"},
237         {'s', "Path to access host /proc and /sys when running in a container.", "PATH",                                 NULL},
238         {'t', "The frequency in seconds, for data collection. \
239 Same as 'update every' config file option.",                                 "seconds",                              "1"},
240         {'u', "System username to run as.",                                      "username",                             "netdata"},
241         {'v', "Version of the program",                                          NULL,                                   NULL},
242         {'W', "vendor options.",                                                 "stacksize=<size>|unittest|debug_flag", NULL},
243 };
244
245 void help(int exitcode) {
246         FILE *stream;
247         if(exitcode == 0)
248                 stream = stdout;
249         else
250                 stream = stderr;
251
252         int num_opts = sizeof(options) / sizeof(struct option_def);
253         int i;
254         int max_len_arg = 0;
255
256         // Compute maximum argument length
257         for( i = 0; i < num_opts; i++ ) {
258                 if(options[i].arg_name) {
259                         int len_arg = strlen(options[i].arg_name);
260                         if(len_arg > max_len_arg) max_len_arg = len_arg;
261                 }
262         }
263
264         fprintf(stream, "SYNOPSIS: netdata [options]\n");
265         fprintf(stream, "\n");
266         fprintf(stream, "Options:\n");
267
268         // Output options description.
269         for( i = 0; i < num_opts; i++ ) {
270                 fprintf(stream, "  -%c %-*s  %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
271                 if(options[i].default_value) {
272                         fprintf(stream, " Default: %s\n", options[i].default_value);
273                 } else {
274                         fprintf(stream, "\n");
275                 }
276         }
277
278         fflush(stream);
279         exit(exitcode);
280 }
281
282 // TODO: Remove this function with the nix major release.
283 void remove_option(int opt_index, int *argc, char **argv) {
284         int i = opt_index;
285         // remove the options.
286         do {
287                 *argc = *argc - 1;
288                 for(i = opt_index; i < *argc; i++) {
289                         argv[i] = argv[i+1];
290                 }
291                 i = opt_index;
292         } while(argv[i][0] != '-' && opt_index >= *argc);
293 }
294
295
296 int main(int argc, char **argv)
297 {
298         int i;
299         int config_loaded = 0;
300         int dont_fork = 0;
301         size_t wanted_stacksize = 0, stacksize = 0;
302         pthread_attr_t attr;
303
304         // global initialization
305         get_HZ();
306
307         // set the name for logging
308         program_name = "netdata";
309
310         // parse command line.
311
312         // parse depercated options
313         // TODO: Remove this block with the next major release.
314         {
315                 i = 1;
316                 while(i < argc) {
317                         if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
318                                 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
319                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -P instead.\n", argv[0], argv[i]);
320                                 remove_option(i, &argc, argv);
321                         }
322                         else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
323                                 dont_fork = 1;
324                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
325                                 remove_option(i, &argc, argv);
326                         }
327                         else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
328                                 config_set("global", "host access prefix", argv[i+1]);
329                                 fprintf(stderr, "%s: deprecate option -- %s -- please use -s instead.\n", argv[0], argv[i]);
330                                 remove_option(i, &argc, argv);
331                         }
332                         else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
333                                 config_set("global", "history", argv[i+1]);
334                                 fprintf(stderr, "%s: deprecate option -- %s -- This option will be rmoved with V2.*.\n", argv[0], argv[i]);
335                                 remove_option(i, &argc, argv);
336                         }
337                         else i++;
338                 }
339         }
340
341         // parse options
342         {
343                 int num_opts = sizeof(options) / sizeof(struct option_def);
344                 char optstring[(num_opts * 2) + 1];
345
346                 int string_i = 0;
347                 for( i = 0; i < num_opts; i++ ) {
348                         optstring[string_i] = options[i].val;
349                         string_i++;
350                         if(options[i].arg_name) {
351                                 optstring[string_i] = ':';
352                                 string_i++;
353                         }
354                 }
355
356                 int opt;
357                 while( (opt = getopt(argc, argv, optstring)) != -1 ) {
358                         switch(opt) {
359                                 case 'c':
360                                         if(load_config(optarg, 1) != 1) {
361                                                 error("Cannot load configuration file %s.", optarg);
362                                                 exit(1);
363                                         }
364                                         else {
365                                                 debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
366                                                 config_loaded = 1;
367                                         }
368                                         break;
369                                 case 'D':
370                                         dont_fork = 1;
371                                         break;
372                                 case 'h':
373                                         help(0);
374                                         break;
375                                 case 'i':
376                                         config_set("global", "bind socket to IP", optarg);
377                                         break;
378                                 case 'P':
379                                         strncpy(pidfile, optarg, FILENAME_MAX);
380                                         pidfile[FILENAME_MAX] = '\0';
381                                         break;
382                                 case 'p':
383                                         config_set("global", "port", optarg);
384                                         break;
385                                 case 's':
386                                         config_set("global", "host access prefix", optarg);
387                                         break;
388                                 case 't':
389                                         config_set("global", "update every", optarg);
390                                         break;
391                                 case 'u':
392                                         config_set("global", "run as user", optarg);
393                                         break;
394                                 case 'v':
395                                         // TODO: Outsource version to makefile which can compute version from git.
396                                         printf("netdata 1.1.0\n");
397                                         return 0;
398                                         break;
399                                 case 'W': 
400                                         {
401                                                 char* stacksize = "stacksize=";
402                                                 char* debug_flags_string = "debug_flags=";
403                                                 if(strcmp(optarg, "unittest") == 0) {
404                                                         rrd_update_every = 1;
405                                                         if(run_all_mockup_tests()) exit(1);
406                                                         if(unit_test_storage()) exit(1);
407                                                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
408                                                         exit(0);
409                                                 } else if(strncmp(optarg, stacksize, strlen(stacksize)) == 0) {
410                                                         optarg += strlen(stacksize);
411                                                         config_set("global", "pthread stack size", optarg);
412                                                 } else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
413                                                         optarg += strlen(debug_flags_string);
414                                                         config_set("global", "debug flags",  optarg);
415                                                         debug_flags = strtoull(optarg, NULL, 0);
416                                                 }
417                                         }
418                                         break;
419                                 default: /* ? */
420                                         help(1);
421                                         break;
422                         }
423                 } 
424         }
425
426         if(!config_loaded) load_config(NULL, 0);
427
428         // prepare configuration environment variables for the plugins
429         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
430         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
431         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
432         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
433         setenv("NETDATA_LIB_DIR"    , config_get("global", "lib directory"      , VARLIB_DIR) , 1);
434         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
435         setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);
436         setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);
437
438         // avoid extended to stat(/etc/localtime)
439         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
440         setenv("TZ", ":/etc/localtime", 0);
441
442         // cd to /tmp to avoid any plugins writing files at random places
443         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
444
445         char *input_log_file = NULL;
446         char *output_log_file = NULL;
447         char *error_log_file = NULL;
448         char *access_log_file = NULL;
449         char *user = NULL;
450         {
451                 char buffer[1024];
452
453                 // --------------------------------------------------------------------
454
455                 sprintf(buffer, "0x%08llx", 0ULL);
456                 char *flags = config_get("global", "debug flags", buffer);
457                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
458
459                 debug_flags = strtoull(flags, NULL, 0);
460                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
461
462                 if(debug_flags != 0) {
463                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
464                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
465                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
466                         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
467                 }
468
469                 // --------------------------------------------------------------------
470
471 #ifdef MADV_MERGEABLE
472                 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
473 #else
474 #warning "Kernel memory deduplication (KSM) is not available"
475 #endif
476
477                 // --------------------------------------------------------------------
478
479
480                 global_host_prefix = config_get("global", "host access prefix", "");
481                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
482
483                 // --------------------------------------------------------------------
484
485                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
486                 if(strcmp(output_log_file, "syslog") == 0) {
487                         output_log_syslog = 1;
488                         output_log_file = NULL;
489                 }
490                 else if(strcmp(output_log_file, "none") == 0) {
491                         output_log_syslog = 0;
492                         output_log_file = NULL;
493                 }
494                 else output_log_syslog = 0;
495
496                 // --------------------------------------------------------------------
497
498                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
499                 if(strcmp(error_log_file, "syslog") == 0) {
500                         error_log_syslog = 1;
501                         error_log_file = NULL;
502                 }
503                 else if(strcmp(error_log_file, "none") == 0) {
504                         error_log_syslog = 0;
505                         error_log_file = NULL;
506                         // optimization - do not even generate debug log entries
507                 }
508                 else error_log_syslog = 0;
509
510                 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
511                 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
512
513                 error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
514                 setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
515
516                 // --------------------------------------------------------------------
517
518                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
519                 if(strcmp(access_log_file, "syslog") == 0) {
520                         access_log_syslog = 1;
521                         access_log_file = NULL;
522                 }
523                 else if(strcmp(access_log_file, "none") == 0) {
524                         access_log_syslog = 0;
525                         access_log_file = NULL;
526                 }
527                 else access_log_syslog = 0;
528
529                 // --------------------------------------------------------------------
530
531                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
532
533                 // --------------------------------------------------------------------
534
535                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
536                         error("WARNING: Cannot get machine hostname.");
537                 hostname = config_get("global", "hostname", buffer);
538                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
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[51];
563                         snprintfz(buf, 50, "%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 < 0) fatal("Cannot listen socket.");
640         }
641
642         // never become a problem
643         if(nice(20) == -1) error("Cannot lower my CPU priority.");
644
645         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1)
646                 fatal("Cannot demonize myself.");
647
648 #ifdef NETDATA_INTERNAL_CHECKS
649         if(debug_flags != 0) {
650                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
651                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
652                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
653                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
654         }
655 #endif /* NETDATA_INTERNAL_CHECKS */
656
657         if(output_log_syslog || error_log_syslog || access_log_syslog)
658                 openlog("netdata", LOG_PID, LOG_DAEMON);
659
660         info("NetData started on pid %d", getpid());
661
662
663         // ------------------------------------------------------------------------
664         // get default pthread stack size
665
666         if(stacksize < wanted_stacksize) {
667                 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
668                 if(i != 0)
669                         fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
670                 else
671                         info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
672         }
673
674         // --------------------------------------------------------------------
675         // initialize the registry
676
677         registry_init();
678
679         // ------------------------------------------------------------------------
680         // spawn the threads
681
682         web_server_threading_selection();
683
684         for (i = 0; static_threads[i].name != NULL ; i++) {
685                 struct netdata_static_thread *st = &static_threads[i];
686
687                 if(st->enabled) {
688                         st->thread = malloc(sizeof(pthread_t));
689                         if(!st->thread)
690                                 fatal("Cannot allocate pthread_t memory");
691
692                         info("Starting thread %s.", st->name);
693
694                         if(pthread_create(st->thread, &attr, st->start_routine, NULL))
695                                 error("failed to create new thread for %s.", st->name);
696
697                         else if(pthread_detach(*st->thread))
698                                 error("Cannot request detach of newly created %s thread.", st->name);
699                 }
700                 else info("Not starting thread %s.", st->name);
701         }
702
703         // ------------------------------------------------------------------------
704         // block signals while initializing threads.
705         sigset_t sigset;
706         sigfillset(&sigset);
707
708         if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
709                 error("Could not unblock signals for threads");
710         }
711
712         // Handle flags set in the signal handler.
713         while(1) {
714                 pause();
715                 if(netdata_exit) {
716                         info("Exit main loop of netdata.");
717                         netdata_cleanup_and_exit(0);
718                         exit(0);
719                 }
720         }
721 }