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