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