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