]> arthur.barton.de Git - netdata.git/blob - src/rrdpush.c
avoid code duplication
[netdata.git] / src / rrdpush.c
1 #include "common.h"
2
3 /*
4  * rrdpush
5  *
6  * 3 threads are involved for all stream operations
7  *
8  * 1. a random data collection thread, calling rrdset_done_push()
9  *    this is called for each chart.
10  *
11  *    the output of this work is kept in a BUFFER in RRDHOST
12  *    the sender thread is signalled via a pipe (also in RRDHOST)
13  *
14  * 2. a sender thread running at the sending netdata
15  *    this is spawned automatically on the first chart to be pushed
16  *
17  *    It tries to push the metrics to the remote netdata, as fast
18  *    as possible (i.e. immediately after they are collected).
19  *
20  * 3. a receiver thread, running at the receiving netdata
21  *    this is spawned automatically when the sender connects to
22  *    the receiver.
23  *
24  */
25
26 #define START_STREAMING_PROMPT "Hit me baby, push them over..."
27
28 int default_rrdpush_enabled = 0;
29 char *default_rrdpush_destination = NULL;
30 char *default_rrdpush_api_key = NULL;
31
32 int rrdpush_init() {
33     default_rrdpush_enabled     = appconfig_get_boolean(&stream_config, CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
34     default_rrdpush_destination = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "destination", "");
35     default_rrdpush_api_key     = appconfig_get(&stream_config, CONFIG_SECTION_STREAM, "api key", "");
36
37     if(default_rrdpush_enabled && (!default_rrdpush_destination || !*default_rrdpush_destination || !default_rrdpush_api_key || !*default_rrdpush_api_key)) {
38         error("STREAM [send]: cannot enable sending thread - information is missing.");
39         default_rrdpush_enabled = 0;
40     }
41
42     return default_rrdpush_enabled;
43 }
44
45 #define CONNECTED_TO_SIZE 100
46
47 // data collection happens from multiple threads
48 // each of these threads calls rrdset_done()
49 // which in turn calls rrdset_done_push()
50 // which uses this pipe to notify the streaming thread
51 // that there are more data ready to be sent
52 #define PIPE_READ 0
53 #define PIPE_WRITE 1
54
55 // to have the remote netdata re-sync the charts
56 // to its current clock, we send for this many
57 // iterations a BEGIN line without microseconds
58 // this is for the first iterations of each chart
59 static unsigned int remote_clock_resync_iterations = 60;
60
61 #define rrdpush_lock(host) pthread_mutex_lock(&((host)->rrdpush_mutex))
62 #define rrdpush_unlock(host) pthread_mutex_unlock(&((host)->rrdpush_mutex))
63
64 // checks if the current chart definition has been sent
65 static inline int need_to_send_chart_definition(RRDSET *st) {
66     RRDDIM *rd;
67     rrddim_foreach_read(rd, st)
68         if(!rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
69             return 1;
70
71     return 0;
72 }
73
74 // sends the current chart definition
75 static inline void send_chart_definition(RRDSET *st) {
76     buffer_sprintf(st->rrdhost->rrdpush_buffer, "CHART '%s' '%s' '%s' '%s' '%s' '%s' '%s' %ld %d\n"
77                 , st->id
78                 , st->name
79                 , st->title
80                 , st->units
81                 , st->family
82                 , st->context
83                 , rrdset_type_name(st->chart_type)
84                 , st->priority
85                 , st->update_every
86     );
87
88     RRDDIM *rd;
89     rrddim_foreach_read(rd, st) {
90         buffer_sprintf(st->rrdhost->rrdpush_buffer, "DIMENSION '%s' '%s' '%s' " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " '%s %s'\n"
91                        , rd->id
92                        , rd->name
93                        , rrd_algorithm_name(rd->algorithm)
94                        , rd->multiplier
95                        , rd->divisor
96                        , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
97                        , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
98         );
99         rrddim_flag_set(rd, RRDDIM_FLAG_EXPOSED);
100     }
101 }
102
103 // sends the current chart dimensions
104 static inline void send_chart_metrics(RRDSET *st) {
105     buffer_sprintf(st->rrdhost->rrdpush_buffer, "BEGIN %s %llu\n", st->id, (st->counter_done > remote_clock_resync_iterations)?st->usec_since_last_update:0);
106
107     RRDDIM *rd;
108     rrddim_foreach_read(rd, st) {
109         if(rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED) && rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
110             buffer_sprintf(st->rrdhost->rrdpush_buffer, "SET %s = " COLLECTED_NUMBER_FORMAT "\n"
111                        , rd->id
112                        , rd->collected_value
113         );
114     }
115
116     buffer_strcat(st->rrdhost->rrdpush_buffer, "END\n");
117 }
118
119 void rrdpush_sender_thread_spawn(RRDHOST *host);
120
121 void rrdset_done_push(RRDSET *st) {
122     RRDHOST *host = st->rrdhost;
123
124     if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED)))
125         return;
126
127     rrdpush_lock(host);
128
129     if(unlikely(host->rrdpush_enabled && !host->rrdpush_spawn))
130         rrdpush_sender_thread_spawn(host);
131
132     if(unlikely(!host->rrdpush_buffer || !host->rrdpush_connected)) {
133         if(unlikely(!host->rrdpush_error_shown))
134             error("STREAM %s [send]: not ready - discarding collected metrics.", host->hostname);
135
136         host->rrdpush_error_shown = 1;
137
138         rrdpush_unlock(host);
139         return;
140     }
141     else if(unlikely(host->rrdpush_error_shown)) {
142         info("STREAM %s [send]: ready - sending metrics...", host->hostname);
143         host->rrdpush_error_shown = 0;
144     }
145
146     if(need_to_send_chart_definition(st))
147         send_chart_definition(st);
148
149     send_chart_metrics(st);
150
151     // signal the sender there are more data
152     if(write(host->rrdpush_pipe[PIPE_WRITE], " ", 1) == -1)
153         error("STREAM %s [send]: cannot write to internal pipe", host->hostname);
154
155     rrdpush_unlock(host);
156 }
157
158 // ----------------------------------------------------------------------------
159 // rrdpush sender thread
160
161 // resets all the chart, so that their definitions
162 // will be resent to the central netdata
163 static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
164     rrdhost_rdlock(host);
165
166     RRDSET *st;
167     rrdset_foreach_read(st, host) {
168
169         // make it re-align the current time
170         // on the remote host
171         st->counter_done = 0;
172
173         rrdset_rdlock(st);
174
175         RRDDIM *rd;
176         rrddim_foreach_read(rd, st)
177             rrddim_flag_clear(rd, RRDDIM_FLAG_EXPOSED);
178
179         rrdset_unlock(st);
180     }
181
182     rrdhost_unlock(host);
183 }
184
185 static inline void rrdpush_sender_thread_data_flush(RRDHOST *host) {
186     rrdpush_lock(host);
187     if(buffer_strlen(host->rrdpush_buffer))
188         error("STREAM %s [send]: discarding %zu bytes of metrics already in the buffer.", host->hostname, buffer_strlen(host->rrdpush_buffer));
189
190     buffer_flush(host->rrdpush_buffer);
191     rrdpush_sender_thread_reset_all_charts(host);
192     rrdpush_unlock(host);
193 }
194
195 static inline void rrdpush_sender_thread_lock(RRDHOST *host) {
196     if(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0)
197         error("STREAM %s [send]: cannot set pthread cancel state to DISABLE.", host->hostname);
198
199     rrdpush_lock(host);
200 }
201
202 static inline void rrdpush_sender_thread_unlock(RRDHOST *host) {
203     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
204         error("STREAM %s [send]: cannot set pthread cancel state to DISABLE.", host->hostname);
205
206     rrdpush_unlock(host);
207 }
208
209 static void rrdpush_sender_thread_cleanup(RRDHOST *host) {
210     rrdpush_lock(host);
211
212     host->rrdpush_connected = 0;
213
214     if(host->rrdpush_socket != -1) {
215         close(host->rrdpush_socket);
216         host->rrdpush_socket = -1;
217     }
218
219     // close the pipe
220     if(host->rrdpush_pipe[PIPE_READ] != -1) {
221         close(host->rrdpush_pipe[PIPE_READ]);
222         host->rrdpush_pipe[PIPE_READ] = -1;
223     }
224
225     if(host->rrdpush_pipe[PIPE_WRITE] != -1) {
226         close(host->rrdpush_pipe[PIPE_WRITE]);
227         host->rrdpush_pipe[PIPE_WRITE] = -1;
228     }
229
230     buffer_free(host->rrdpush_buffer);
231     host->rrdpush_buffer = NULL;
232
233     host->rrdpush_spawn = 0;
234
235     rrdpush_unlock(host);
236 }
237
238 void rrdpush_sender_thread_stop(RRDHOST *host) {
239     rrdhost_check_wrlock(host);
240
241     if(host->rrdpush_spawn) {
242         info("STREAM %s [send]: stopping sending thread...", host->hostname);
243         pthread_cancel(host->rrdpush_thread);
244         rrdpush_sender_thread_cleanup(host);
245     }
246 }
247
248 void *rrdpush_sender_thread(void *ptr) {
249     RRDHOST *host = (RRDHOST *)ptr;
250
251     info("STREAM %s [send]: thread created (task id %d)", host->hostname, gettid());
252
253     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
254         error("STREAM %s [send]: cannot set pthread cancel type to DEFERRED.", host->hostname);
255
256     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
257         error("STREAM %s [send]: cannot set pthread cancel state to ENABLE.", host->hostname);
258
259     int timeout = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "timeout seconds", 60);
260     int default_port = (int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "default port", 19999);
261     size_t max_size = (size_t)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024);
262     unsigned int reconnect_delay = (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
263     remote_clock_resync_iterations = (unsigned int)appconfig_get_number(&stream_config, CONFIG_SECTION_STREAM, "initial clock resync iterations", remote_clock_resync_iterations);
264     char connected_to[CONNECTED_TO_SIZE + 1] = "";
265
266     if(!host->rrdpush_enabled || !host->rrdpush_destination || !*host->rrdpush_destination || !host->rrdpush_api_key || !*host->rrdpush_api_key)
267         goto cleanup;
268
269     // initialize rrdpush globals
270     host->rrdpush_buffer = buffer_create(1);
271     host->rrdpush_connected = 0;
272     if(pipe(host->rrdpush_pipe) == -1) fatal("STREAM %s [send]: cannot create required pipe.", host->hostname);
273
274     // initialize local variables
275     size_t begin = 0;
276     size_t reconnects_counter = 0;
277     size_t sent_bytes = 0;
278     size_t sent_connection = 0;
279
280     struct timeval tv = {
281             .tv_sec = timeout,
282             .tv_usec = 0
283     };
284
285     struct pollfd fds[2], *ifd, *ofd;
286     nfds_t fdmax;
287
288     ifd = &fds[0];
289     ofd = &fds[1];
290
291     for(; host->rrdpush_enabled && !netdata_exit ;) {
292
293         if(unlikely(host->rrdpush_socket == -1)) {
294             // stop appending data into rrdpush_buffer
295             // they will be lost, so there is no point to do it
296             host->rrdpush_connected = 0;
297
298             info("STREAM %s [send to %s]: connecting...", host->hostname, host->rrdpush_destination);
299             host->rrdpush_socket = connect_to_one_of(host->rrdpush_destination, default_port, &tv, &reconnects_counter, connected_to, CONNECTED_TO_SIZE);
300
301             if(unlikely(host->rrdpush_socket == -1)) {
302                 error("STREAM %s [send to %s]: failed to connect", host->hostname, host->rrdpush_destination);
303                 sleep(reconnect_delay);
304                 continue;
305             }
306
307             info("STREAM %s [send to %s]: initializing communication...", host->hostname, connected_to);
308
309             char http[1000 + 1];
310             snprintfz(http, 1000,
311                     "STREAM key=%s&hostname=%s&machine_guid=%s&os=%s&update_every=%d HTTP/1.1\r\n"
312                     "User-Agent: netdata-push-service/%s\r\n"
313                     "Accept: */*\r\n\r\n"
314                       , host->rrdpush_api_key
315                       , host->hostname
316                       , host->machine_guid
317                       , host->os
318                       , default_rrd_update_every
319                       , program_version
320             );
321
322             if(send_timeout(host->rrdpush_socket, http, strlen(http), 0, timeout) == -1) {
323                 close(host->rrdpush_socket);
324                 host->rrdpush_socket = -1;
325                 error("STREAM %s [send to %s]: failed to send http header to netdata", host->hostname, connected_to);
326                 sleep(reconnect_delay);
327                 continue;
328             }
329
330             info("STREAM %s [send to %s]: waiting response from remote netdata...", host->hostname, connected_to);
331
332             if(recv_timeout(host->rrdpush_socket, http, 1000, 0, timeout) == -1) {
333                 close(host->rrdpush_socket);
334                 host->rrdpush_socket = -1;
335                 error("STREAM %s [send to %s]: failed to initialize communication", host->hostname, connected_to);
336                 sleep(reconnect_delay);
337                 continue;
338             }
339
340             if(strncmp(http, START_STREAMING_PROMPT, strlen(START_STREAMING_PROMPT))) {
341                 close(host->rrdpush_socket);
342                 host->rrdpush_socket = -1;
343                 error("STREAM %s [send to %s]: server is not replying properly.", host->hostname, connected_to);
344                 sleep(reconnect_delay);
345                 continue;
346             }
347
348             info("STREAM %s [send to %s]: established communication - sending metrics...", host->hostname, connected_to);
349
350             if(fcntl(host->rrdpush_socket, F_SETFL, O_NONBLOCK) < 0)
351                 error("STREAM %s [send to %s]: cannot set non-blocking mode for socket.", host->hostname, connected_to);
352
353             rrdpush_sender_thread_data_flush(host);
354             sent_connection = 0;
355
356             // allow appending data into rrdpush_buffer
357             host->rrdpush_connected = 1;
358         }
359
360         ifd->fd = host->rrdpush_pipe[PIPE_READ];
361         ifd->events = POLLIN;
362         ifd->revents = 0;
363
364         ofd->fd = host->rrdpush_socket;
365         ofd->revents = 0;
366         if(begin < buffer_strlen(host->rrdpush_buffer)) {
367             ofd->events = POLLOUT;
368             fdmax = 2;
369         }
370         else {
371             ofd->events = 0;
372             fdmax = 1;
373         }
374
375         if(netdata_exit) break;
376         int retval = poll(fds, fdmax, timeout * 1000);
377         if(netdata_exit) break;
378
379         if(unlikely(retval == -1)) {
380             if(errno == EAGAIN || errno == EINTR)
381                 continue;
382
383             error("STREAM %s [send to %s]: failed to poll().", host->hostname, connected_to);
384             close(host->rrdpush_socket);
385             host->rrdpush_socket = -1;
386             break;
387         }
388         else if(unlikely(!retval)) {
389             // timeout
390             continue;
391         }
392
393         if(ifd->revents & POLLIN) {
394             char buffer[1000 + 1];
395             if(read(host->rrdpush_pipe[PIPE_READ], buffer, 1000) == -1)
396                 error("STREAM %s [send to %s]: cannot read from internal pipe.", host->hostname, connected_to);
397         }
398
399         if(ofd->revents & POLLOUT && begin < buffer_strlen(host->rrdpush_buffer)) {
400             rrdpush_sender_thread_lock(host);
401             ssize_t ret = send(host->rrdpush_socket, &host->rrdpush_buffer->buffer[begin], buffer_strlen(host->rrdpush_buffer) - begin, MSG_DONTWAIT);
402             if(ret == -1) {
403                 if(errno != EAGAIN && errno != EINTR) {
404                     error("STREAM %s [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", host->hostname, connected_to, sent_connection);
405                     close(host->rrdpush_socket);
406                     host->rrdpush_socket = -1;
407                 }
408             }
409             else {
410                 sent_connection += ret;
411                 sent_bytes += ret;
412                 begin += ret;
413                 if(begin == buffer_strlen(host->rrdpush_buffer)) {
414                     buffer_flush(host->rrdpush_buffer);
415                     begin = 0;
416                 }
417             }
418             rrdpush_sender_thread_unlock(host);
419         }
420
421         // protection from overflow
422         if(host->rrdpush_buffer->len > max_size) {
423             errno = 0;
424             error("STREAM %s [send to %s]: too many data pending - buffer is %zu bytes long, %zu unsent - we have sent %zu bytes in total, %zu on this connection. Closing connection to flush the data.", host->hostname, connected_to, host->rrdpush_buffer->len, host->rrdpush_buffer->len - begin, sent_bytes, sent_connection);
425             if(host->rrdpush_socket != -1) {
426                 close(host->rrdpush_socket);
427                 host->rrdpush_socket = -1;
428             }
429         }
430     }
431
432 cleanup:
433     debug(D_WEB_CLIENT, "STREAM %s [send]: sending thread exits.", host->hostname);
434
435     rrdpush_sender_thread_cleanup(host);
436
437     pthread_exit(NULL);
438     return NULL;
439 }
440
441
442 // ----------------------------------------------------------------------------
443 // rrdpush receiver thread
444
445 int rrdpush_receive(int fd, const char *key, const char *hostname, const char *machine_guid, const char *os, int update_every, char *client_ip, char *client_port) {
446     RRDHOST *host;
447     int history = default_rrd_history_entries;
448     RRD_MEMORY_MODE mode = default_rrd_memory_mode;
449     int health_enabled = default_health_enabled;
450     int rrdpush_enabled = default_rrdpush_enabled;
451     char *rrdpush_destination = default_rrdpush_destination;
452     char *rrdpush_api_key = default_rrdpush_api_key;
453     time_t alarms_delay = 60;
454
455     update_every = (int)appconfig_get_number(&stream_config, machine_guid, "update every", update_every);
456     if(update_every < 0) update_every = 1;
457
458     history = (int)appconfig_get_number(&stream_config, key, "default history", history);
459     history = (int)appconfig_get_number(&stream_config, machine_guid, "history", history);
460     if(history < 5) history = 5;
461
462     mode = rrd_memory_mode_id(appconfig_get(&stream_config, key, "default memory mode", rrd_memory_mode_name(mode)));
463     mode = rrd_memory_mode_id(appconfig_get(&stream_config, machine_guid, "memory mode", rrd_memory_mode_name(mode)));
464
465     health_enabled = appconfig_get_boolean_ondemand(&stream_config, key, "health enabled by default", health_enabled);
466     health_enabled = appconfig_get_boolean_ondemand(&stream_config, machine_guid, "health enabled", health_enabled);
467
468     alarms_delay = appconfig_get_number(&stream_config, key, "default postpone alarms on connect seconds", alarms_delay);
469     alarms_delay = appconfig_get_number(&stream_config, machine_guid, "postpone alarms on connect seconds", alarms_delay);
470
471     rrdpush_enabled = appconfig_get_boolean(&stream_config, key, "default proxy enabled", rrdpush_enabled);
472     rrdpush_enabled = appconfig_get_boolean(&stream_config, machine_guid, "proxy enabled", rrdpush_enabled);
473
474     rrdpush_destination = appconfig_get(&stream_config, key, "default proxy destination", rrdpush_destination);
475     rrdpush_destination = appconfig_get(&stream_config, machine_guid, "proxy destination", rrdpush_destination);
476
477     rrdpush_api_key = appconfig_get(&stream_config, key, "default proxy api key", rrdpush_api_key);
478     rrdpush_api_key = appconfig_get(&stream_config, machine_guid, "proxy api key", rrdpush_api_key);
479
480     if(!strcmp(machine_guid, "localhost"))
481         host = localhost;
482     else
483         host = rrdhost_find_or_create(
484                 hostname
485                 , machine_guid
486                 , os
487                 , update_every
488                 , history
489                 , mode
490                 , (health_enabled != CONFIG_BOOLEAN_NO)
491                 , (rrdpush_enabled && rrdpush_destination && *rrdpush_destination && rrdpush_api_key && *rrdpush_api_key)
492                 , rrdpush_destination
493                 , rrdpush_api_key
494         );
495
496     if(!host) {
497         close(fd);
498         error("STREAM %s [receive from [%s]:%s]: failed to find/create host structure.", hostname, client_ip, client_port);
499         return 1;
500     }
501
502 #ifdef NETDATA_INTERNAL_CHECKS
503     info("STREAM %s [receive from [%s]:%s]: client willing to stream metrics for host '%s' with machine_guid '%s': update every = %d, history = %d, memory mode = %s, health %s"
504          , hostname
505          , client_ip
506          , client_port
507          , host->hostname
508          , host->machine_guid
509          , host->rrd_update_every
510          , host->rrd_history_entries
511          , rrd_memory_mode_name(host->rrd_memory_mode)
512          , (health_enabled == CONFIG_BOOLEAN_NO)?"disabled":((health_enabled == CONFIG_BOOLEAN_YES)?"enabled":"auto")
513     );
514 #endif // NETDATA_INTERNAL_CHECKS
515
516     struct plugind cd = {
517             .enabled = 1,
518             .update_every = default_rrd_update_every,
519             .pid = 0,
520             .serial_failures = 0,
521             .successful_collections = 0,
522             .obsolete = 0,
523             .started_t = now_realtime_sec(),
524             .next = NULL,
525     };
526
527     // put the client IP and port into the buffers used by plugins.d
528     snprintfz(cd.id,           CONFIG_MAX_NAME,  "%s:%s", client_ip, client_port);
529     snprintfz(cd.filename,     FILENAME_MAX,     "%s:%s", client_ip, client_port);
530     snprintfz(cd.fullfilename, FILENAME_MAX,     "%s:%s", client_ip, client_port);
531     snprintfz(cd.cmd,          PLUGINSD_CMD_MAX, "%s:%s", client_ip, client_port);
532
533     info("STREAM %s [receive from [%s]:%s]: initializing communication...", host->hostname, client_ip, client_port);
534     if(send_timeout(fd, START_STREAMING_PROMPT, strlen(START_STREAMING_PROMPT), 0, 60) != strlen(START_STREAMING_PROMPT)) {
535         error("STREAM %s [receive from [%s]:%s]: cannot send ready command.", host->hostname, client_ip, client_port);
536         return 0;
537     }
538
539     // remove the non-blocking flag from the socket
540     if(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK) == -1)
541         error("STREAM %s [receive from [%s]:%s]: cannot remove the non-blocking flag from socket %d", host->hostname, client_ip, client_port, fd);
542
543     // convert the socket to a FILE *
544     FILE *fp = fdopen(fd, "r");
545     if(!fp) {
546         error("STREAM %s [receive from [%s]:%s]: failed to get a FILE for FD %d.", host->hostname, client_ip, client_port, fd);
547         return 0;
548     }
549
550     rrdhost_wrlock(host);
551     host->use_counter++;
552     if(health_enabled != CONFIG_BOOLEAN_NO)
553         host->health_delay_up_to = now_realtime_sec() + alarms_delay;
554     rrdhost_unlock(host);
555
556     // call the plugins.d processor to receive the metrics
557     info("STREAM %s [receive from [%s]:%s]: receiving metrics...", host->hostname, client_ip, client_port);
558     size_t count = pluginsd_process(host, &cd, fp, 1);
559     error("STREAM %s [receive from [%s]:%s]: disconnected (completed updates %zu).", host->hostname, client_ip, client_port, count);
560
561     rrdhost_wrlock(host);
562     host->use_counter--;
563     if(!host->use_counter) {
564         if(health_enabled == CONFIG_BOOLEAN_AUTO)
565             host->health_enabled = 0;
566
567         rrdpush_sender_thread_stop(host);
568     }
569     rrdhost_unlock(host);
570
571     // cleanup
572     fclose(fp);
573
574     return (int)count;
575 }
576
577 struct rrdpush_thread {
578     int fd;
579     char *key;
580     char *hostname;
581     char *machine_guid;
582     char *os;
583     char *client_ip;
584     char *client_port;
585     int update_every;
586 };
587
588 void *rrdpush_receiver_thread(void *ptr) {
589     struct rrdpush_thread *rpt = (struct rrdpush_thread *)ptr;
590
591     if (pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
592         error("STREAM %s [receive]: cannot set pthread cancel type to DEFERRED.", rpt->hostname);
593
594     if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
595         error("STREAM %s [receive]: cannot set pthread cancel state to ENABLE.", rpt->hostname);
596
597
598     info("STREAM %s [%s]:%s: receive thread created (task id %d)", rpt->hostname, rpt->client_ip, rpt->client_port, gettid());
599     rrdpush_receive(rpt->fd, rpt->key, rpt->hostname, rpt->machine_guid, rpt->os, rpt->update_every, rpt->client_ip, rpt->client_port);
600     info("STREAM %s [receive from [%s]:%s]: receive thread ended (task id %d)", rpt->hostname, rpt->client_ip, rpt->client_port, gettid());
601
602     close(rpt->fd);
603     freez(rpt->key);
604     freez(rpt->hostname);
605     freez(rpt->machine_guid);
606     freez(rpt->os);
607     freez(rpt->client_ip);
608     freez(rpt->client_port);
609     freez(rpt);
610
611     pthread_exit(NULL);
612     return NULL;
613 }
614
615 void rrdpush_sender_thread_spawn(RRDHOST *host) {
616     if(pthread_create(&host->rrdpush_thread, NULL, rrdpush_sender_thread, (void *)host))
617         error("STREAM %s [send]: failed to create new thread for client.", host->hostname);
618
619     else if(pthread_detach(host->rrdpush_thread))
620         error("STREAM %s [send]: cannot request detach newly created thread.", host->hostname);
621
622     host->rrdpush_spawn = 1;
623 }
624
625 int rrdpush_receiver_thread_spawn(RRDHOST *host, struct web_client *w, char *url) {
626     (void)host;
627
628     info("STREAM [receive from [%s]:%s]: new client connection.", w->client_ip, w->client_port);
629
630     char *key = NULL, *hostname = NULL, *machine_guid = NULL, *os = NULL;
631     int update_every = default_rrd_update_every;
632     char buf[GUID_LEN + 1];
633
634     while(url) {
635         char *value = mystrsep(&url, "?&");
636         if(!value || !*value) continue;
637
638         char *name = mystrsep(&value, "=");
639         if(!name || !*name) continue;
640         if(!value || !*value) continue;
641
642         if(!strcmp(name, "key"))
643             key = value;
644         else if(!strcmp(name, "hostname"))
645             hostname = value;
646         else if(!strcmp(name, "machine_guid"))
647             machine_guid = value;
648         else if(!strcmp(name, "update_every"))
649             update_every = (int)strtoul(value, NULL, 0);
650         else if(!strcmp(name, "os"))
651             os = value;
652     }
653
654     if(!key || !*key) {
655         error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
656         buffer_flush(w->response.data);
657         buffer_sprintf(w->response.data, "You need an API key for this request.");
658         return 401;
659     }
660
661     if(!hostname || !*hostname) {
662         error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
663         buffer_flush(w->response.data);
664         buffer_sprintf(w->response.data, "You need to send a hostname too.");
665         return 400;
666     }
667
668     if(!machine_guid || !*machine_guid) {
669         error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
670         buffer_flush(w->response.data);
671         buffer_sprintf(w->response.data, "You need to send a machine GUID too.");
672         return 400;
673     }
674
675     if(regenerate_guid(key, buf) == -1) {
676         error("STREAM [receive from [%s]:%s]: API key '%s' is not valid GUID. Forbidding access.", w->client_ip, w->client_port, key);
677         buffer_flush(w->response.data);
678         buffer_sprintf(w->response.data, "Your API key is invalid.");
679         return 401;
680     }
681
682     if(regenerate_guid(machine_guid, buf) == -1) {
683         error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not GUID. Forbidding access.", w->client_ip, w->client_port, key);
684         buffer_flush(w->response.data);
685         buffer_sprintf(w->response.data, "Your machine GUID is invalid.");
686         return 404;
687     }
688
689     if(!appconfig_get_boolean(&stream_config, key, "enabled", 1)) {
690         error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
691         buffer_flush(w->response.data);
692         buffer_sprintf(w->response.data, "Your API key is not permitted access.");
693         return 401;
694     }
695
696     if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
697         error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
698         buffer_flush(w->response.data);
699         buffer_sprintf(w->response.data, "Your machine guide is not permitted access.");
700         return 404;
701     }
702
703     struct rrdpush_thread *rpt = mallocz(sizeof(struct rrdpush_thread));
704     rpt->fd           = w->ifd;
705     rpt->key          = strdupz(key);
706     rpt->hostname     = strdupz(hostname);
707     rpt->machine_guid = strdupz(machine_guid);
708     rpt->os           = strdupz(os);
709     rpt->client_ip    = strdupz(w->client_ip);
710     rpt->client_port  = strdupz(w->client_port);
711     rpt->update_every = update_every;
712     pthread_t thread;
713
714     debug(D_SYSTEM, "STREAM [receive from [%s]:%s]: starting receiving thread.", w->client_ip, w->client_port);
715
716     if(pthread_create(&thread, NULL, rrdpush_receiver_thread, (void *)rpt))
717         error("STREAM [receive from [%s]:%s]: failed to create new thread for client.", w->client_ip, w->client_port);
718
719     else if(pthread_detach(thread))
720         error("STREAM [receive from [%s]:%s]: cannot request detach newly created thread.", w->client_ip, w->client_port);
721
722     // prevent the caller from closing the streaming socket
723     if(w->ifd == w->ofd)
724         w->ifd = w->ofd = -1;
725     else
726         w->ifd = -1;
727
728     buffer_flush(w->response.data);
729     return 200;
730 }