]> arthur.barton.de Git - netdata.git/blob - src/web_server.c
faster multi-threads web server
[netdata.git] / src / web_server.c
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4 #include <unistd.h>
5 #include <stdlib.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <arpa/inet.h>
10 #include <errno.h>
11 #include <pthread.h>
12 #include <sys/stat.h>
13 #include <fcntl.h>
14 #include <netinet/tcp.h>
15 #include <malloc.h>
16
17 #include "common.h"
18 #include "log.h"
19 #include "appconfig.h"
20 #include "url.h"
21 #include "web_buffer.h"
22 #include "web_client.h"
23 #include "web_server.h"
24 #include "global_statistics.h"
25 #include "rrd.h"
26 #include "rrd2json.h"
27 #include "../config.h"
28
29 int listen_backlog = LISTEN_BACKLOG;
30 int listen_fd = -1;
31 int listen_port = LISTEN_PORT;
32 int web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
33
34 #ifdef NETDATA_INTERNAL_CHECKS
35 static void log_allocations(void)
36 {
37         static int mem = 0;
38
39         struct mallinfo mi;
40
41         mi = mallinfo();
42         if(mi.uordblks > mem) {
43                 int clients = 0;
44                 struct web_client *w;
45                 for(w = web_clients; w ; w = w->next) clients++;
46
47                 info("Allocated memory increased from %d to %d (increased by %d bytes). There are %d web clients connected.", mem, mi.uordblks, mi.uordblks - mem, clients);
48                 mem = mi.uordblks;
49         }
50 }
51 #endif
52
53 static int is_ip_anything(const char *ip)
54 {
55         if(!ip || !*ip
56                         || !strcmp(ip, "any")
57                         || !strcmp(ip, "all")
58                         || !strcmp(ip, "*")
59                         || !strcmp(ip, "::")
60                         || !strcmp(ip, "0.0.0.0")
61                         ) return 1;
62
63         return 0;
64 }
65
66 int create_listen_socket4(const char *ip, int port, int listen_backlog)
67 {
68         int sock;
69         int sockopt = 1;
70
71         debug(D_LISTENER, "IPv4 creating new listening socket on port %d", port);
72
73         sock = socket(AF_INET, SOCK_STREAM, 0);
74         if(sock < 0) {
75                 error("IPv4 socket() failed.");
76                 return -1;
77         }
78
79         /* avoid "address already in use" */
80         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
81
82         struct sockaddr_in name;
83         memset(&name, 0, sizeof(struct sockaddr_in));
84         name.sin_family = AF_INET;
85         name.sin_port = htons (port);
86
87         if(is_ip_anything(ip)) {
88                 name.sin_addr.s_addr = htonl(INADDR_ANY);
89                 // info("Listening on any IPs (IPv4).");
90         }
91         else {
92                 int ret = inet_pton(AF_INET, ip, (void *)&name.sin_addr.s_addr);
93                 if(ret != 1) {
94                         error("Failed to convert IP '%s' to a valid IPv4 address.", ip);
95                         close(sock);
96                         return -1;
97                 }
98                 // info("Listening on IP '%s' (IPv4).", ip);
99         }
100
101         if(bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
102                 close(sock);
103                 error("IPv4 bind() failed.");
104                 return -1;
105         }
106
107         if(listen(sock, listen_backlog) < 0) {
108                 close(sock);
109                 fatal("IPv4 listen() failed.");
110                 return -1;
111         }
112
113         debug(D_LISTENER, "IPv4 listening port %d created", port);
114         return sock;
115 }
116
117 int create_listen_socket6(const char *ip, int port, int listen_backlog)
118 {
119         int sock = -1;
120         int sockopt = 1;
121
122         debug(D_LISTENER, "IPv6 creating new listening socket on port %d", port);
123
124         sock = socket(AF_INET6, SOCK_STREAM, 0);
125         if (sock < 0) {
126                 error("IPv6 socket() failed. Disabling IPv6.");
127                 return -1;
128         }
129
130         /* avoid "address already in use" */
131         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void*)&sockopt, sizeof(sockopt));
132
133         struct sockaddr_in6 name;
134         memset(&name, 0, sizeof(struct sockaddr_in6));
135         name.sin6_family = AF_INET6;
136         name.sin6_port = htons ((uint16_t) port);
137
138         if(is_ip_anything(ip)) {
139                 name.sin6_addr = in6addr_any;
140                 // info("Listening on all IPs (IPv6 and IPv4)");
141         }
142         else {
143                 int ret = inet_pton(AF_INET6, ip, (void *)&name.sin6_addr.s6_addr);
144                 if(ret != 1) {
145                         error("Failed to convert IP '%s' to a valid IPv6 address. Disabling IPv6.", ip);
146                         close(sock);
147                         return -1;
148                 }
149                 // info("Listening on IP '%s' (IPv6)", ip);
150         }
151
152         name.sin6_scope_id = 0;
153
154         if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0) {
155                 close(sock);
156                 error("IPv6 bind() failed. Disabling IPv6.");
157                 return -1;
158         }
159
160         if (listen(sock, listen_backlog) < 0) {
161                 close(sock);
162                 error("IPv6 listen() failed. Disabling IPv6.");
163                 return -1;
164         }
165
166         debug(D_LISTENER, "IPv6 listening port %d created", port);
167         return sock;
168 }
169
170
171 int create_listen_socket(void) {
172         listen_backlog = (int) config_get_number("global", "http port listen backlog", LISTEN_BACKLOG);
173
174         listen_port = (int) config_get_number("global", "port", LISTEN_PORT);
175         if(listen_port < 1 || listen_port > 65535) {
176                 error("Invalid listen port %d given. Defaulting to %d.", listen_port, LISTEN_PORT);
177                 listen_port = LISTEN_PORT;
178         }
179         else debug(D_OPTIONS, "Listen port set to %d.", listen_port);
180
181         int ip = 0;
182         char *ipv = config_get("global", "ip version", "any");
183         if(!strcmp(ipv, "any") || !strcmp(ipv, "both") || !strcmp(ipv, "all")) ip = 0;
184         else if(!strcmp(ipv, "ipv4") || !strcmp(ipv, "IPV4") || !strcmp(ipv, "IPv4") || !strcmp(ipv, "4")) ip = 4;
185         else if(!strcmp(ipv, "ipv6") || !strcmp(ipv, "IPV6") || !strcmp(ipv, "IPv6") || !strcmp(ipv, "6")) ip = 6;
186         else error("Cannot understand ip version '%s'. Assuming 'any'.", ipv);
187
188         if(ip == 0 || ip == 6) listen_fd = create_listen_socket6(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
189         if(listen_fd < 0) {
190                 listen_fd = create_listen_socket4(config_get("global", "bind socket to IP", "*"), listen_port, listen_backlog);
191                 // if(listen_fd >= 0 && ip != 4) info("Managed to open an IPv4 socket on port %d.", listen_port);
192         }
193
194         return listen_fd;
195 }
196
197 // --------------------------------------------------------------------------------------
198 // the main socket listener
199
200 // 1. it accepts new incoming requests on our port
201 // 2. creates a new web_client for each connection received
202 // 3. spawns a new pthread to serve the client (this is optimal for keep-alive clients)
203 // 4. cleans up old web_clients that their pthreads have been exited
204
205 #define CLEANUP_EVERY_EVENTS 1000
206
207 void *socket_listen_main_multi_threaded(void *ptr) {
208         if(ptr) { ; }
209
210         web_server_mode = WEB_SERVER_MODE_MULTI_THREADED;
211         info("Multi-threaded WEB SERVER thread created with task id %d", gettid());
212
213         struct web_client *w;
214         struct timeval tv;
215         int retval, failures = 0, counter = 0;
216
217         if(ptr) { ; }
218
219         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
220                 error("Cannot set pthread cancel type to DEFERRED.");
221
222         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
223                 error("Cannot set pthread cancel state to ENABLE.");
224
225         if(listen_fd < 0 || listen_fd >= FD_SETSIZE) fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fd);
226
227         fd_set ifds;
228         FD_ZERO (&ifds);
229
230         for(;;) {
231                 tv.tv_sec = 0;
232                 tv.tv_usec = 100000;
233
234                 if(likely(listen_fd >= 0))
235                         FD_SET(listen_fd, &ifds);
236
237                 // debug(D_WEB_CLIENT, "LISTENER: Waiting...");
238                 retval = select(listen_fd + 1, &ifds, NULL, NULL, &tv);
239
240                 if(unlikely(retval == -1)) {
241                         error("LISTENER: select() failed.");
242                         failures++;
243
244                         if(failures > 10) {
245                                 error("LISTENER: our listen port %d seems dead. Re-opening it.", listen_fd);
246                                 close(listen_fd);
247                                 listen_fd = -1;
248                                 sleep(5);
249                                 create_listen_socket();
250                                 if(listen_fd < 0)
251                                         fatal("Cannot listen for web clients (connected clients %llu).", global_statistics.connected_clients);
252
253                                 failures = 0;
254                         }
255
256                         continue;
257                 }
258                 else if(likely(retval)) {
259                         // check for new incoming connections
260                         if(likely(FD_ISSET(listen_fd, &ifds))) {
261                                 w = web_client_create(listen_fd);
262                                 if(unlikely(!w)) {
263                                         // no need for error log - web_client_create already logged the error
264                                         continue;
265                                 }
266
267                                 if(pthread_create(&w->thread, NULL, web_client_main, w) != 0) {
268                                         error("%llu: failed to create new thread for web client.");
269                                         w->obsolete = 1;
270                                 }
271                                 else if(pthread_detach(w->thread) != 0) {
272                                         error("%llu: Cannot request detach of newly created web client thread.", w->id);
273                                         w->obsolete = 1;
274                                 }
275                         }
276                         else debug(D_WEB_CLIENT, "LISTENER: select() didn't do anything.");
277
278                 }
279                 else {
280                         debug(D_WEB_CLIENT, "LISTENER: select() timeout.");
281                         counter = CLEANUP_EVERY_EVENTS;
282                 }
283
284                 // cleanup unused clients
285                 counter++;
286                 if(counter > CLEANUP_EVERY_EVENTS) {
287                         counter = 0;
288                         for (w = web_clients; w;) {
289                                 if (w->obsolete) {
290                                         debug(D_WEB_CLIENT, "%llu: Removing client.", w->id);
291                                         // pthread_cancel(w->thread);
292                                         // pthread_join(w->thread, NULL);
293                                         w = web_client_free(w);
294 #ifdef NETDATA_INTERNAL_CHECKS
295                                         log_allocations();
296 #endif
297                                 }
298                                 else w = w->next;
299                         }
300                 }
301
302                 failures = 0;
303         }
304
305         error("LISTENER: exit!");
306         close(listen_fd);
307         listen_fd = -1;
308         return NULL;
309 }
310
311 struct web_client *single_threaded_clients[FD_SETSIZE];
312
313 static inline int single_threaded_link_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds, int *max) {
314         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
315                 return 1;
316
317         if(unlikely(w->ifd < 0 || w->ifd >= FD_SETSIZE || w->ofd < 0 || w->ofd >= FD_SETSIZE)) {
318                 error("%llu: invalid file descriptor, ifd = %d, ofd = %d (required 0 <= fd < FD_SETSIZE (%d)", w->id, w->ifd, w->ofd, FD_SETSIZE);
319                 return 1;
320         }
321
322         FD_SET(w->ifd, efds);
323         if(unlikely(*max < w->ifd)) *max = w->ifd;
324
325         if(unlikely(w->ifd != w->ofd)) {
326                 if(*max < w->ofd) *max = w->ofd;
327                 FD_SET(w->ofd, efds);
328         }
329
330         if(w->wait_receive) FD_SET(w->ifd, ifds);
331         if(w->wait_send)    FD_SET(w->ofd, ofds);
332
333         single_threaded_clients[w->ifd] = w;
334         single_threaded_clients[w->ofd] = w;
335
336         return 0;
337 }
338
339 static inline int single_threaded_unlink_client(struct web_client *w, fd_set *ifds, fd_set *ofds, fd_set *efds) {
340         FD_CLR(w->ifd, efds);
341         if(unlikely(w->ifd != w->ofd)) FD_CLR(w->ofd, efds);
342
343         if(w->wait_receive) FD_CLR(w->ifd, ifds);
344         if(w->wait_send)    FD_CLR(w->ofd, ofds);
345
346         single_threaded_clients[w->ifd] = NULL;
347         single_threaded_clients[w->ofd] = NULL;
348
349         if(unlikely(w->obsolete || w->dead || (!w->wait_receive && !w->wait_send)))
350                 return 1;
351
352         return 0;
353 }
354
355 void *socket_listen_main_single_threaded(void *ptr) {
356         (void)ptr;
357
358         web_server_mode = WEB_SERVER_MODE_SINGLE_THREADED;
359
360         info("Single threaded WEB SERVER thread created with task id %d", gettid());
361
362         struct web_client *w;
363         int retval, failures = 0;
364
365         if(ptr) { ; }
366
367         if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
368                 error("Cannot set pthread cancel type to DEFERRED.");
369
370         if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
371                 error("Cannot set pthread cancel state to ENABLE.");
372
373         if(listen_fd < 0 || listen_fd >= FD_SETSIZE)
374                 fatal("LISTENER: Listen socket %d is not ready, or invalid.", listen_fd);
375
376         int i;
377         for(i = 0; i < FD_SETSIZE ; i++)
378                 single_threaded_clients[i] = NULL;
379
380         fd_set ifds, ofds, efds, rifds, rofds, refds;
381         FD_ZERO (&ifds);
382         FD_ZERO (&ofds);
383         FD_ZERO (&efds);
384         FD_SET(listen_fd, &ifds);
385         FD_SET(listen_fd, &efds);
386         int fdmax = listen_fd;
387
388         for(;;) {
389                 debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server waiting (listen fd = %d, fdmax = %d)...", listen_fd, fdmax);
390
391                 struct timeval tv = { .tv_sec = 1, .tv_usec = 0 };
392                 rifds = ifds;
393                 rofds = ofds;
394                 refds = efds;
395                 retval = select(fdmax+1, &rifds, &rofds, &refds, &tv);
396
397                 if(unlikely(retval == -1)) {
398                         error("LISTENER: select() failed.");
399                         failures++;
400                         if(failures > 10) {
401                                 if(global_statistics.connected_clients) {
402                                         error("REMOVING ALL %lu WEB CLIENTS !", global_statistics.connected_clients);
403                                         while (web_clients) {
404                                                 single_threaded_unlink_client(web_clients, &ifds, &ofds, &efds);
405                                                 web_client_free(web_clients);
406                                         }
407                                 }
408
409                                 error("LISTENER: our listen port %d seems dead. Re-opening it.", listen_fd);
410
411                                 close(listen_fd);
412                                 listen_fd = -1;
413                                 sleep(5);
414
415                                 create_listen_socket();
416                                 if(listen_fd < 0 || listen_fd >= FD_SETSIZE)
417                                         fatal("Cannot listen for web clients (connected clients %llu).", global_statistics.connected_clients);
418
419                                 FD_ZERO (&ifds);
420                                 FD_ZERO (&ofds);
421                                 FD_ZERO (&efds);
422                                 FD_SET(listen_fd, &ifds);
423                                 FD_SET(listen_fd, &efds);
424                                 failures = 0;
425                         }
426                 }
427                 else if(likely(retval)) {
428                         failures = 0;
429                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: got something.");
430
431                         if(FD_ISSET(listen_fd, &rifds)) {
432                                 debug(D_WEB_CLIENT_ACCESS, "LISTENER: new connection.");
433                                 w = web_client_create(listen_fd);
434                                 if(single_threaded_link_client(w, &ifds, &ofds, &ifds, &fdmax) != 0) {
435                                         web_client_free(w);
436                                 }
437                         }
438
439                         for(i = 0 ; i <= fdmax ; i++) {
440                                 if(likely(!FD_ISSET(i, &rifds) && !FD_ISSET(i, &rofds) && !FD_ISSET(i, &refds)))
441                                         continue;
442
443                                 w = single_threaded_clients[i];
444                                 if(unlikely(!w))
445                                         continue;
446
447                                 if(unlikely(single_threaded_unlink_client(w, &ifds, &ofds, &efds) != 0)) {
448                                         web_client_free(w);
449                                         continue;
450                                 }
451
452                                 if (unlikely(FD_ISSET(w->ifd, &refds) || FD_ISSET(w->ofd, &refds))) {
453                                         web_client_free(w);
454                                         continue;
455                                 }
456
457                                 if (unlikely(w->wait_receive && FD_ISSET(w->ifd, &rifds))) {
458                                         if (unlikely(web_client_receive(w) < 0)) {
459                                                 web_client_free(w);
460                                                 continue;
461                                         }
462
463                                         if (w->mode != WEB_CLIENT_MODE_FILECOPY) {
464                                                 debug(D_WEB_CLIENT, "%llu: Processing received data.", w->id);
465                                                 web_client_process(w);
466                                         }
467                                 }
468
469                                 if (unlikely(w->wait_send && FD_ISSET(w->ofd, &rofds))) {
470                                         if (unlikely(web_client_send(w) < 0)) {
471                                                 debug(D_WEB_CLIENT, "%llu: Cannot send data to client. Closing client.", w->id);
472                                                 web_client_free(w);
473                                                 continue;
474                                         }
475                                 }
476
477                                 if(unlikely(single_threaded_link_client(w, &ifds, &ofds, &efds, &fdmax) != 0)) {
478                                         web_client_free(w);
479                                 }
480                         }
481                 }
482                 else {
483                         debug(D_WEB_CLIENT_ACCESS, "LISTENER: single threaded web server timeout.");
484 #ifdef NETDATA_INTERNAL_CHECKS
485                         log_allocations();
486 #endif
487                 }
488         }
489
490         error("LISTENER: exit!");
491         close(listen_fd);
492         listen_fd = -1;
493         return NULL;
494 }