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