6 * 3 threads are involved for all stream operations
8 * 1. a random data collection thread, calling rrdset_done_push()
9 * this is called for each chart.
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)
14 * 2. a sender thread running at the sending netdata
15 * this is spawned automatically on the first chart to be pushed
17 * It tries to push the metrics to the remote netdata, as fast
18 * as possible (i.e. immediately after they are collected).
20 * 3. a receiver thread, running at the receiving netdata
21 * this is spawned automatically when the sender connects to
26 int default_rrdpush_enabled = 0;
27 static char *rrdpush_destination = NULL;
28 static char *rrdpush_api_key = NULL;
31 default_rrdpush_enabled = config_get_boolean(CONFIG_SECTION_STREAM, "enabled", default_rrdpush_enabled);
32 rrdpush_destination = config_get(CONFIG_SECTION_STREAM, "destination", "");
33 rrdpush_api_key = config_get(CONFIG_SECTION_STREAM, "api key", "");
35 if(default_rrdpush_enabled && (!rrdpush_destination || !*rrdpush_destination || !rrdpush_api_key || !*rrdpush_api_key)) {
36 error("STREAM [send]: cannot enable sending thread - information is missing.");
37 default_rrdpush_enabled = 0;
40 return default_rrdpush_enabled;
43 #define CONNECTED_TO_SIZE 100
45 // data collection happens from multiple threads
46 // each of these threads calls rrdset_done()
47 // which in turn calls rrdset_done_push()
48 // which uses this pipe to notify the streaming thread
49 // that there are more data ready to be sent
53 // to have the remote netdata re-sync the charts
54 // to its current clock, we send for this many
55 // iterations a BEGIN line without microseconds
56 // this is for the first iterations of each chart
57 static unsigned int remote_clock_resync_iterations = 60;
59 #define rrdpush_lock(host) pthread_mutex_lock(&((host)->rrdpush_mutex))
60 #define rrdpush_unlock(host) pthread_mutex_unlock(&((host)->rrdpush_mutex))
62 // checks if the current chart definition has been sent
63 static inline int need_to_send_chart_definition(RRDSET *st) {
65 rrddim_foreach_read(rd, st)
66 if(!rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
72 // sends the current chart definition
73 static inline void send_chart_definition(RRDSET *st) {
74 buffer_sprintf(st->rrdhost->rrdpush_buffer, "CHART '%s' '%s' '%s' '%s' '%s' '%s' '%s' %ld %d\n"
81 , rrdset_type_name(st->chart_type)
87 rrddim_foreach_read(rd, st) {
88 buffer_sprintf(st->rrdhost->rrdpush_buffer, "DIMENSION '%s' '%s' '%s' " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " '%s %s'\n"
91 , rrd_algorithm_name(rd->algorithm)
94 , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
95 , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
97 rrddim_flag_set(rd, RRDDIM_FLAG_EXPOSED);
101 // sends the current chart dimensions
102 static inline void send_chart_metrics(RRDSET *st) {
103 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 rrddim_foreach_read(rd, st) {
107 if(rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED) && rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
108 buffer_sprintf(st->rrdhost->rrdpush_buffer, "SET %s = " COLLECTED_NUMBER_FORMAT "\n"
110 , rd->collected_value
114 buffer_strcat(st->rrdhost->rrdpush_buffer, "END\n");
117 void rrdpush_sender_thread_spawn(RRDHOST *host);
119 void rrdset_done_push(RRDSET *st) {
120 RRDHOST *host = st->rrdhost;
122 if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED)))
127 if(unlikely(host->rrdpush_enabled && !host->rrdpush_spawn))
128 rrdpush_sender_thread_spawn(host);
130 if(unlikely(!host->rrdpush_buffer || !host->rrdpush_connected)) {
131 if(unlikely(!host->rrdpush_error_shown))
132 error("STREAM [send]: not ready - discarding collected metrics.");
134 host->rrdpush_error_shown = 1;
136 rrdpush_unlock(host);
139 else if(unlikely(host->rrdpush_error_shown)) {
140 error("STREAM [send]: ready - sending metrics...");
141 host->rrdpush_error_shown = 0;
144 if(need_to_send_chart_definition(st))
145 send_chart_definition(st);
147 send_chart_metrics(st);
149 // signal the sender there are more data
150 if(write(host->rrdpush_pipe[PIPE_WRITE], " ", 1) == -1)
151 error("STREAM [send]: cannot write to internal pipe");
153 rrdpush_unlock(host);
156 // ----------------------------------------------------------------------------
157 // rrdpush sender thread
159 // resets all the chart, so that their definitions
160 // will be resent to the central netdata
161 static void rrdpush_sender_thread_reset_all_charts(RRDHOST *host) {
162 rrdhost_rdlock(host);
165 rrdset_foreach_read(st, host) {
167 // make it re-align the current time
168 // on the remote host
169 st->counter_done = 0;
174 rrddim_foreach_read(rd, st)
175 rrddim_flag_clear(rd, RRDDIM_FLAG_EXPOSED);
180 rrdhost_unlock(host);
183 static inline void rrdpush_sender_thread_data_flush(RRDHOST *host) {
185 if(buffer_strlen(host->rrdpush_buffer))
186 error("STREAM [send]: discarding %zu bytes of metrics already in the buffer.", buffer_strlen(host->rrdpush_buffer));
188 buffer_flush(host->rrdpush_buffer);
189 rrdpush_sender_thread_reset_all_charts(host);
190 rrdpush_unlock(host);
193 static inline void rrdpush_sender_thread_lock(RRDHOST *host) {
194 if(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0)
195 error("STREAM [send]: cannot set pthread cancel state to DISABLE.");
200 static inline void rrdpush_sender_thread_unlock(RRDHOST *host) {
201 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
202 error("STREAM [send]: cannot set pthread cancel state to DISABLE.");
204 rrdpush_unlock(host);
207 void rrdpush_sender_thread_cleanup(RRDHOST *host) {
210 host->rrdpush_connected = 0;
212 if(host->rrdpush_socket != -1) close(host->rrdpush_socket);
215 if(host->rrdpush_pipe[PIPE_READ] != -1) close(host->rrdpush_pipe[PIPE_READ]);
216 if(host->rrdpush_pipe[PIPE_WRITE] != -1) close(host->rrdpush_pipe[PIPE_WRITE]);
217 host->rrdpush_pipe[PIPE_READ] = -1;
218 host->rrdpush_pipe[PIPE_WRITE] = -1;
220 buffer_free(host->rrdpush_buffer);
221 host->rrdpush_buffer = NULL;
223 host->rrdpush_spawn = 0;
224 host->rrdpush_enabled = 0;
226 rrdpush_unlock(host);
229 void *rrdpush_sender_thread(void *ptr) {
230 RRDHOST *host = (RRDHOST *)ptr;
232 info("STREAM [send]: thread created (task id %d)", gettid());
234 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
235 error("STREAM [send]: cannot set pthread cancel type to DEFERRED.");
237 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
238 error("STREAM [send]: cannot set pthread cancel state to ENABLE.");
240 int timeout = (int)config_get_number(CONFIG_SECTION_STREAM, "timeout seconds", 60);
241 int default_port = (int)config_get_number(CONFIG_SECTION_STREAM, "default port", 19999);
242 size_t max_size = (size_t)config_get_number(CONFIG_SECTION_STREAM, "buffer size bytes", 1024 * 1024);
243 unsigned int reconnect_delay = (unsigned int)config_get_number(CONFIG_SECTION_STREAM, "reconnect delay seconds", 5);
244 remote_clock_resync_iterations = (unsigned int)config_get_number(CONFIG_SECTION_STREAM, "initial clock resync iterations", remote_clock_resync_iterations);
245 char connected_to[CONNECTED_TO_SIZE + 1] = "";
247 if(!host->rrdpush_enabled || !rrdpush_destination || !*rrdpush_destination || !rrdpush_api_key || !*rrdpush_api_key)
250 // initialize rrdpush globals
251 host->rrdpush_buffer = buffer_create(1);
252 host->rrdpush_connected = 0;
253 if(pipe(host->rrdpush_pipe) == -1) fatal("STREAM [send]: cannot create required pipe.");
255 // initialize local variables
257 size_t reconnects_counter = 0;
258 size_t sent_bytes = 0;
259 size_t sent_connection = 0;
261 struct timeval tv = {
266 struct pollfd fds[2], *ifd, *ofd;
272 for(; host->rrdpush_enabled && !netdata_exit ;) {
274 if(unlikely(host->rrdpush_socket == -1)) {
275 // stop appending data into rrdpush_buffer
276 // they will be lost, so there is no point to do it
277 host->rrdpush_connected = 0;
279 info("STREAM [send to %s]: connecting...", rrdpush_destination);
280 host->rrdpush_socket = connect_to_one_of(rrdpush_destination, default_port, &tv, &reconnects_counter, connected_to, CONNECTED_TO_SIZE);
282 if(unlikely(host->rrdpush_socket == -1)) {
283 error("STREAM [send to %s]: failed to connect", rrdpush_destination);
284 sleep(reconnect_delay);
288 info("STREAM [send to %s]: initializing communication...", connected_to);
291 snprintfz(http, 1000,
292 "STREAM key=%s&hostname=%s&machine_guid=%s&os=%s&update_every=%d HTTP/1.1\r\n"
293 "User-Agent: netdata-push-service/%s\r\n"
294 "Accept: */*\r\n\r\n"
296 , localhost->hostname
297 , localhost->machine_guid
299 , default_rrd_update_every
303 if(send_timeout(host->rrdpush_socket, http, strlen(http), 0, timeout) == -1) {
304 close(host->rrdpush_socket);
305 host->rrdpush_socket = -1;
306 error("STREAM [send to %s]: failed to send http header to netdata", connected_to);
307 sleep(reconnect_delay);
311 info("STREAM [send to %s]: waiting response from remote netdata...", connected_to);
313 if(recv_timeout(host->rrdpush_socket, http, 1000, 0, timeout) == -1) {
314 close(host->rrdpush_socket);
315 host->rrdpush_socket = -1;
316 error("STREAM [send to %s]: failed to initialize communication", connected_to);
317 sleep(reconnect_delay);
321 if(strncmp(http, "STREAM", 6)) {
322 close(host->rrdpush_socket);
323 host->rrdpush_socket = -1;
324 error("STREAM [send to %s]: server is not replying properly.", connected_to);
325 sleep(reconnect_delay);
329 info("STREAM [send to %s]: established communication - sending metrics...", connected_to);
331 if(fcntl(host->rrdpush_socket, F_SETFL, O_NONBLOCK) < 0)
332 error("STREAM [send to %s]: cannot set non-blocking mode for socket.", connected_to);
334 rrdpush_sender_thread_data_flush(host);
337 // allow appending data into rrdpush_buffer
338 host->rrdpush_connected = 1;
341 ifd->fd = host->rrdpush_pipe[PIPE_READ];
342 ifd->events = POLLIN;
345 ofd->fd = host->rrdpush_socket;
347 if(begin < buffer_strlen(host->rrdpush_buffer)) {
348 ofd->events = POLLOUT;
356 if(netdata_exit) break;
357 int retval = poll(fds, fdmax, timeout * 1000);
358 if(netdata_exit) break;
360 if(unlikely(retval == -1)) {
361 if(errno == EAGAIN || errno == EINTR)
364 error("STREAM [send to %s]: failed to poll().", connected_to);
365 close(host->rrdpush_socket);
366 host->rrdpush_socket = -1;
369 else if(unlikely(!retval)) {
374 if(ifd->revents & POLLIN) {
375 char buffer[1000 + 1];
376 if(read(host->rrdpush_pipe[PIPE_READ], buffer, 1000) == -1)
377 error("STREAM [send to %s]: cannot read from internal pipe.", connected_to);
380 if(ofd->revents & POLLOUT && begin < buffer_strlen(host->rrdpush_buffer)) {
381 rrdpush_sender_thread_lock(host);
382 ssize_t ret = send(host->rrdpush_socket, &host->rrdpush_buffer->buffer[begin], buffer_strlen(host->rrdpush_buffer) - begin, MSG_DONTWAIT);
384 if(errno != EAGAIN && errno != EINTR) {
385 error("STREAM [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", connected_to, sent_connection);
386 close(host->rrdpush_socket);
387 host->rrdpush_socket = -1;
391 sent_connection += ret;
394 if(begin == buffer_strlen(host->rrdpush_buffer)) {
395 buffer_flush(host->rrdpush_buffer);
399 rrdpush_sender_thread_unlock(host);
402 // protection from overflow
403 if(host->rrdpush_buffer->len > max_size) {
405 error("STREAM [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.", connected_to, host->rrdpush_buffer->len, host->rrdpush_buffer->len - begin, sent_bytes, sent_connection);
406 if(host->rrdpush_socket != -1) {
407 close(host->rrdpush_socket);
408 host->rrdpush_socket = -1;
414 debug(D_WEB_CLIENT, "STREAM [send]: sending thread exits.");
416 rrdpush_sender_thread_cleanup(host);
423 // ----------------------------------------------------------------------------
424 // rrdpush receiver thread
426 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) {
428 int history = default_rrd_history_entries;
429 RRD_MEMORY_MODE mode = default_rrd_memory_mode;
430 int health_enabled = default_health_enabled;
431 time_t alarms_delay = 60;
433 update_every = (int)appconfig_get_number(&stream_config, machine_guid, "update every", update_every);
434 if(update_every < 0) update_every = 1;
436 history = (int)appconfig_get_number(&stream_config, key, "default history", history);
437 history = (int)appconfig_get_number(&stream_config, machine_guid, "history", history);
438 if(history < 5) history = 5;
440 mode = rrd_memory_mode_id(appconfig_get(&stream_config, key, "default memory mode", rrd_memory_mode_name(mode)));
441 mode = rrd_memory_mode_id(appconfig_get(&stream_config, machine_guid, "memory mode", rrd_memory_mode_name(mode)));
443 health_enabled = appconfig_get_boolean_ondemand(&stream_config, key, "health enabled by default", health_enabled);
444 health_enabled = appconfig_get_boolean_ondemand(&stream_config, machine_guid, "health enabled", health_enabled);
446 alarms_delay = appconfig_get_number(&stream_config, key, "default postpone alarms on connect seconds", alarms_delay);
447 alarms_delay = appconfig_get_number(&stream_config, machine_guid, "postpone alarms on connect seconds", alarms_delay);
449 if(!strcmp(machine_guid, "localhost"))
452 host = rrdhost_find_or_create(hostname, machine_guid, os, update_every, history, mode, health_enabled?1:0);
454 info("STREAM [receive from [%s]:%s]: metrics for host '%s' with machine_guid '%s': update every = %d, history = %d, memory mode = %s, health %s",
455 client_ip, client_port,
456 hostname, machine_guid,
459 rrd_memory_mode_name(mode),
460 (health_enabled == CONFIG_BOOLEAN_NO)?"disabled":((health_enabled == CONFIG_BOOLEAN_YES)?"enabled":"auto")
463 struct plugind cd = {
465 .update_every = default_rrd_update_every,
467 .serial_failures = 0,
468 .successful_collections = 0,
470 .started_t = now_realtime_sec(),
474 // put the client IP and port into the buffers used by plugins.d
475 snprintfz(cd.id, CONFIG_MAX_NAME, "%s:%s", client_ip, client_port);
476 snprintfz(cd.filename, FILENAME_MAX, "%s:%s", client_ip, client_port);
477 snprintfz(cd.fullfilename, FILENAME_MAX, "%s:%s", client_ip, client_port);
478 snprintfz(cd.cmd, PLUGINSD_CMD_MAX, "%s:%s", client_ip, client_port);
480 info("STREAM [receive from [%s]:%s]: initializing communication...", client_ip, client_port);
481 if(send_timeout(fd, "STREAM", 6, 0, 60) != 6) {
482 error("STREAM [receive from [%s]:%s]: cannot send STREAM command.", client_ip, client_port);
486 // remove the non-blocking flag from the socket
487 if(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK) == -1)
488 error("STREAM [receive from [%s]:%s]: cannot remove the non-blocking flag from socket %d", client_ip, client_port, fd);
490 // convert the socket to a FILE *
491 FILE *fp = fdopen(fd, "r");
493 error("STREAM [receive from [%s]:%s]: failed to get a FILE for FD %d.", client_ip, client_port, fd);
497 rrdhost_wrlock(host);
499 if(health_enabled != CONFIG_BOOLEAN_NO)
500 host->health_delay_up_to = now_realtime_sec() + alarms_delay;
501 rrdhost_unlock(host);
503 // call the plugins.d processor to receive the metrics
504 info("STREAM [receive from [%s]:%s]: receiving metrics... (host '%s', machine GUID '%s').", client_ip, client_port, host->hostname, host->machine_guid);
505 size_t count = pluginsd_process(host, &cd, fp, 1);
506 error("STREAM [receive from [%s]:%s]: disconnected (host '%s', machine GUID '%s', completed updates %zu).", client_ip, client_port, host->hostname, host->machine_guid, count);
508 rrdhost_wrlock(host);
510 if(!host->use_counter && health_enabled == CONFIG_BOOLEAN_AUTO)
511 host->health_enabled = 0;
512 rrdhost_unlock(host);
520 struct rrdpush_thread {
531 void *rrdpush_receiver_thread(void *ptr) {
532 struct rrdpush_thread *rpt = (struct rrdpush_thread *)ptr;
534 if (pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
535 error("STREAM [receive]: cannot set pthread cancel type to DEFERRED.");
537 if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
538 error("STREAM [receive]: cannot set pthread cancel state to ENABLE.");
541 info("STREAM [%s]:%s: receive thread created (task id %d)", rpt->client_ip, rpt->client_port, gettid());
542 rrdpush_receive(rpt->fd, rpt->key, rpt->hostname, rpt->machine_guid, rpt->os, rpt->update_every, rpt->client_ip, rpt->client_port);
543 info("STREAM [receive from [%s]:%s]: receive thread ended (task id %d)", rpt->client_ip, rpt->client_port, gettid());
547 freez(rpt->hostname);
548 freez(rpt->machine_guid);
550 freez(rpt->client_ip);
551 freez(rpt->client_port);
558 static inline int rrdpush_receive_validate_api_key(const char *key) {
559 return appconfig_get_boolean(&stream_config, key, "enabled", 0);
562 void rrdpush_sender_thread_spawn(RRDHOST *host) {
563 if(pthread_create(&host->rrdpush_thread, NULL, rrdpush_sender_thread, (void *)host))
564 error("STREAM [send for host %s]: failed to create new thread for client.", host->hostname);
566 else if(pthread_detach(host->rrdpush_thread))
567 error("STREAM [send for host %s]: cannot request detach newly created thread.", host->hostname);
569 host->rrdpush_spawn = 1;
572 int rrdpush_receiver_thread_spawn(RRDHOST *host, struct web_client *w, char *url) {
575 info("STREAM [receive from [%s]:%s]: new client connection.", w->client_ip, w->client_port);
577 char *key = NULL, *hostname = NULL, *machine_guid = NULL, *os = NULL;
578 int update_every = default_rrd_update_every;
581 char *value = mystrsep(&url, "?&");
582 if(!value || !*value) continue;
584 char *name = mystrsep(&value, "=");
585 if(!name || !*name) continue;
586 if(!value || !*value) continue;
588 if(!strcmp(name, "key"))
590 else if(!strcmp(name, "hostname"))
592 else if(!strcmp(name, "machine_guid"))
593 machine_guid = value;
594 else if(!strcmp(name, "update_every"))
595 update_every = (int)strtoul(value, NULL, 0);
596 else if(!strcmp(name, "os"))
601 error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
602 buffer_flush(w->response.data);
603 buffer_sprintf(w->response.data, "You need an API key for this request.");
607 if(!hostname || !*hostname) {
608 error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
609 buffer_flush(w->response.data);
610 buffer_sprintf(w->response.data, "You need to send a hostname too.");
614 if(!machine_guid || !*machine_guid) {
615 error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
616 buffer_flush(w->response.data);
617 buffer_sprintf(w->response.data, "You need to send a machine GUID too.");
621 if(!rrdpush_receive_validate_api_key(key)) {
622 error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
623 buffer_flush(w->response.data);
624 buffer_sprintf(w->response.data, "Your API key is not permitted access.");
628 if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
629 error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
630 buffer_flush(w->response.data);
631 buffer_sprintf(w->response.data, "Your machine guide is not permitted access.");
635 struct rrdpush_thread *rpt = mallocz(sizeof(struct rrdpush_thread));
637 rpt->key = strdupz(key);
638 rpt->hostname = strdupz(hostname);
639 rpt->machine_guid = strdupz(machine_guid);
640 rpt->os = strdupz(os);
641 rpt->client_ip = strdupz(w->client_ip);
642 rpt->client_port = strdupz(w->client_port);
643 rpt->update_every = update_every;
646 debug(D_SYSTEM, "STREAM [receive from [%s]:%s]: starting receiving thread.", w->client_ip, w->client_port);
648 if(pthread_create(&thread, NULL, rrdpush_receiver_thread, (void *)rpt))
649 error("STREAM [receive from [%s]:%s]: failed to create new thread for client.", w->client_ip, w->client_port);
651 else if(pthread_detach(thread))
652 error("STREAM [receive from [%s]:%s]: cannot request detach newly created thread.", w->client_ip, w->client_port);
654 // prevent the caller from closing the streaming socket
656 w->ifd = w->ofd = -1;
660 buffer_flush(w->response.data);