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