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