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