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