]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
added more fping alarms; added the ability to have alarms that never send CLEAR notif...
[netdata.git] / src / web_server.c
1 #include "common.h"
2
3 int listen_backlog = LISTEN_BACKLOG;
4 size_t listen_fds_count = 0;
5 int listen_fds[MAX_LISTEN_FDS] = { [0 ... 99] = -1 };
6 char *listen_fds_names[MAX_LISTEN_FDS] = { [0 ... 99] = NULL };
7 int listen_port = LISTEN_PORT;
8 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
9
10 static int shown_server_socket_error = 0;
11
12 #ifdef NETDATA_INTERNAL_CHECKS
13 static void log_allocations(void)
14 {
15 #ifdef HAVE_C_MALLINFO
16     static int heap = 0, used = 0, mmap = 0;
17
18     struct mallinfo mi;
19
20     mi = mallinfo();
21     if(mi.uordblks > used) {
22         int clients = 0;
23         struct web_client *w;
24         for(w = web_clients; w ; w = w->next) clients++;
25
26         info("Allocated memory: used %d KB (+%d B), mmap %d KB (+%d B), heap %d KB (+%d B). %d web clients connected.",
27             mi.uordblks / 1024,
28             mi.uordblks - used,
29             mi.hblkhd / 1024,
30             mi.hblkhd - mmap,
31             mi.arena / 1024,
32             mi.arena - heap,
33             clients);
34
35         used = mi.uordblks;
36         heap = mi.arena;
37         mmap = mi.hblkhd;
38     }
39 #else /* ! HAVE_C_MALLINFO */
40     ;
41 #endif /* ! HAVE_C_MALLINFO */
42
43 #ifdef has_jemalloc
44     malloc_stats_print(NULL, NULL, NULL);
45 #endif
46 }
47 #endif /* NETDATA_INTERNAL_CHECKS */
48
49 #ifndef HAVE_ACCEPT4
50 int accept4(int sock, struct sockaddr *addr, socklen_t *addrlen, int flags) {
51     int fd = accept(sock, addr, addrlen);
52     int newflags = 0;
53
54     if (fd < 0) return fd;
55
56     if (flags & SOCK_NONBLOCK) {
57         newflags |= O_NONBLOCK;
58         flags &= ~SOCK_NONBLOCK;
59     }
60
61 #ifdef SOCK_CLOEXEC
62 #ifdef O_CLOEXEC
63     if (flags & SOCK_CLOEXEC) {
64         newflags |= O_CLOEXEC;
65         flags &= ~SOCK_CLOEXEC;
66     }
67 #endif
68 #endif
69
70     if (flags) {
71         errno = -EINVAL;
72         return -1;
73     }
74
75     if (fcntl(fd, F_SETFL, newflags) < 0) {
76         int saved_errno = errno;
77         close(fd);
78         errno = saved_errno;
79         return -1;
80     }
81
82     return fd;
83 }
84 #endif
85
86 int create_listen_socket4(const char *ip, int port, int listen_backlog) {
87     int sock;
88     int sockopt = 1;
89
90     debug(D_LISTENER, "IPv4 creating new listening socket on ip '%s' port %d", ip, port);
91
92     sock = socket(AF_INET, SOCK_STREAM, 0);
93     if(sock < 0) {
94         error("IPv4 socket() on ip '%s' port %d failed.", ip, port);
95         shown_server_socket_error = 1;
96         return -1;
97     }
98
99     /* avoid "address already in use" */
100     if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
101         error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
102
103     struct sockaddr_in name;
104     memset(&name, 0, sizeof(struct sockaddr_in));
105     name.sin_family = AF_INET;
106     name.sin_port = htons (port);
107
108     int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
109     if(ret != 1) {
110         error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
111         shown_server_socket_error = 1;
112         close(sock);
113         return -1;
114     }
115
116     if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
117         close(sock);
118         error("IPv4 bind() on ip '%s' port %d failed.", ip, port);
119         shown_server_socket_error = 1;
120         return -1;
121     }
122
123     if(listen(sock, listen_backlog) < 0) {
124         close(sock);
125         error("IPv4 listen() on ip '%s' port %d failed.", ip, port);
126         shown_server_socket_error = 1;
127         return -1;
128     }
129
130     debug(D_LISTENER, "Listening on IPv4 ip '%s' port %d", ip, port);
131     return sock;
132 }
133
134 int create_listen_socket6(const char *ip, int port, int listen_backlog) {
135     int sock = -1;
136     int sockopt = 1;
137     int ipv6only = 1;
138
139     debug(D_LISTENER, "IPv6 creating new listening socket on ip '%s' port %d", ip, port);
140
141     sock = socket(AF_INET6, SOCK_STREAM, 0);
142     if (sock < 0) {
143         error("IPv6 socket() on ip '%s' port %d failed.", ip, port);
144         shown_server_socket_error = 1;
145         return -1;
146     }
147
148     /* avoid "address already in use" */
149     if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt)) != 0)
150         error("Cannot set SO_REUSEADDR on ip '%s' port's %d.", ip, port);
151
152     /* IPv6 only */
153     if(setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&ipv6only, sizeof(ipv6only)) != 0)
154         error("Cannot set IPV6_V6ONLY on ip '%s' port's %d.", ip, port);
155
156     struct sockaddr_in6 name;
157     memset(&name, 0, sizeof(struct sockaddr_in6));
158     name.sin6_family = AF_INET6;
159     name.sin6_port = htons ((uint16_t) port);
160
161     int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
162     if(ret != 1) {
163         error("Failed to convert IP '%s' to a valid IPv6 address.", ip);
164         shown_server_socket_error = 1;
165         close(sock);
166         return -1;
167     }
168
169     name.sin6_scope_id = 0;
170
171     if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
172         close(sock);
173         error("IPv6 bind() on ip '%s' port %d failed.", ip, port);
174         shown_server_socket_error = 1;
175         return -1;
176     }
177
178     if (listen(sock, listen_backlog) < 0) {
179         close(sock);
180         error("IPv6 listen() on ip '%s' port %d failed.", ip, port);
181         shown_server_socket_error = 1;
182         return -1;
183     }
184
185     debug(D_LISTENER, "Listening on IPv6 ip '%s' port %d", ip, port);
186     return sock;
187 }
188
189 static inline int add_listen_socket(int fd, const char *ip, int port) {
190     if(listen_fds_count >= MAX_LISTEN_FDS) {
191         error("Too many listening sockets. Failed to add listening socket at ip '%s' port %d", ip, port);
192         shown_server_socket_error = 1;
193         close(fd);
194         return -1;
195     }
196
197     listen_fds[listen_fds_count] = fd;
198
199     char buffer[100 + 1];
200     snprintfz(buffer, 100, "[%s]:%d", ip, port);
201     listen_fds_names[listen_fds_count] = strdupz(buffer);
202
203     listen_fds_count++;
204     return 0;
205 }
206
207 int is_listen_socket(int fd) {
208     size_t i;
209     for(i = 0; i < listen_fds_count ;i++)
210         if(listen_fds[i] == fd) return 1;
211
212     return 0;
213 }
214
215 static inline void close_listen_sockets(void) {
216     size_t i;
217     for(i = 0; i < listen_fds_count ;i++) {
218         close(listen_fds[i]);
219         listen_fds[i] = -1;
220
221         freez(listen_fds_names[i]);
222         listen_fds_names[i] = NULL;
223     }
224
225     listen_fds_count = 0;
226 }
227
228 static inline int bind_to_one(const char *definition, int default_port, int listen_backlog) {
229     int added = 0;
230     struct addrinfo hints;
231     struct addrinfo *result = NULL, *rp = NULL;
232
233     char buffer[strlen(definition) + 1];
234     strcpy(buffer, definition);
235
236     char buffer2[10 + 1];
237     snprintfz(buffer2, 10, "%d", default_port);
238
239     char *ip = buffer, *port = buffer2;
240
241     char *e = ip;
242     if(*e == '[') {
243         e = ++ip;
244         while(*e && *e != ']') e++;
245         if(*e == ']') {
246             *e = '\0';
247             e++;
248         }
249     }
250     else {
251         while(*e && *e != ':') e++;
252     }
253
254     if(*e == ':') {
255         port = e + 1;
256         *e = '\0';
257     }
258
259     if(!*ip || *ip == '*' || !strcmp(ip, "any") || !strcmp(ip, "all"))
260         ip = NULL;
261     if(!*port)
262         port = buffer2;
263
264     memset(&hints, 0, sizeof(struct addrinfo));
265     hints.ai_family = AF_UNSPEC;    /* Allow IPv4 or IPv6 */
266     hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
267     hints.ai_flags = AI_PASSIVE;    /* For wildcard IP address */
268     hints.ai_protocol = 0;          /* Any protocol */
269     hints.ai_canonname = NULL;
270     hints.ai_addr = NULL;
271     hints.ai_next = NULL;
272
273     int r = getaddrinfo(ip, port, &hints, &result);
274     if (r != 0) {
275         error("getaddrinfo('%s', '%s'): %s\n", ip, port, gai_strerror(r));
276         return -1;
277     }
278
279     for (rp = result; rp != NULL; rp = rp->ai_next) {
280         int fd = -1;
281
282         char rip[INET_ADDRSTRLEN + INET6_ADDRSTRLEN] = "INVALID";
283         int rport = default_port;
284
285         switch (rp->ai_addr->sa_family) {
286             case AF_INET: {
287                 struct sockaddr_in *sin = (struct sockaddr_in *) rp->ai_addr;
288                 inet_ntop(AF_INET, &sin->sin_addr, rip, INET_ADDRSTRLEN);
289                 rport = ntohs(sin->sin_port);
290                 fd = create_listen_socket4(rip, rport, listen_backlog);
291                 break;
292             }
293
294             case AF_INET6: {
295                 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) rp->ai_addr;
296                 inet_ntop(AF_INET6, &sin6->sin6_addr, rip, INET6_ADDRSTRLEN);
297                 rport = ntohs(sin6->sin6_port);
298                 fd = create_listen_socket6(rip, rport, listen_backlog);
299                 break;
300             }
301         }
302
303         if (fd == -1)
304             error("Cannot bind to ip '%s', port %d", rip, rport);
305         else {
306             add_listen_socket(fd, rip, rport);
307             added++;
308         }
309     }
310
311     freeaddrinfo(result);
312
313     return added;
314 }
315
316 int create_listen_sockets(void) {
317     shown_server_socket_error = 0;
318
319     listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
320
321     if(config_exists("global", "bind socket to IP") && !config_exists("global", "bind to"))
322         config_rename("global", "bind socket to IP", "bind to");
323
324     if(config_exists("global", "port") && !config_exists("global", "default port"))
325         config_rename("global", "port", "default port");
326
327     listen_port = (int) config_get_number("global", "default port", LISTEN_PORT);
328     if(listen_port < 1 || listen_port > 65535) {
329         error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
330         listen_port = (int) config_set_number("global", "default port", LISTEN_PORT);
331     }
332     debug(D_OPTIONS, "Default listen port set to %d.", listen_port);
333
334     char *s = config_get("global", "bind to", "*");
335     while(*s) {
336         char *e = s;
337
338         // skip separators, moving both s(tart) and e(nd)
339         while(isspace(*e) || *e == ',') s = ++e;
340
341         // move e(nd) to the first separator
342         while(*e && !isspace(*e) && *e != ',') e++;
343
344         // is there anything?
345         if(!*s || s == e) break;
346
347         char buf[e - s + 1];
348         strncpyz(buf, s, e - s);
349         bind_to_one(buf, listen_port, listen_backlog);
350
351         s = e;
352     }
353
354     if(!listen_fds_count)
355         fatal("Cannot listen on any socket. Exiting...");
356     else if(shown_server_socket_error) {
357         size_t i;
358         for(i = 0; i < listen_fds_count ;i++)
359             info("Listen socket %s opened.", listen_fds_names[i]);
360     }
361
362     return (int)listen_fds_count;
363 }
364
365 // --------------------------------------------------------------------------------------
366 // the main socket listener
367
368 static inline void cleanup_web_clients(void) {
369     struct web_client *w;
370
371     for (w = web_clients; w;) {
372         if (w->obsolete) {
373             debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
374             // pthread_cancel(w->thread);
375             // pthread_join(w->thread, NULL);
376             w = web_client_free(w);
377 #ifdef NETDATA_INTERNAL_CHECKS
378             log_allocations();
379 #endif
380         }
381         else w = w->next;
382     }
383 }
384
385 // 1. it accepts new incoming requests on our port
386 // 2. creates a new web_client for each connection received
387 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
388 // 4. cleans up old web_clients that their pthreads have been exited
389
390 #define CLEANUP_EVERY_EVENTS 100
391
392 void *socket_listen_main_multi_threaded(void *ptr) {
393     struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
394
395     web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
396     info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
397
398     struct web_client *w;
399     int retval, counter = 0;
400
401     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
402         error("Cannot set pthread cancel type to DEFERRED.");
403
404     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
405         error("Cannot set pthread cancel state to ENABLE.");
406
407     if(!listen_fds_count)
408         fatal("LISTENER: No sockets to listen to.");
409
410     struct pollfd *fds = callocz(sizeof(struct pollfd), listen_fds_count);
411
412     size_t i;
413     for(i = 0; i < listen_fds_count ;i++) {
414         fds[i].fd = listen_fds[i];
415         fds[i].events = POLLIN;
416         fds[i].revents = 0;
417
418         info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
419     }
420
421     int timeout = 10 * 1000;
422
423     for(;;) {
424         // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
425         retval = poll(fds, listen_fds_count, timeout);
426
427         if(unlikely(retval == -1)) {
428             error("LISTENER: poll() failed.");
429             continue;
430         }
431         else if(unlikely(!retval)) {
432             debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
433             counter = 0;
434             cleanup_web_clients();
435             continue;
436         }
437
438         for(i = 0 ; i < listen_fds_count ; i++) {
439             short int revents = fds[i].revents;
440
441             // check for new incoming connections
442             if(revents & POLLIN || revents & POLLPRI) {
443                 fds[i].revents = 0;
444
445                 w = web_client_create(fds[i].fd);
446                 if(unlikely(!w)) {
447                     // no need for error log - web_client_create already logged the error
448                     continue;
449                 }
450
451                 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
452                     error("%llu: failed to create new thread for web client.", w->id);
453                     w->obsolete = 1;
454                 }
455                 else if(pthread_detach(w->thread) != 0) {
456                     error("%llu: Cannot request detach of newly created web client thread.", w->id);
457                     w->obsolete = 1;
458                 }
459             }
460         }
461
462         // cleanup unused clients
463         counter++;
464         if(counter >= CLEANUP_EVERY_EVENTS) {
465             counter = 0;
466             cleanup_web_clients();
467         }
468     }
469
470     debug(D_WEB_CLIENT, "LISTENER: exit!");
471     close_listen_sockets();
472
473     freez(fds);
474
475     static_thread->enabled = 0;
476     pthread_exit(NULL);
477     return NULL;
478 }
479
480 struct web_client *single_threaded_clients[FD_SETSIZE];
481
482 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
483     if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
484         return 1;
485
486     if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
487         error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
488         return 1;
489     }
490
491     FD_SET(w->ifd, efds);
492     if(unlikely(*max < w->ifd)) *max = w->ifd;
493
494     if(unlikely(w->ifd != w->ofd)) {
495         if(*max < w->ofd) *max = w->ofd;
496         FD_SET(w->ofd, efds);
497     }
498
499     if(w->wait_receive) FD_SET(w->ifd, ifds);
500     if(w->wait_send)    FD_SET(w->ofd, ofds);
501
502     single_threaded_clients[w->ifd] = w;
503     single_threaded_clients[w->ofd] = w;
504
505     return 0;
506 }
507
508 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
509     FD_CLR(w->ifd, efds);
510     if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
511
512     if(w->wait_receive) FD_CLR(w->ifd, ifds);
513     if(w->wait_send)    FD_CLR(w->ofd, ofds);
514
515     single_threaded_clients[w->ifd] = NULL;
516     single_threaded_clients[w->ofd] = NULL;
517
518     if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
519         return 1;
520
521     return 0;
522 }
523
524 void *socket_listen_main_single_threaded(void *ptr) {
525     struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
526
527     web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
528
529     info("Single-threaded WEB SERVER thread created with task id %d", gettid());
530
531     struct web_client *w;
532     int retval;
533
534     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
535         error("Cannot set pthread cancel type to DEFERRED.");
536
537     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
538         error("Cannot set pthread cancel state to ENABLE.");
539
540     if(!listen_fds_count)
541         fatal("LISTENER: no listen sockets available.");
542
543     size_t i;
544     for(i = 0; i < FD_SETSIZE ; i++)
545         single_threaded_clients[i] = NULL;
546
547     fd_set ifds, ofds, efds, rifds, rofds, refds;
548     FD_ZERO (&ifds);
549     FD_ZERO (&ofds);
550     FD_ZERO (&efds);
551     int fdmax = 0;
552
553     for(i = 0; i < listen_fds_count ; i++) {
554         if (listen_fds[i] < 0 || listen_fds[i] >= FD_SETSIZE)
555             fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fds[i]);
556
557         info("Listening on '%s'", (listen_fds_names[i])?listen_fds_names[i]:"UNKNOWN");
558
559         FD_SET(listen_fds[i], &ifds);
560         FD_SET(listen_fds[i], &efds);
561         if(fdmax < listen_fds[i])
562             fdmax = listen_fds[i];
563     }
564
565     for(;;) {
566         debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (fdmax = %d)...", fdmax);
567
568         struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
569         rifds = ifds;
570         rofds = ofds;
571         refds = efds;
572         retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
573
574         if(unlikely(retval == -1)) {
575             error("LISTENER: select() failed.");
576             continue;
577         }
578         else if(likely(retval)) {
579             debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
580
581             for(i = 0; i < listen_fds_count ; i++) {
582                 if (FD_ISSET(listen_fds[i], &rifds)) {
583                     debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
584                     w = web_client_create(listen_fds[i]);
585                     if (single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
586                         web_client_free(w);
587                     }
588                 }
589             }
590
591             for(i = 0 ; i <= (size_t)fdmax ; i++) {
592                 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
593                     continue;
594
595                 w = single_threaded_clients[i];
596                 if(unlikely(!w))
597                     continue;
598
599                 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
600                     web_client_free(w);
601                     continue;
602                 }
603
604                 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
605                     web_client_free(w);
606                     continue;
607                 }
608
609                 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
610                     if (unlikely(web_client_receive(w) < 0)) {
611                         web_client_free(w);
612                         continue;
613                     }
614
615                     if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
616                         debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
617                         web_client_process(w);
618                     }
619                 }
620
621                 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
622                     if (unlikely(web_client_send(w) < 0)) {
623                         debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
624                         web_client_free(w);
625                         continue;
626                     }
627                 }
628
629                 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
630                     web_client_free(w);
631                 }
632             }
633         }
634         else {
635             debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
636 #ifdef NETDATA_INTERNAL_CHECKS
637             log_allocations();
638 #endif
639         }
640     }
641
642     debug(D_WEB_CLIENT, "LISTENER: exit!");
643     close_listen_sockets();
644
645     static_thread->enabled = 0;
646     pthread_exit(NULL);
647     return NULL;
648 }