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