]> arthur.barton.de Git - netdata.git/blob - src/main.c
fixed minor issues throughout the code (mainly types); dashboard has now a watermark...
[netdata.git] / src / main.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <signal.h>
8 #include <syslog.h>
9 #include <pthread.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14 #include <sys/time.h>
15 #include <sys/resource.h>
16 #include <sys/mman.h>
17
18 #include "common.h"
19 #include "log.h"
20 #include "daemon.h"
21 #include "web_server.h"
22 #include "popen.h"
23 #include "appconfig.h"
24 #include "web_client.h"
25 #include "rrd.h"
26 #include "rrd2json.h"
27
28 #include "unit_test.h"
29
30 #include "plugins_d.h"
31 #include "plugin_idlejitter.h"
32 #include "plugin_tc.h"
33 #include "plugin_checks.h"
34 #include "plugin_proc.h"
35 #include "plugin_nfacct.h"
36
37 #include "main.h"
38
39 int netdata_exit = 0;
40
41 void netdata_cleanup_and_exit(int ret)
42 {
43         kill_childs();
44         rrdset_free_all();
45         //unlink("/var/run/netdata.pid");
46         info("NetData exiting. Bye bye...");
47         exit(ret);
48 }
49
50 struct netdata_static_thread {
51         char *name;
52
53         char *config_section;
54         char *config_name;
55
56         int enabled;
57
58         pthread_t *thread;
59
60         void (*init_routine) (void);
61         void *(*start_routine) (void *);
62 };
63
64 struct netdata_static_thread static_threads[] = {
65         {"tc",                  "plugins",      "tc",                   1, NULL, NULL,  tc_main},
66         {"idlejitter",  "plugins",      "idlejitter",   1, NULL, NULL,  cpuidlejitter_main},
67         {"proc",                "plugins",      "proc",                 1, NULL, NULL,  proc_main},
68
69 #ifdef INTERNAL_PLUGIN_NFACCT
70         // nfacct requires root access
71         // so, we build it as an external plugin with setuid to root
72         {"nfacct",              "plugins",      "nfacct",               1, NULL, NULL,  nfacct_main},
73 #endif
74
75         {"plugins.d",   NULL,           NULL,                   1, NULL, NULL,  pluginsd_main},
76         {"check",               "plugins",      "checks",               0, NULL, NULL,  checks_main},
77         {"web",                 NULL,           NULL,                   1, NULL, NULL,  socket_listen_main},
78         {NULL,                  NULL,           NULL,                   0, NULL, NULL,  NULL}
79 };
80
81 int killpid(pid_t pid, int sig)
82 {
83         int ret = -1;
84         debug(D_EXIT, "Request to kill pid %d", pid);
85
86         errno = 0;
87         if(kill(pid, 0) == -1) {
88                 switch(errno) {
89                         case ESRCH:
90                                 error("Request to kill pid %d, but it is not running.", pid);
91                                 break;
92
93                         case EPERM:
94                                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
95                                 break;
96
97                         default:
98                                 error("Request to kill pid %d, but I received an error.", pid);
99                                 break;
100                 }
101         }
102         else {
103                 errno = 0;
104
105                 void (*old)(int);
106                 old = signal(sig, SIG_IGN);
107                 if(old == SIG_ERR) {
108                         error("Cannot overwrite signal handler for signal %d", sig);
109                         old = sig_handler;
110                 }
111
112                 ret = kill(pid, sig);
113
114                 if(signal(sig, old) == SIG_ERR)
115                         error("Cannot restore signal handler for signal %d", sig);
116
117                 if(ret == -1) {
118                         switch(errno) {
119                                 case ESRCH:
120                                         error("Cannot kill pid %d, but it is not running.", pid);
121                                         break;
122
123                                 case EPERM:
124                                         error("Cannot kill pid %d, but I do not have enough permissions.", pid);
125                                         break;
126
127                                 default:
128                                         error("Cannot kill pid %d, but I received an error.", pid);
129                                         break;
130                         }
131                 }
132         }
133
134         return ret;
135 }
136
137 void kill_childs()
138 {
139         siginfo_t info;
140
141         struct web_client *w;
142         for(w = web_clients; w ; w = w->next) {
143                 debug(D_EXIT, "Stopping web client %s", w->client_ip);
144                 pthread_cancel(w->thread);
145                 pthread_join(w->thread, NULL);
146         }
147
148         int i;
149         for (i = 0; static_threads[i].name != NULL ; i++) {
150                 if(static_threads[i].thread) {
151                         debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
152                         pthread_cancel(*static_threads[i].thread);
153                         pthread_join(*static_threads[i].thread, NULL);
154                         static_threads[i].thread = NULL;
155                 }
156         }
157
158         if(tc_child_pid) {
159                 info("Killing tc-qos-helper procees");
160                 if(killpid(tc_child_pid, SIGTERM) != -1)
161                         waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
162         }
163         tc_child_pid = 0;
164
165         struct plugind *cd;
166         for(cd = pluginsd_root ; cd ; cd = cd->next) {
167                 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
168                 pthread_cancel(cd->thread);
169                 pthread_join(cd->thread, NULL);
170
171                 if(cd->pid && !cd->obsolete) {
172                         debug(D_EXIT, "killing %s plugin process", cd->id);
173                         if(killpid(cd->pid, SIGTERM) != -1)
174                                 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
175                 }
176         }
177
178         // if, for any reason there is any child exited
179         // catch it here
180         waitid(P_PID, 0, &info, WEXITED|WNOHANG);
181
182         debug(D_EXIT, "All threads/childs stopped.");
183 }
184
185
186 int main(int argc, char **argv)
187 {
188         int i;
189         int config_loaded = 0;
190         int dont_fork = 0;
191
192         // global initialization
193         get_HZ();
194
195         // set the name for logging
196         program_name = "netdata";
197
198         // parse  the arguments
199         for(i = 1; i < argc ; i++) {
200                 if(strcmp(argv[i], "-c") == 0 && (i+1) < argc) {
201                         if(load_config(argv[i+1], 1) != 1) {
202                                 error("Cannot load configuration file %s.", argv[i+1]);
203                                 exit(1);
204                         }
205                         else {
206                                 debug(D_OPTIONS, "Configuration loaded from %s.", argv[i+1]);
207                                 config_loaded = 1;
208                         }
209                         i++;
210                 }
211                 else if(strcmp(argv[i], "-df") == 0 && (i+1) < argc) { config_set("global", "debug flags",  argv[i+1]); i++; }
212                 else if(strcmp(argv[i], "-p")  == 0 && (i+1) < argc) { config_set("global", "port",         argv[i+1]); i++; }
213                 else if(strcmp(argv[i], "-u")  == 0 && (i+1) < argc) { config_set("global", "run as user",  argv[i+1]); i++; }
214                 else if(strcmp(argv[i], "-l")  == 0 && (i+1) < argc) { config_set("global", "history",      argv[i+1]); i++; }
215                 else if(strcmp(argv[i], "-t")  == 0 && (i+1) < argc) { config_set("global", "update every", argv[i+1]); i++; }
216                 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) { config_set("global", "host access prefix", argv[i+1]); i++; }
217                 else if(strcmp(argv[i], "-nodeamon") == 0 || strcmp(argv[i], "-nd") == 0) dont_fork = 1;
218                 else if(strcmp(argv[i], "--unittest")  == 0) {
219                         if(unit_test_storage()) exit(1);
220                         exit(0);
221                         rrd_update_every = 1;
222                         if(unit_test(1000000, 0)) exit(1);
223                         if(unit_test(1000000, 500000)) exit(1);
224                         if(unit_test(1000000, 100000)) exit(1);
225                         if(unit_test(1000000, 900000)) exit(1);
226                         if(unit_test(2000000, 0)) exit(1);
227                         if(unit_test(2000000, 500000)) exit(1);
228                         if(unit_test(2000000, 100000)) exit(1);
229                         if(unit_test(2000000, 900000)) exit(1);
230                         if(unit_test(500000, 500000)) exit(1);
231                         //if(unit_test(500000, 100000)) exit(1); // FIXME: the expected numbers are wrong
232                         //if(unit_test(500000, 900000)) exit(1); // FIXME: the expected numbers are wrong
233                         if(unit_test(500000, 0)) exit(1);
234                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
235                         exit(0);
236                 }
237                 else {
238                         fprintf(stderr, "Cannot understand option '%s'.\n", argv[i]);
239                         fprintf(stderr, "\nUSAGE: %s [-d] [-l LINES_TO_SAVE] [-u UPDATE_TIMER] [-p LISTEN_PORT] [-dl debug log file] [-df debug flags].\n\n", argv[0]);
240                         fprintf(stderr, "  -c CONFIG FILE the configuration file to load. Default: %s.\n", CONFIG_DIR "/" CONFIG_FILENAME);
241                         fprintf(stderr, "  -l LINES_TO_SAVE can be from 5 to %d lines in JSON data. Default: %d.\n", RRD_HISTORY_ENTRIES_MAX, RRD_DEFAULT_HISTORY_ENTRIES);
242                         fprintf(stderr, "  -t UPDATE_TIMER can be from 1 to %d seconds. Default: %d.\n", UPDATE_EVERY_MAX, UPDATE_EVERY);
243                         fprintf(stderr, "  -p LISTEN_PORT can be from 1 to %d. Default: %d.\n", 65535, LISTEN_PORT);
244                         fprintf(stderr, "  -u USERNAME can be any system username to run as. Default: none.\n");
245                         fprintf(stderr, "  -ch path to access host /proc and /sys when running in a container. Default: empty.\n");
246                         fprintf(stderr, "  -nd or -nodeamon to disable forking in the background. Default: unset.\n");
247                         fprintf(stderr, "  -df FLAGS debug options. Default: 0x%08llx.\n", debug_flags);
248                         exit(1);
249                 }
250         }
251
252         if(!config_loaded) load_config(NULL, 0);
253
254         // prepare configuration environment variables for the plugins
255         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
256         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
257         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
258         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
259         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
260
261         // avoid extended to stat(/etc/localtime)
262         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
263         setenv("TZ", ":/etc/localtime", 0);
264
265         // cd to /tmp to avoid any plugins writing files at random places
266         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
267
268         char *input_log_file = NULL;
269         char *output_log_file = NULL;
270         char *error_log_file = NULL;
271         char *access_log_file = NULL;
272         char *user = NULL;
273         {
274                 char buffer[1024];
275
276                 // --------------------------------------------------------------------
277
278                 sprintf(buffer, "0x%08llx", 0ULL);
279                 char *flags = config_get("global", "debug flags", buffer);
280                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
281
282                 debug_flags = strtoull(flags, NULL, 0);
283                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
284
285                 if(debug_flags != 0) {
286                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
287                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
288                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
289                 }
290
291                 // --------------------------------------------------------------------
292
293 #ifdef MADV_MERGEABLE
294                 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
295 #else
296 #warning "Kernel memory deduplication (KSM) is not available"
297 #endif
298
299                 // --------------------------------------------------------------------
300
301
302                 global_host_prefix = config_get("global", "host access prefix", "");
303                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
304
305                 // --------------------------------------------------------------------
306
307                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
308                 if(strcmp(output_log_file, "syslog") == 0) {
309                         output_log_syslog = 1;
310                         output_log_file = NULL;
311                 }
312                 else if(strcmp(output_log_file, "none") == 0) {
313                         output_log_syslog = 0;
314                         output_log_file = NULL;
315                 }
316                 else output_log_syslog = 0;
317
318                 // --------------------------------------------------------------------
319
320                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
321                 if(strcmp(error_log_file, "syslog") == 0) {
322                         error_log_syslog = 1;
323                         error_log_file = NULL;
324                 }
325                 else if(strcmp(error_log_file, "none") == 0) {
326                         error_log_syslog = 0;
327                         error_log_file = NULL;
328                         // optimization - do not even generate debug log entries
329                 }
330                 else error_log_syslog = 0;
331
332                 // --------------------------------------------------------------------
333
334                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
335                 if(strcmp(access_log_file, "syslog") == 0) {
336                         access_log_syslog = 1;
337                         access_log_file = NULL;
338                 }
339                 else if(strcmp(access_log_file, "none") == 0) {
340                         access_log_syslog = 0;
341                         access_log_file = NULL;
342                 }
343                 else access_log_syslog = 0;
344
345                 // --------------------------------------------------------------------
346
347                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
348
349                 // --------------------------------------------------------------------
350
351                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
352                         error("WARNING: Cannot get machine hostname.");
353                 hostname = config_get("global", "hostname", buffer);
354                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
355
356                 // --------------------------------------------------------------------
357
358                 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
359                 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
360                         fprintf(stderr, "Invalid save lines %d given. Defaulting to %d.\n", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
361                         rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
362                 }
363                 else {
364                         debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
365                 }
366
367                 // --------------------------------------------------------------------
368
369                 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
370                 if(rrd_update_every < 1 || rrd_update_every > 600) {
371                         fprintf(stderr, "Invalid update timer %d given. Defaulting to %d.\n", rrd_update_every, UPDATE_EVERY_MAX);
372                         rrd_update_every = UPDATE_EVERY;
373                 }
374                 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
375
376                 // let the plugins know the min update_every
377                 {
378                         char buf[50];
379                         snprintf(buf, 50, "%d", rrd_update_every);
380                         setenv("NETDATA_UPDATE_EVERY", buf, 1);
381                 }
382
383                 // --------------------------------------------------------------------
384
385                 for (i = 0; static_threads[i].name != NULL ; i++) {
386                         struct netdata_static_thread *st = &static_threads[i];
387
388                         if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
389                         if(st->enabled && st->init_routine) st->init_routine();
390                 }
391
392                 // --------------------------------------------------------------------
393
394                 prepare_rundir();
395                 user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
396                 web_files_uid();
397
398                 // --------------------------------------------------------------------
399
400                 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
401
402                 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
403                 if(listen_port < 1 || listen_port > 65535) {
404                         fprintf(stderr, "Invalid listen port %d given. Defaulting to %d.\n", listen_port, LISTEN_PORT);
405                         listen_port = LISTEN_PORT;
406                 }
407                 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
408
409                 int ip = 0;
410                 char *ipv = config_get("global", "ip version", "any");
411                 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
412                 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
413                 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
414                 else fprintf(stderr, "Cannot understand ip version '%s'. Assumming 'any'.", ipv);
415
416                 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(listen_port, listen_backlog);
417                 if(listen_fd < 0) {
418                         listen_fd = create_listen_socket4(listen_port, listen_backlog);
419                         if(listen_fd >= 0 && ip != 4) fprintf(stderr, "Managed to open an IPv4 socket on port %d.", listen_port);
420                 }
421
422                 if(listen_fd < 0) fatal("Cannot listen socket.");
423         }
424
425         // never become a problem
426         if(nice(20) == -1) error("Cannot lower my CPU priority.");
427
428         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1) {
429                 fatal("Cannot demonize myself.");
430                 exit(1);
431         }
432
433         if(output_log_syslog || error_log_syslog || access_log_syslog)
434                 openlog("netdata", LOG_PID, LOG_DAEMON);
435
436         info("NetData started on pid %d", getpid());
437
438
439         // catch all signals
440         for (i = 1 ; i < 65 ;i++) {
441                 switch(i) {
442                         case SIGKILL: // not catchable
443                         case SIGSTOP: // not catchable
444                                 break;
445
446                         case SIGSEGV:
447                         case SIGFPE:
448                         case SIGCHLD:
449                                 signal(i, SIG_DFL);
450                                 break;
451
452                         default:
453                                 signal(i,  sig_handler);
454                                 break;
455                 }
456         }
457
458         for (i = 0; static_threads[i].name != NULL ; i++) {
459                 struct netdata_static_thread *st = &static_threads[i];
460
461                 if(st->enabled) {
462                         st->thread = malloc(sizeof(pthread_t));
463
464                         info("Starting thread %s.", st->name);
465
466                         if(pthread_create(st->thread, NULL, st->start_routine, NULL))
467                                 error("failed to create new thread for %s.", st->name);
468
469                         else if(pthread_detach(*st->thread))
470                                 error("Cannot request detach of newly created %s thread.", st->name);
471                 }
472                 else info("Not starting thread %s.", st->name);
473         }
474
475         // for future use - the main thread
476         while(1) {
477                 if(netdata_exit != 0) {
478                         netdata_exit++;
479
480                         if(netdata_exit > 5) {
481                                 netdata_cleanup_and_exit(0);
482                                 exit(0);
483                         }
484                 }
485                 sleep(2);
486         }
487
488         exit(0);
489 }