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