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