]> arthur.barton.de Git - netdata.git/blob - src/main.c
1100b393e6b835662934ed18d77f153c2026393f
[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     rrdhost_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     sleep(2);
27     rrdhost_free_all();
28 #endif
29
30     info("netdata exiting. Bye bye...");
31     exit(ret);
32 }
33
34 struct netdata_static_thread static_threads[] = {
35 #ifdef INTERNAL_PLUGIN_NFACCT
36 // nfacct requires root access
37     // so, we build it as an external plugin with setuid to root
38     {"nfacct",              "plugins",  "nfacct",     1, NULL, NULL, nfacct_main},
39 #endif
40
41     {"tc",                 "plugins",   "tc",         1, NULL, NULL, tc_main},
42     {"idlejitter",         "plugins",   "idlejitter", 1, NULL, NULL, cpuidlejitter_main},
43 #if defined(__FreeBSD__)
44     {"freebsd",            "plugins",   "freebsd",    1, NULL, NULL, freebsd_main},
45 #elif defined(__APPLE__)
46     {"macos",              "plugins",   "macos",      1, NULL, NULL, macos_main},
47 #else
48     {"proc",               "plugins",   "proc",       1, NULL, NULL, proc_main},
49     {"diskspace",          "plugins",   "diskspace",  1, NULL, NULL, proc_diskspace_main},
50     {"cgroups",            "plugins",   "cgroups",    1, NULL, NULL, cgroups_main},
51 #endif /* __FreeBSD__, __APPLE__*/
52     {"check",              "plugins",   "checks",     0, NULL, NULL, checks_main},
53     {"backends",            NULL,       NULL,         1, NULL, NULL, backends_main},
54     {"health",              NULL,       NULL,         1, NULL, NULL, health_main},
55     {"plugins.d",           NULL,       NULL,         1, NULL, NULL, pluginsd_main},
56     {"web",                 NULL,       NULL,         1, NULL, NULL, socket_listen_main_multi_threaded},
57     {"web-single-threaded", NULL,       NULL,         0, NULL, NULL, socket_listen_main_single_threaded},
58     {NULL,                  NULL,       NULL,         0, NULL, NULL, NULL}
59 };
60
61 void web_server_threading_selection(void) {
62     int threaded = config_get_boolean("global", "multi threaded web server", 1);
63
64     int i;
65     for(i = 0; static_threads[i].name ; i++) {
66         if(static_threads[i].start_routine == socket_listen_main_multi_threaded)
67             static_threads[i].enabled = threaded?1:0;
68
69         if(static_threads[i].start_routine == socket_listen_main_single_threaded)
70             static_threads[i].enabled = threaded?0:1;
71     }
72
73     web_client_timeout = (int) config_get_number("global", "disconnect idle web clients after seconds", DEFAULT_DISCONNECT_IDLE_WEB_CLIENTS_AFTER_SECONDS);
74
75     respect_web_browser_do_not_track_policy = config_get_boolean("global", "respect web browser do not track policy", respect_web_browser_do_not_track_policy);
76     web_x_frame_options = config_get("global", "web x-frame-options header", "");
77     if(!*web_x_frame_options) web_x_frame_options = NULL;
78
79 #ifdef NETDATA_WITH_ZLIB
80     web_enable_gzip = config_get_boolean("global", "enable web responses gzip compression", web_enable_gzip);
81
82     char *s = config_get("global", "web compression strategy", "default");
83     if(!strcmp(s, "default"))
84         web_gzip_strategy = Z_DEFAULT_STRATEGY;
85     else if(!strcmp(s, "filtered"))
86         web_gzip_strategy = Z_FILTERED;
87     else if(!strcmp(s, "huffman only"))
88         web_gzip_strategy = Z_HUFFMAN_ONLY;
89     else if(!strcmp(s, "rle"))
90         web_gzip_strategy = Z_RLE;
91     else if(!strcmp(s, "fixed"))
92         web_gzip_strategy = Z_FIXED;
93     else {
94         error("Invalid compression strategy '%s'. Valid strategies are 'default', 'filtered', 'huffman only', 'rle' and 'fixed'. Proceeding with 'default'.", s);
95         web_gzip_strategy = Z_DEFAULT_STRATEGY;
96     }
97
98     web_gzip_level = (int)config_get_number("global", "web compression level", 3);
99     if(web_gzip_level < 1) {
100         error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 1 (fastest compression).", web_gzip_level);
101         web_gzip_level = 1;
102     }
103     else if(web_gzip_level > 9) {
104         error("Invalid compression level %d. Valid levels are 1 (fastest) to 9 (best ratio). Proceeding with level 9 (best compression).", web_gzip_level);
105         web_gzip_level = 9;
106     }
107 #endif /* NETDATA_WITH_ZLIB */
108 }
109
110
111 int killpid(pid_t pid, int sig)
112 {
113     int ret = -1;
114     debug(D_EXIT, "Request to kill pid %d", pid);
115
116     errno = 0;
117     if(kill(pid, 0) == -1) {
118         switch(errno) {
119             case ESRCH:
120                 error("Request to kill pid %d, but it is not running.", pid);
121                 break;
122
123             case EPERM:
124                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
125                 break;
126
127             default:
128                 error("Request to kill pid %d, but I received an error.", pid);
129                 break;
130         }
131     }
132     else {
133         errno = 0;
134         ret = kill(pid, sig);
135         if(ret == -1) {
136             switch(errno) {
137                 case ESRCH:
138                     error("Cannot kill pid %d, but it is not running.", pid);
139                     break;
140
141                 case EPERM:
142                     error("Cannot kill pid %d, but I do not have enough permissions.", pid);
143                     break;
144
145                 default:
146                     error("Cannot kill pid %d, but I received an error.", pid);
147                     break;
148             }
149         }
150     }
151
152     return ret;
153 }
154
155 void kill_childs()
156 {
157     error_log_limit_unlimited();
158
159     siginfo_t info;
160
161     struct web_client *w;
162     for(w = web_clients; w ; w = w->next) {
163         info("Stopping web client %s", w->client_ip);
164         pthread_cancel(w->thread);
165         // it is detached
166         // pthread_join(w->thread, NULL);
167
168         w->obsolete = 1;
169     }
170
171     int i;
172     for (i = 0; static_threads[i].name != NULL ; i++) {
173         if(static_threads[i].enabled) {
174             info("Stopping %s thread", static_threads[i].name);
175             pthread_cancel(*static_threads[i].thread);
176             // it is detached
177             // pthread_join(*static_threads[i].thread, NULL);
178
179             static_threads[i].enabled = 0;
180         }
181     }
182
183     if(tc_child_pid) {
184         info("Killing tc-qos-helper process %d", tc_child_pid);
185         if(killpid(tc_child_pid, SIGTERM) != -1)
186             waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
187
188         tc_child_pid = 0;
189     }
190
191     struct plugind *cd;
192     for(cd = pluginsd_root ; cd ; cd = cd->next) {
193         if(cd->enabled && !cd->obsolete) {
194             info("Stopping %s plugin thread", cd->id);
195             pthread_cancel(cd->thread);
196
197             if(cd->pid) {
198                 info("killing %s plugin child process pid %d", cd->id, cd->pid);
199                 if(killpid(cd->pid, SIGTERM) != -1)
200                     waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
201
202                 cd->pid = 0;
203             }
204
205             cd->obsolete = 1;
206         }
207     }
208
209     // if, for any reason there is any child exited
210     // catch it here
211     info("Cleaning up an other children");
212     waitid(P_PID, 0, &info, WEXITED|WNOHANG);
213
214     info("All threads/childs stopped.");
215 }
216
217 struct option_def options[] = {
218     // opt description                                    arg name       default value
219     { 'c', "Configuration file to load.",                 "filename",    CONFIG_DIR "/" CONFIG_FILENAME},
220     { 'D', "Do not fork. Run in the foreground.",         NULL,          "run in the background"},
221     { 'h', "Display this help message.",                  NULL,          NULL},
222     { 'P', "File to save a pid while running.",           "filename",    "do not save pid to a file"},
223     { 'i', "The IP address to listen to.",                "IP",          "all IP addresses IPv4 and IPv6"},
224     { 'k', "Check health configuration and exit.",        NULL,          NULL},
225     { 'p', "API/Web port to use.",                        "port",        "19999"},
226     { 's', "Prefix for /proc and /sys (for containers).", "path",        "no prefix"},
227     { 't', "The internal clock of netdata.",              "seconds",     "1"},
228     { 'u', "Run as user.",                                "username",    "netdata"},
229     { 'v', "Print netdata version and exit.",             NULL,          NULL},
230     { 'W', "See Advanced options below.",                 "options",     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     if(max_len_arg > 30) max_len_arg = 30;
253     if(max_len_arg < 20) max_len_arg = 20;
254
255     fprintf(stream, "%s", "\n"
256             " ^\n"
257             " |.-.   .-.   .-.   .-.   .  netdata                                         \n"
258             " |   '-'   '-'   '-'   '-'   real-time performance monitoring, done right!   \n"
259             " +----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+--->\n"
260             "\n"
261             " Copyright (C) 2016-2017, Costa Tsaousis <costa@tsaousis.gr>\n"
262             " Released under GNU General Public License v3 or later.\n"
263             " All rights reserved.\n"
264             "\n"
265             " Home Page  : https://my-netdata.io\n"
266             " Source Code: https://github.com/firehol/netdata\n"
267             " Wiki / Docs: https://github.com/firehol/netdata/wiki\n"
268             " Support    : https://github.com/firehol/netdata/issues\n"
269             " License    : https://github.com/firehol/netdata/blob/master/LICENSE.md\n"
270             "\n"
271             " Twitter    : https://twitter.com/linuxnetdata\n"
272             " Facebook   : https://www.facebook.com/linuxnetdata/\n"
273             "\n"
274             " netdata is a https://firehol.org project.\n"
275             "\n"
276             "\n"
277     );
278
279     fprintf(stream, " SYNOPSIS: netdata [options]\n");
280     fprintf(stream, "\n");
281     fprintf(stream, " Options:\n\n");
282
283     // Output options description.
284     for( i = 0; i < num_opts; i++ ) {
285         fprintf(stream, "  -%c %-*s  %s", options[i].val, max_len_arg, options[i].arg_name ? options[i].arg_name : "", options[i].description);
286         if(options[i].default_value) {
287             fprintf(stream, "\n   %c %-*s  Default: %s\n", ' ', max_len_arg, "", options[i].default_value);
288         } else {
289             fprintf(stream, "\n");
290         }
291         fprintf(stream, "\n");
292     }
293
294     fprintf(stream, "\n Advanced options:\n\n"
295             "  -W stacksize=N           Set the stacksize (in bytes).\n\n"
296             "  -W debug_flags=N         Set runtime tracing to debug.log.\n\n"
297             "  -W unittest              Run internal unittests and exit.\n\n"
298             "  -W simple-pattern pattern string\n"
299             "                           Check if string matches pattern and exit.\n\n"
300     );
301
302     fprintf(stream, "\n Signals netdata handles:\n\n"
303             "  - HUP                    Close and reopen log files.\n"
304             "  - USR1                   Save internal DB to disk.\n"
305             "  - USR2                   Reload health configuration.\n"
306             "\n"
307     );
308
309     fflush(stream);
310     exit(exitcode);
311 }
312
313 // TODO: Remove this function with the nix major release.
314 void remove_option(int opt_index, int *argc, char **argv) {
315     int i = opt_index;
316     // remove the options.
317     do {
318         *argc = *argc - 1;
319         for(i = opt_index; i < *argc; i++) {
320             argv[i] = argv[i+1];
321         }
322         i = opt_index;
323     } while(argv[i][0] != '-' && opt_index >= *argc);
324 }
325
326 static const char *verify_required_directory(const char *dir) {
327     if(chdir(dir) == -1)
328         fatal("Cannot cd to directory '%s'", dir);
329
330     DIR *d = opendir(dir);
331     if(!d)
332         fatal("Cannot examine the contents of directory '%s'", dir);
333     closedir(d);
334
335     return dir;
336 }
337
338 int main(int argc, char **argv) {
339     char *hostname = "localhost";
340     int i, check_config = 0;
341     int config_loaded = 0;
342     int dont_fork = 0;
343     size_t wanted_stacksize = 0, stacksize = 0;
344     pthread_attr_t attr;
345
346     // set the name for logging
347     program_name = "netdata";
348
349     // parse depercated options
350     // TODO: Remove this block with the next major release.
351     {
352         i = 1;
353         while(i < argc) {
354             if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
355                 strncpyz(pidfile, argv[i+1], FILENAME_MAX);
356                 fprintf(stderr, "%s: deprecated option -- %s -- please use -P instead.\n", argv[0], argv[i]);
357                 remove_option(i, &argc, argv);
358             }
359             else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) {
360                 dont_fork = 1;
361                 fprintf(stderr, "%s: deprecated option -- %s -- please use -D instead.\n ", argv[0], argv[i]);
362                 remove_option(i, &argc, argv);
363             }
364             else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) {
365                 config_set("global", "host access prefix", argv[i+1]);
366                 fprintf(stderr, "%s: deprecated option -- %s -- please use -s instead.\n", argv[0], argv[i]);
367                 remove_option(i, &argc, argv);
368             }
369             else if(strcmp(argv[i], "-l") == 0 && (i+1) < argc) {
370                 config_set("global", "history", argv[i+1]);
371                 fprintf(stderr, "%s: deprecated option -- %s -- This option will be removed with V2.*.\n", argv[0], argv[i]);
372                 remove_option(i, &argc, argv);
373             }
374             else i++;
375         }
376     }
377
378     // parse options
379     {
380         int num_opts = sizeof(options) / sizeof(struct option_def);
381         char optstring[(num_opts * 2) + 1];
382
383         int string_i = 0;
384         for( i = 0; i < num_opts; i++ ) {
385             optstring[string_i] = options[i].val;
386             string_i++;
387             if(options[i].arg_name) {
388                 optstring[string_i] = ':';
389                 string_i++;
390             }
391         }
392         // terminate optstring
393         optstring[string_i] ='\0';
394         optstring[(num_opts *2)] ='\0';
395
396         int opt;
397         while( (opt = getopt(argc, argv, optstring)) != -1 ) {
398             switch(opt) {
399                 case 'c':
400                     if(load_config(optarg, 1) != 1) {
401                         error("Cannot load configuration file %s.", optarg);
402                         exit(1);
403                     }
404                     else {
405                         debug(D_OPTIONS, "Configuration loaded from %s.", optarg);
406                         config_loaded = 1;
407                     }
408                     break;
409                 case 'D':
410                     dont_fork = 1;
411                     break;
412                 case 'h':
413                     help(0);
414                     break;
415                 case 'i':
416                     config_set("global", "bind to", optarg);
417                     break;
418                 case 'k':
419                     dont_fork = 1;
420                     check_config = 1;
421                     break;
422                 case 'P':
423                     strncpy(pidfile, optarg, FILENAME_MAX);
424                     pidfile[FILENAME_MAX] = '\0';
425                     break;
426                 case 'p':
427                     config_set("global", "default port", optarg);
428                     break;
429                 case 's':
430                     config_set("global", "host access prefix", optarg);
431                     break;
432                 case 't':
433                     config_set("global", "update every", optarg);
434                     break;
435                 case 'u':
436                     config_set("global", "run as user", optarg);
437                     break;
438                 case 'v':
439                     printf("%s %s\n", program_name, program_version);
440                     return 0;
441                 case 'W':
442                     {
443                         char* stacksize_string = "stacksize=";
444                         char* debug_flags_string = "debug_flags=";
445                         if(strcmp(optarg, "unittest") == 0) {
446                             rrd_update_every = 1;
447                             if(run_all_mockup_tests()) exit(1);
448                             if(unit_test_storage()) exit(1);
449                             fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
450                             exit(0);
451                         }
452                         else if(strcmp(optarg, "simple-pattern") == 0) {
453                             if(optind + 2 > argc) {
454                                 fprintf(stderr, "%s", "\nUSAGE: -W simple-pattern 'pattern' 'string'\n\n"
455                                         " Checks if 'pattern' matches the given 'string'.\n"
456                                         " - 'pattern' can be one or more space separated words.\n"
457                                         " - each 'word' can contain one or more asterisks.\n"
458                                         " - words starting with '!' give negative matches.\n"
459                                         " - words are processed left to right\n"
460                                         "\n"
461                                         "Examples:\n"
462                                         "\n"
463                                         " > match all veth interfaces, except veth0:\n"
464                                         "\n"
465                                         "   -W simple-pattern '!veth0 veth*' 'veth12'\n"
466                                         "\n"
467                                         "\n"
468                                         " > match all *.ext files directly in /path/:\n"
469                                         "   (this will not match *.ext files in a subdir of /path/)\n"
470                                         "\n"
471                                         "   -W simple-pattern '!/path/*/*.ext /path/*.ext' '/path/test.ext'\n"
472                                         "\n"
473                                 );
474                                 exit(1);
475                             }
476
477                             const char *heystack = argv[optind];
478                             const char *needle = argv[optind + 1];
479
480                             SIMPLE_PATTERN *p = simple_pattern_create(heystack
481                                                                       , SIMPLE_PATTERN_EXACT);
482                             int ret = simple_pattern_matches(p, needle);
483                             simple_pattern_free(p);
484
485                             if(ret) {
486                                 fprintf(stdout, "RESULT: MATCHED - pattern '%s' matches '%s'\n", heystack, needle);
487                                 exit(0);
488                             }
489                             else {
490                                 fprintf(stdout, "RESULT: NOT MATCHED - pattern '%s' does not match '%s'\n", heystack, needle);
491                                 exit(1);
492                             }
493                         }
494                         else if(strncmp(optarg, stacksize_string, strlen(stacksize_string)) == 0) {
495                             optarg += strlen(stacksize_string);
496                             config_set("global", "pthread stack size", optarg);
497                         }
498                         else if(strncmp(optarg, debug_flags_string, strlen(debug_flags_string)) == 0) {
499                             optarg += strlen(debug_flags_string);
500                             config_set("global", "debug flags",  optarg);
501                             debug_flags = strtoull(optarg, NULL, 0);
502                         }
503                     }
504                     break;
505                 default: /* ? */
506                     help(1);
507                     break;
508             }
509         }
510     }
511
512 #ifdef _SC_OPEN_MAX
513     // close all open file descriptors, except the standard ones
514     // the caller may have left open files (lxc-attach has this issue)
515     {
516         int fd;
517         for(fd = (int) (sysconf(_SC_OPEN_MAX) - 1); fd > 2; fd--)
518             if(fd_is_valid(fd)) close(fd);
519     }
520 #endif
521
522     if(!config_loaded)
523         load_config(NULL, 0);
524
525     {
526         char *pmax = config_get("global", "glibc malloc arena max for plugins", "1");
527         if(pmax && *pmax)
528             setenv("MALLOC_ARENA_MAX", pmax, 1);
529
530 #if defined(HAVE_C_MALLOPT)
531         int i = config_get_number("global", "glibc malloc arena max for netdata", 1);
532         if(i > 0)
533             mallopt(M_ARENA_MAX, 1);
534 #endif
535
536         // prepare configuration environment variables for the plugins
537
538         netdata_configured_config_dir  = config_get("global", "config directory",    CONFIG_DIR);
539         netdata_configured_log_dir     = config_get("global", "log directory",       LOG_DIR);
540         netdata_configured_plugins_dir = config_get("global", "plugins directory",   PLUGINS_DIR);
541         netdata_configured_web_dir     = config_get("global", "web files directory", WEB_DIR);
542         netdata_configured_cache_dir   = config_get("global", "cache directory",     CACHE_DIR);
543         netdata_configured_varlib_dir  = config_get("global", "lib directory",       VARLIB_DIR);
544         netdata_configured_home_dir    = config_get("global", "home directory",      CACHE_DIR);
545
546         setenv("NETDATA_CONFIG_DIR" , verify_required_directory(netdata_configured_config_dir),  1);
547         setenv("NETDATA_PLUGINS_DIR", verify_required_directory(netdata_configured_plugins_dir), 1);
548         setenv("NETDATA_WEB_DIR"    , verify_required_directory(netdata_configured_web_dir),     1);
549         setenv("NETDATA_CACHE_DIR"  , verify_required_directory(netdata_configured_cache_dir),   1);
550         setenv("NETDATA_LIB_DIR"    , verify_required_directory(netdata_configured_varlib_dir),  1);
551         setenv("NETDATA_LOG_DIR"    , verify_required_directory(netdata_configured_log_dir),     1);
552         setenv("HOME"               , verify_required_directory(netdata_configured_home_dir),    1);
553
554         netdata_configured_host_prefix = config_get("global", "host access prefix", "");
555         setenv("NETDATA_HOST_PREFIX", netdata_configured_host_prefix, 1);
556
557         // disable buffering for python plugins
558         setenv("PYTHONUNBUFFERED", "1", 1);
559
560         // avoid flood calls to stat(/etc/localtime)
561         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
562         setenv("TZ", ":/etc/localtime", 0);
563
564         // work while we are cd into config_dir
565         // to allow the plugins refer to their config
566         // files using relative filenames
567         if(chdir(netdata_configured_config_dir) == -1)
568             fatal("Cannot cd to '%s'", netdata_configured_config_dir);
569
570         char path[1024 + 1], *p = getenv("PATH");
571         if(!p) p = "/bin:/usr/bin";
572         snprintfz(path, 1024, "%s:%s", p, "/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
573         setenv("PATH", config_get("plugins", "PATH environment variable", path), 1);
574
575         p = getenv("PYTHONPATH");
576         if(!p) p = "";
577         setenv("PYTHONPATH", config_get("plugins", "PYTHONPATH environment variable", p), 1);
578     }
579
580     char *user = NULL;
581     {
582         char *flags = config_get("global", "debug flags",  "0x0000000000000000");
583         setenv("NETDATA_DEBUG_FLAGS", flags, 1);
584
585         debug_flags = strtoull(flags, NULL, 0);
586         debug(D_OPTIONS, "Debug flags set to '0x%" PRIX64 "'.", debug_flags);
587
588         if(debug_flags != 0) {
589             struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
590             if(setrlimit(RLIMIT_CORE, &rl) != 0)
591                 error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
592
593 #ifdef HAVE_SYS_PRCTL_H
594             prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
595 #endif
596         }
597
598         // --------------------------------------------------------------------
599
600 #ifdef MADV_MERGEABLE
601         enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
602 #else
603 #warning "Kernel memory deduplication (KSM) is not available"
604 #endif
605
606         // --------------------------------------------------------------------
607
608         get_system_HZ();
609         get_system_cpus();
610         get_system_pid_max();
611         
612         // --------------------------------------------------------------------
613
614         {
615             char filename[FILENAME_MAX + 1];
616             snprintfz(filename, FILENAME_MAX, "%s/debug.log", netdata_configured_log_dir);
617             stdout_filename    = config_get("global", "debug log",  filename);
618
619             snprintfz(filename, FILENAME_MAX, "%s/error.log", netdata_configured_log_dir);
620             stderr_filename    = config_get("global", "error log",  filename);
621
622             snprintfz(filename, FILENAME_MAX, "%s/access.log", netdata_configured_log_dir);
623             stdaccess_filename = config_get("global", "access log", filename);
624         }
625
626         error_log_throttle_period_backup =
627             error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
628         setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
629
630         error_log_errors_per_period = (unsigned long)config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
631         setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
632
633         if(check_config) {
634             stdout_filename = stderr_filename = stdaccess_filename = "system";
635             error_log_throttle_period = 0;
636             error_log_errors_per_period = 0;
637         }
638         error_log_limit_unlimited();
639
640         // --------------------------------------------------------------------
641
642         default_localhost_rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(default_localhost_rrd_memory_mode)));
643
644         // --------------------------------------------------------------------
645
646         {
647             char hostnamebuf[HOSTNAME_MAX + 1];
648             if(gethostname(hostnamebuf, HOSTNAME_MAX) == -1)
649                 error("WARNING: Cannot get machine hostname.");
650             hostname = config_get("global", "hostname", hostnamebuf);
651             debug(D_OPTIONS, "hostname set to '%s'", hostname);
652             setenv("NETDATA_HOSTNAME", hostname, 1);
653         }
654
655         // --------------------------------------------------------------------
656
657         rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
658         if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
659             error("Invalid history entries %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
660             rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
661         }
662         else {
663             debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
664         }
665
666         // --------------------------------------------------------------------
667
668         rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
669         if(rrd_update_every < 1 || rrd_update_every > 600) {
670             error("Invalid data collection frequency (update every) %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
671             rrd_update_every = UPDATE_EVERY;
672         }
673         else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
674
675         // let the plugins know the min update_every
676         {
677             char buf[16];
678             snprintfz(buf, 15, "%d", rrd_update_every);
679             setenv("NETDATA_UPDATE_EVERY", buf, 1);
680         }
681
682         // --------------------------------------------------------------------
683
684         // block signals while initializing threads.
685         // this causes the threads to block signals.
686         sigset_t sigset;
687         sigfillset(&sigset);
688         if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1)
689             error("Could not block signals for threads");
690
691         // Catch signals which we want to use
692         struct sigaction sa;
693         sa.sa_flags = 0;
694
695         // ingore all signals while we run in a signal handler
696         sigfillset(&sa.sa_mask);
697
698         // INFO: If we add signals here we have to unblock them
699         // at popen.c when running a external plugin.
700
701         // Ignore SIGPIPE completely.
702         sa.sa_handler = SIG_IGN;
703         if(sigaction(SIGPIPE, &sa, NULL) == -1)
704             error("Failed to change signal handler for SIGPIPE");
705
706         sa.sa_handler = sig_handler_exit;
707         if(sigaction(SIGINT, &sa, NULL) == -1)
708             error("Failed to change signal handler for SIGINT");
709
710         sa.sa_handler = sig_handler_exit;
711         if(sigaction(SIGTERM, &sa, NULL) == -1)
712             error("Failed to change signal handler for SIGTERM");
713
714         sa.sa_handler = sig_handler_logrotate;
715         if(sigaction(SIGHUP, &sa, NULL) == -1)
716             error("Failed to change signal handler for SIGHUP");
717
718         // save database on SIGUSR1
719         sa.sa_handler = sig_handler_save;
720         if(sigaction(SIGUSR1, &sa, NULL) == -1)
721             error("Failed to change signal handler for SIGUSR1");
722
723         // reload health configuration on SIGUSR2
724         sa.sa_handler = sig_handler_reload_health;
725         if(sigaction(SIGUSR2, &sa, NULL) == -1)
726             error("Failed to change signal handler for SIGUSR2");
727
728         // --------------------------------------------------------------------
729
730         i = pthread_attr_init(&attr);
731         if(i != 0)
732             fatal("pthread_attr_init() failed with code %d.", i);
733
734         i = pthread_attr_getstacksize(&attr, &stacksize);
735         if(i != 0)
736             fatal("pthread_attr_getstacksize() failed with code %d.", i);
737         else
738             debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
739
740         wanted_stacksize = (size_t)config_get_number("global", "pthread stack size", (long)stacksize);
741
742         // --------------------------------------------------------------------
743
744         for (i = 0; static_threads[i].name != NULL ; i++) {
745             struct netdata_static_thread *st = &static_threads[i];
746
747             if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
748             if(st->enabled && st->init_routine) st->init_routine();
749         }
750
751         // --------------------------------------------------------------------
752
753         // get the user we should run
754         // IMPORTANT: this is required before web_files_uid()
755         user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
756
757         // IMPORTANT: these have to run once, while single threaded
758         web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
759         web_files_gid();
760
761         // --------------------------------------------------------------------
762
763         if(!check_config)
764             create_listen_sockets();
765     }
766
767     // initialize the log files
768     open_all_log_files();
769
770 #ifdef NETDATA_INTERNAL_CHECKS
771     if(debug_flags != 0) {
772         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
773         if(setrlimit(RLIMIT_CORE, &rl) != 0)
774             error("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
775 #ifdef HAVE_SYS_PRCTL_H
776         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
777 #endif
778     }
779 #endif /* NETDATA_INTERNAL_CHECKS */
780
781     // fork, switch user, create pid file, set process priority
782     if(become_daemon(dont_fork, user) == -1)
783         fatal("Cannot daemonize myself.");
784
785     info("netdata started on pid %d.", getpid());
786
787     // ------------------------------------------------------------------------
788     // get default pthread stack size
789
790     if(stacksize < wanted_stacksize) {
791         i = pthread_attr_setstacksize(&attr, wanted_stacksize);
792         if(i != 0)
793             fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
794         else
795             debug(D_SYSTEM, "Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
796     }
797
798     // ------------------------------------------------------------------------
799     // initialize health monitoring
800
801     health_init();
802
803     // ------------------------------------------------------------------------
804     // initialize the registry
805
806     registry_init();
807
808     // ------------------------------------------------------------------------
809     // initialize rrd host
810
811     rrd_init(hostname);
812
813     if(check_config)
814         exit(1);
815
816     // ------------------------------------------------------------------------
817     // enable log flood protection
818
819     error_log_limit_reset();
820
821     // ------------------------------------------------------------------------
822     // spawn the threads
823
824     web_server_threading_selection();
825
826     for (i = 0; static_threads[i].name != NULL ; i++) {
827         struct netdata_static_thread *st = &static_threads[i];
828
829         if(st->enabled) {
830             st->thread = mallocz(sizeof(pthread_t));
831
832             debug(D_SYSTEM, "Starting thread %s.", st->name);
833
834             if(pthread_create(st->thread, &attr, st->start_routine, st))
835                 error("failed to create new thread for %s.", st->name);
836
837             else if(pthread_detach(*st->thread))
838                 error("Cannot request detach of newly created %s thread.", st->name);
839         }
840         else debug(D_SYSTEM, "Not starting thread %s.", st->name);
841     }
842
843     info("netdata initialization completed. Enjoy real-time performance monitoring!");
844
845     // ------------------------------------------------------------------------
846     // block signals while initializing threads.
847     sigset_t sigset;
848     sigfillset(&sigset);
849
850     if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
851         error("Could not unblock signals for threads");
852     }
853
854     // Handle flags set in the signal handler.
855     while(1) {
856         pause();
857         if(netdata_exit) {
858             debug(D_EXIT, "Exit main loop of netdata.");
859             netdata_cleanup_and_exit(0);
860             exit(0);
861         }
862     }
863 }