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