]> arthur.barton.de Git - netdata.git/blob - src/main.c
Merge pull request #404 from simonnagl/bugfix
[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 #include <sys/prctl.h>
18
19 #include "common.h"
20 #include "log.h"
21 #include "daemon.h"
22 #include "web_server.h"
23 #include "popen.h"
24 #include "appconfig.h"
25 #include "web_client.h"
26 #include "rrd.h"
27 #include "rrd2json.h"
28
29 #include "unit_test.h"
30
31 #include "plugins_d.h"
32 #include "plugin_idlejitter.h"
33 #include "plugin_tc.h"
34 #include "plugin_checks.h"
35 #include "plugin_proc.h"
36 #include "plugin_nfacct.h"
37
38 #include "main.h"
39
40 extern void *cgroups_main(void *ptr);
41
42 volatile sig_atomic_t netdata_exit = 0;
43
44 void netdata_cleanup_and_exit(int ret)
45 {
46         netdata_exit = 1;
47         rrdset_save_all();
48         // kill_childs();
49
50         // let it log a few more error messages
51         error_log_limit_reset();
52
53         if(pidfd != -1) {
54                 if(ftruncate(pidfd, 0) != 0)
55                         error("Cannot truncate pidfile '%s'.", pidfile);
56
57                 close(pidfd);
58                 pidfd = -1;
59         }
60
61         if(pidfile[0]) {
62                 if(unlink(pidfile) != 0)
63                         error("Cannot unlink pidfile '%s'.", pidfile);
64         }
65
66         info("NetData exiting. Bye bye...");
67         exit(ret);
68 }
69
70 struct netdata_static_thread {
71         char *name;
72
73         char *config_section;
74         char *config_name;
75
76         int enabled;
77
78         pthread_t *thread;
79
80         void (*init_routine) (void);
81         void *(*start_routine) (void *);
82 };
83
84 struct netdata_static_thread static_threads[] = {
85         {"tc",                  "plugins",      "tc",                   1, NULL, NULL,  tc_main},
86         {"idlejitter",  "plugins",      "idlejitter",   1, NULL, NULL,  cpuidlejitter_main},
87         {"proc",                "plugins",      "proc",                 1, NULL, NULL,  proc_main},
88         {"cgroups",             "plugins",      "cgroups",              1, NULL, NULL,  cgroups_main},
89
90 #ifdef INTERNAL_PLUGIN_NFACCT
91         // nfacct requires root access
92         // so, we build it as an external plugin with setuid to root
93         {"nfacct",              "plugins",      "nfacct",               1, NULL, NULL,  nfacct_main},
94 #endif
95
96         {"plugins.d",   NULL,           NULL,                   1, NULL, NULL,  pluginsd_main},
97         {"check",               "plugins",      "checks",               0, NULL, NULL,  checks_main},
98         {"web",                 NULL,           NULL,                   1, NULL, NULL,  socket_listen_main},
99         {NULL,                  NULL,           NULL,                   0, NULL, NULL,  NULL}
100 };
101
102 int killpid(pid_t pid, int sig)
103 {
104         int ret = -1;
105         debug(D_EXIT, "Request to kill pid %d", pid);
106
107         errno = 0;
108         if(kill(pid, 0) == -1) {
109                 switch(errno) {
110                         case ESRCH:
111                                 error("Request to kill pid %d, but it is not running.", pid);
112                                 break;
113
114                         case EPERM:
115                                 error("Request to kill pid %d, but I do not have enough permissions.", pid);
116                                 break;
117
118                         default:
119                                 error("Request to kill pid %d, but I received an error.", pid);
120                                 break;
121                 }
122         }
123         else {
124                 errno = 0;
125                 ret = kill(pid, sig);
126                 if(ret == -1) {
127                         switch(errno) {
128                                 case ESRCH:
129                                         error("Cannot kill pid %d, but it is not running.", pid);
130                                         break;
131
132                                 case EPERM:
133                                         error("Cannot kill pid %d, but I do not have enough permissions.", pid);
134                                         break;
135
136                                 default:
137                                         error("Cannot kill pid %d, but I received an error.", pid);
138                                         break;
139                         }
140                 }
141         }
142
143         return ret;
144 }
145
146 void kill_childs()
147 {
148         siginfo_t info;
149
150         struct web_client *w;
151         for(w = web_clients; w ; w = w->next) {
152                 debug(D_EXIT, "Stopping web client %s", w->client_ip);
153                 pthread_cancel(w->thread);
154                 pthread_join(w->thread, NULL);
155         }
156
157         int i;
158         for (i = 0; static_threads[i].name != NULL ; i++) {
159                 if(static_threads[i].thread) {
160                         debug(D_EXIT, "Stopping %s thread", static_threads[i].name);
161                         pthread_cancel(*static_threads[i].thread);
162                         pthread_join(*static_threads[i].thread, NULL);
163                         static_threads[i].thread = NULL;
164                 }
165         }
166
167         if(tc_child_pid) {
168                 info("Killing tc-qos-helper procees");
169                 if(killpid(tc_child_pid, SIGTERM) != -1)
170                         waitid(P_PID, (id_t) tc_child_pid, &info, WEXITED);
171         }
172         tc_child_pid = 0;
173
174         struct plugind *cd;
175         for(cd = pluginsd_root ; cd ; cd = cd->next) {
176                 debug(D_EXIT, "Stopping %s plugin thread", cd->id);
177                 pthread_cancel(cd->thread);
178                 pthread_join(cd->thread, NULL);
179
180                 if(cd->pid && !cd->obsolete) {
181                         debug(D_EXIT, "killing %s plugin process", cd->id);
182                         if(killpid(cd->pid, SIGTERM) != -1)
183                                 waitid(P_PID, (id_t) cd->pid, &info, WEXITED);
184                 }
185         }
186
187         // if, for any reason there is any child exited
188         // catch it here
189         waitid(P_PID, 0, &info, WEXITED|WNOHANG);
190
191         debug(D_EXIT, "All threads/childs stopped.");
192 }
193
194
195 int main(int argc, char **argv)
196 {
197         int i;
198         int config_loaded = 0;
199         int dont_fork = 0;
200         size_t wanted_stacksize = 0, stacksize = 0;
201         pthread_attr_t attr;
202
203         // global initialization
204         get_HZ();
205
206         // set the name for logging
207         program_name = "netdata";
208
209         // parse  the arguments
210         for(i = 1; i < argc ; i++) {
211                 if(strcmp(argv[i], "-c") == 0 && (i+1) < argc) {
212                         if(load_config(argv[i+1], 1) != 1) {
213                                 error("Cannot load configuration file %s.", argv[i+1]);
214                                 exit(1);
215                         }
216                         else {
217                                 debug(D_OPTIONS, "Configuration loaded from %s.", argv[i+1]);
218                                 config_loaded = 1;
219                         }
220                         i++;
221                 }
222                 else if(strcmp(argv[i], "-df") == 0 && (i+1) < argc) { config_set("global", "debug flags",  argv[i+1]); debug_flags = strtoull(argv[i+1], NULL, 0); i++; }
223                 else if(strcmp(argv[i], "-p")  == 0 && (i+1) < argc) { config_set("global", "port",         argv[i+1]); i++; }
224                 else if(strcmp(argv[i], "-u")  == 0 && (i+1) < argc) { config_set("global", "run as user",  argv[i+1]); i++; }
225                 else if(strcmp(argv[i], "-l")  == 0 && (i+1) < argc) { config_set("global", "history",      argv[i+1]); i++; }
226                 else if(strcmp(argv[i], "-t")  == 0 && (i+1) < argc) { config_set("global", "update every", argv[i+1]); i++; }
227                 else if(strcmp(argv[i], "-ch") == 0 && (i+1) < argc) { config_set("global", "host access prefix", argv[i+1]); i++; }
228                 else if(strcmp(argv[i], "-stacksize") == 0 && (i+1) < argc) { config_set("global", "pthread stack size", argv[i+1]); i++; }
229                 else if(strcmp(argv[i], "-nodaemon") == 0 || strcmp(argv[i], "-nd") == 0) dont_fork = 1;
230                 else if(strcmp(argv[i], "-pidfile") == 0 && (i+1) < argc) {
231                         i++;
232                         strncpy(pidfile, argv[i], FILENAME_MAX);
233                         pidfile[FILENAME_MAX] = '\0';
234                 }
235                 else if(strcmp(argv[i], "--unittest")  == 0) {
236                         rrd_update_every = 1;
237                         if(run_all_mockup_tests()) exit(1);
238                         if(unit_test_storage()) exit(1);
239                         fprintf(stderr, "\n\nALL TESTS PASSED\n\n");
240                         exit(0);
241                 }
242                 else {
243                         fprintf(stderr, "Cannot understand option '%s'.\n", argv[i]);
244                         fprintf(stderr, "\nUSAGE: %s [-d] [-l LINES_TO_SAVE] [-u UPDATE_TIMER] [-p LISTEN_PORT] [-df debug flags].\n\n", argv[0]);
245                         fprintf(stderr, "  -c CONFIG FILE the configuration file to load. Default: %s.\n", CONFIG_DIR "/" CONFIG_FILENAME);
246                         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);
247                         fprintf(stderr, "  -t UPDATE_TIMER can be from 1 to %d seconds. Default: %d.\n", UPDATE_EVERY_MAX, UPDATE_EVERY);
248                         fprintf(stderr, "  -p LISTEN_PORT can be from 1 to %d. Default: %d.\n", 65535, LISTEN_PORT);
249                         fprintf(stderr, "  -u USERNAME can be any system username to run as. Default: none.\n");
250                         fprintf(stderr, "  -ch path to access host /proc and /sys when running in a container. Default: empty.\n");
251                         fprintf(stderr, "  -nd or -nodeamon to disable forking in the background. Default: unset.\n");
252                         fprintf(stderr, "  -df FLAGS debug options. Default: 0x%08llx.\n", debug_flags);
253                         fprintf(stderr, "  -stacksize BYTES to overwrite the pthread stack size.\n");
254                         fprintf(stderr, "  -pidfile FILENAME to save a pid while running.\n");
255                         exit(1);
256                 }
257         }
258
259         if(!config_loaded) load_config(NULL, 0);
260
261         // prepare configuration environment variables for the plugins
262         setenv("NETDATA_CONFIG_DIR" , config_get("global", "config directory"   , CONFIG_DIR) , 1);
263         setenv("NETDATA_PLUGINS_DIR", config_get("global", "plugins directory"  , PLUGINS_DIR), 1);
264         setenv("NETDATA_WEB_DIR"    , config_get("global", "web files directory", WEB_DIR)    , 1);
265         setenv("NETDATA_CACHE_DIR"  , config_get("global", "cache directory"    , CACHE_DIR)  , 1);
266         setenv("NETDATA_LOG_DIR"    , config_get("global", "log directory"      , LOG_DIR)    , 1);
267         setenv("NETDATA_HOST_PREFIX", config_get("global", "host access prefix" , "")         , 1);
268         setenv("HOME"               , config_get("global", "home directory"     , CACHE_DIR)  , 1);
269
270         // avoid extended to stat(/etc/localtime)
271         // http://stackoverflow.com/questions/4554271/how-to-avoid-excessive-stat-etc-localtime-calls-in-strftime-on-linux
272         setenv("TZ", ":/etc/localtime", 0);
273
274         // cd to /tmp to avoid any plugins writing files at random places
275         if(chdir("/tmp")) error("netdata: ERROR: Cannot cd to /tmp");
276
277         char *input_log_file = NULL;
278         char *output_log_file = NULL;
279         char *error_log_file = NULL;
280         char *access_log_file = NULL;
281         char *user = NULL;
282         {
283                 char buffer[1024];
284
285                 // --------------------------------------------------------------------
286
287                 sprintf(buffer, "0x%08llx", 0ULL);
288                 char *flags = config_get("global", "debug flags", buffer);
289                 setenv("NETDATA_DEBUG_FLAGS", flags, 1);
290
291                 debug_flags = strtoull(flags, NULL, 0);
292                 debug(D_OPTIONS, "Debug flags set to '0x%8llx'.", debug_flags);
293
294                 if(debug_flags != 0) {
295                         struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
296                         if(setrlimit(RLIMIT_CORE, &rl) != 0)
297                                 info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
298                         prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
299                 }
300
301                 // --------------------------------------------------------------------
302
303 #ifdef MADV_MERGEABLE
304                 enable_ksm = config_get_boolean("global", "memory deduplication (ksm)", enable_ksm);
305 #else
306 #warning "Kernel memory deduplication (KSM) is not available"
307 #endif
308
309                 // --------------------------------------------------------------------
310
311
312                 global_host_prefix = config_get("global", "host access prefix", "");
313                 setenv("NETDATA_HOST_PREFIX", global_host_prefix, 1);
314
315                 // --------------------------------------------------------------------
316
317                 output_log_file = config_get("global", "debug log", LOG_DIR "/debug.log");
318                 if(strcmp(output_log_file, "syslog") == 0) {
319                         output_log_syslog = 1;
320                         output_log_file = NULL;
321                 }
322                 else if(strcmp(output_log_file, "none") == 0) {
323                         output_log_syslog = 0;
324                         output_log_file = NULL;
325                 }
326                 else output_log_syslog = 0;
327
328                 // --------------------------------------------------------------------
329
330                 error_log_file = config_get("global", "error log", LOG_DIR "/error.log");
331                 if(strcmp(error_log_file, "syslog") == 0) {
332                         error_log_syslog = 1;
333                         error_log_file = NULL;
334                 }
335                 else if(strcmp(error_log_file, "none") == 0) {
336                         error_log_syslog = 0;
337                         error_log_file = NULL;
338                         // optimization - do not even generate debug log entries
339                 }
340                 else error_log_syslog = 0;
341
342                 error_log_throttle_period = config_get_number("global", "errors flood protection period", error_log_throttle_period);
343                 setenv("NETDATA_ERRORS_THROTTLE_PERIOD", config_get("global", "errors flood protection period"    , ""), 1);
344
345                 error_log_errors_per_period = config_get_number("global", "errors to trigger flood protection", error_log_errors_per_period);
346                 setenv("NETDATA_ERRORS_PER_PERIOD"     , config_get("global", "errors to trigger flood protection", ""), 1);
347
348                 // --------------------------------------------------------------------
349
350                 access_log_file = config_get("global", "access log", LOG_DIR "/access.log");
351                 if(strcmp(access_log_file, "syslog") == 0) {
352                         access_log_syslog = 1;
353                         access_log_file = NULL;
354                 }
355                 else if(strcmp(access_log_file, "none") == 0) {
356                         access_log_syslog = 0;
357                         access_log_file = NULL;
358                 }
359                 else access_log_syslog = 0;
360
361                 // --------------------------------------------------------------------
362
363                 rrd_memory_mode = rrd_memory_mode_id(config_get("global", "memory mode", rrd_memory_mode_name(rrd_memory_mode)));
364
365                 // --------------------------------------------------------------------
366
367                 if(gethostname(buffer, HOSTNAME_MAX) == -1)
368                         error("WARNING: Cannot get machine hostname.");
369                 hostname = config_get("global", "hostname", buffer);
370                 debug(D_OPTIONS, "hostname set to '%s'", hostname);
371
372                 // --------------------------------------------------------------------
373
374                 rrd_default_history_entries = (int) config_get_number("global", "history", RRD_DEFAULT_HISTORY_ENTRIES);
375                 if(rrd_default_history_entries < 5 || rrd_default_history_entries > RRD_HISTORY_ENTRIES_MAX) {
376                         info("Invalid save lines %d given. Defaulting to %d.", rrd_default_history_entries, RRD_DEFAULT_HISTORY_ENTRIES);
377                         rrd_default_history_entries = RRD_DEFAULT_HISTORY_ENTRIES;
378                 }
379                 else {
380                         debug(D_OPTIONS, "save lines set to %d.", rrd_default_history_entries);
381                 }
382
383                 // --------------------------------------------------------------------
384
385                 rrd_update_every = (int) config_get_number("global", "update every", UPDATE_EVERY);
386                 if(rrd_update_every < 1 || rrd_update_every > 600) {
387                         info("Invalid update timer %d given. Defaulting to %d.", rrd_update_every, UPDATE_EVERY_MAX);
388                         rrd_update_every = UPDATE_EVERY;
389                 }
390                 else debug(D_OPTIONS, "update timer set to %d.", rrd_update_every);
391
392                 // let the plugins know the min update_every
393                 {
394                         char buf[50];
395                         snprintf(buf, 50, "%d", rrd_update_every);
396                         setenv("NETDATA_UPDATE_EVERY", buf, 1);
397                 }
398
399                 // --------------------------------------------------------------------
400
401                 // block signals while initializing threads.
402                 // this causes the threads to block signals.
403                 sigset_t sigset;
404                 sigfillset(&sigset);
405
406                 if(pthread_sigmask(SIG_BLOCK, &sigset, NULL) == -1) {
407                         error("Could not block signals for threads");
408                 }
409
410                 // Catch signals which we want to use to quit savely
411                 struct sigaction sa;
412                 sigemptyset(&sa.sa_mask);
413                 sigaddset(&sa.sa_mask, SIGHUP);
414                 sigaddset(&sa.sa_mask, SIGINT);
415                 sigaddset(&sa.sa_mask, SIGTERM);
416                 sa.sa_handler = sig_handler;
417                 sa.sa_flags = 0;
418                 if(sigaction(SIGHUP, &sa, NULL) == -1) {
419                         error("Failed to change signal handler for SIGHUP");
420                 }
421                 if(sigaction(SIGINT, &sa, NULL) == -1) {
422                         error("Failed to change signal handler for SIGINT");
423                 }
424                 if(sigaction(SIGTERM, &sa, NULL) == -1) {
425                         error("Failed to change signal handler for SIGTERM");
426                 }
427                 // Ignore SIGPIPE completely.
428                 // INFO: If we add signals here we have to unblock them
429                 // at popen.c when running a external plugin.
430                 sa.sa_handler = SIG_IGN;
431                 if(sigaction(SIGPIPE, &sa, NULL) == -1) {
432                         error("Failed to change signal handler for SIGTERM");
433                 }
434
435                 // --------------------------------------------------------------------
436
437                 i = pthread_attr_init(&attr);
438                 if(i != 0)
439                         fatal("pthread_attr_init() failed with code %d.", i);
440
441                 i = pthread_attr_getstacksize(&attr, &stacksize);
442                 if(i != 0)
443                         fatal("pthread_attr_getstacksize() failed with code %d.", i);
444                 else
445                         debug(D_OPTIONS, "initial pthread stack size is %zu bytes", stacksize);
446
447                 wanted_stacksize = config_get_number("global", "pthread stack size", stacksize);
448
449                 // --------------------------------------------------------------------
450
451                 for (i = 0; static_threads[i].name != NULL ; i++) {
452                         struct netdata_static_thread *st = &static_threads[i];
453
454                         if(st->config_name) st->enabled = config_get_boolean(st->config_section, st->config_name, st->enabled);
455                         if(st->enabled && st->init_routine) st->init_routine();
456                 }
457
458                 // --------------------------------------------------------------------
459
460                 // get the user we should run
461                 // IMPORTANT: this is required before web_files_uid()
462                 user = config_get("global", "run as user"    , (getuid() == 0)?NETDATA_USER:"");
463
464                 // IMPORTANT: these have to run once, while single threaded
465                 web_files_uid(); // IMPORTANT: web_files_uid() before web_files_gid()
466                 web_files_gid();
467
468                 // --------------------------------------------------------------------
469
470                 listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
471
472                 listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
473                 if(listen_port < 1 || listen_port > 65535) {
474                         info("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
475                         listen_port = LISTEN_PORT;
476                 }
477                 else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
478
479                 int ip = 0;
480                 char *ipv = config_get("global", "ip version", "any");
481                 if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
482                 else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
483                 else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
484                 else info("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
485
486                 if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
487                 if(listen_fd < 0) {
488                         listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
489                         if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
490                 }
491
492                 if(listen_fd < 0) fatal("Cannot listen socket.");
493         }
494
495         // never become a problem
496         if(nice(20) == -1) error("Cannot lower my CPU priority.");
497
498         if(become_daemon(dont_fork, 0, user, input_log_file, output_log_file, error_log_file, access_log_file, &access_fd, &stdaccess) == -1) {
499                 fatal("Cannot demonize myself.");
500                 exit(1);
501         }
502
503         if(debug_flags != 0) {
504                 struct rlimit rl = { RLIM_INFINITY, RLIM_INFINITY };
505                 if(setrlimit(RLIMIT_CORE, &rl) != 0)
506                         info("Cannot request unlimited core dumps for debugging... Proceeding anyway...");
507
508                 prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
509         }
510
511         if(output_log_syslog || error_log_syslog || access_log_syslog)
512                 openlog("netdata", LOG_PID, LOG_DAEMON);
513
514         info("NetData started on pid %d", getpid());
515
516
517
518         // ------------------------------------------------------------------------
519         // get default pthread stack size
520
521         if(stacksize < wanted_stacksize) {
522                 i = pthread_attr_setstacksize(&attr, wanted_stacksize);
523                 if(i != 0)
524                         fatal("pthread_attr_setstacksize() to %zu bytes, failed with code %d.", wanted_stacksize, i);
525                 else
526                         info("Successfully set pthread stacksize to %zu bytes", wanted_stacksize);
527         }
528
529         // ------------------------------------------------------------------------
530         // spawn the threads
531
532         for (i = 0; static_threads[i].name != NULL ; i++) {
533                 struct netdata_static_thread *st = &static_threads[i];
534
535                 if(st->enabled) {
536                         st->thread = malloc(sizeof(pthread_t));
537                         if(!st->thread)
538                                 fatal("Cannot allocate pthread_t memory");
539
540                         info("Starting thread %s.", st->name);
541
542                         if(pthread_create(st->thread, &attr, st->start_routine, NULL))
543                                 error("failed to create new thread for %s.", st->name);
544
545                         else if(pthread_detach(*st->thread))
546                                 error("Cannot request detach of newly created %s thread.", st->name);
547                 }
548                 else info("Not starting thread %s.", st->name);
549         }
550
551         // ------------------------------------------------------------------------
552         // block signals while initializing threads.
553         sigset_t sigset;
554         sigfillset(&sigset);
555
556         if(pthread_sigmask(SIG_UNBLOCK, &sigset, NULL) == -1) {
557                 error("Could not unblock signals for threads");
558         }
559
560         // Handle flags set in the signal handler.
561         while(1) {
562                 pause();
563                 if(netdata_exit) {
564                         info("Exit main loop of netdata.");
565                         netdata_cleanup_and_exit(0);
566                         exit(0);
567                 }
568         }
569 }