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