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