3 int default_rrdpush_enabled = 0;
4 int default_rrdpush_exclusive = 1;
6 static char *remote_netdata_config = NULL;
7 static char *api_key = NULL;
9 #define CONNECTED_TO_SIZE 100
11 // data collection happens from multiple threads
12 // each of these threads calls rrdset_done()
13 // which in turn calls rrdset_done_push()
14 // which uses this pipe to notify the streaming thread
15 // that there are more data ready to be sent
19 // to have the remote netdata re-sync the charts
20 // to its current clock, we send for this many
21 // iterations a BEGIN line without microseconds
22 // this is for the first iterations of each chart
23 static unsigned int remote_clock_resync_iterations = 60;
25 #define rrdpush_lock(host) pthread_mutex_lock(&((host)->rrdpush_mutex))
26 #define rrdpush_unlock(host) pthread_mutex_unlock(&((host)->rrdpush_mutex))
28 // checks if the current chart definition has been sent
29 static inline int need_to_send_chart_definition(RRDSET *st) {
31 rrddim_foreach_read(rd, st)
32 if(!rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
38 // sends the current chart definition
39 static inline void send_chart_definition(RRDSET *st) {
40 buffer_sprintf(st->rrdhost->rrdpush_buffer, "CHART '%s' '%s' '%s' '%s' '%s' '%s' '%s' %ld %d\n"
47 , rrdset_type_name(st->chart_type)
53 rrddim_foreach_read(rd, st) {
54 buffer_sprintf(st->rrdhost->rrdpush_buffer, "DIMENSION '%s' '%s' '%s' " COLLECTED_NUMBER_FORMAT " " COLLECTED_NUMBER_FORMAT " '%s %s'\n"
57 , rrd_algorithm_name(rd->algorithm)
60 , rrddim_flag_check(rd, RRDDIM_FLAG_HIDDEN)?"hidden":""
61 , rrddim_flag_check(rd, RRDDIM_FLAG_DONT_DETECT_RESETS_OR_OVERFLOWS)?"noreset":""
63 rrddim_flag_set(rd, RRDDIM_FLAG_EXPOSED);
67 // sends the current chart dimensions
68 static inline void send_chart_metrics(RRDSET *st) {
69 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);
72 rrddim_foreach_read(rd, st) {
73 if(rrddim_flag_check(rd, RRDDIM_FLAG_UPDATED) && rrddim_flag_check(rd, RRDDIM_FLAG_EXPOSED))
74 buffer_sprintf(st->rrdhost->rrdpush_buffer, "SET %s = " COLLECTED_NUMBER_FORMAT "\n"
80 buffer_strcat(st->rrdhost->rrdpush_buffer, "END\n");
83 // resets all the chart, so that their definitions
84 // will be resent to the central netdata
85 static void reset_all_charts(RRDHOST *host) {
89 rrdset_foreach_read(st, host) {
91 // make it re-align the current time
98 rrddim_foreach_read(rd, st)
99 rrddim_flag_clear(rd, RRDDIM_FLAG_EXPOSED);
104 rrdhost_unlock(host);
107 void rrdpush_sender_thread_spawn(RRDHOST *host);
109 void rrdset_done_push(RRDSET *st) {
110 RRDHOST *host = st->rrdhost;
112 if(unlikely(!rrdset_flag_check(st, RRDSET_FLAG_ENABLED)))
117 if(unlikely(host->rrdpush_enabled && !host->rrdpush_spawn))
118 rrdpush_sender_thread_spawn(host);
120 if(unlikely(!host->rrdpush_buffer || !host->rrdpush_connected)) {
121 if(unlikely(!host->rrdpush_error_shown))
122 error("STREAM [send]: not ready - discarding collected metrics.");
124 host->rrdpush_error_shown = 1;
126 rrdpush_unlock(host);
129 else if(unlikely(host->rrdpush_error_shown)) {
130 error("STREAM [send]: ready - sending metrics...");
131 host->rrdpush_error_shown = 0;
135 if(need_to_send_chart_definition(st))
136 send_chart_definition(st);
138 send_chart_metrics(st);
141 // signal the sender there are more data
142 if(write(host->rrdpush_pipe[PIPE_WRITE], " ", 1) == -1)
143 error("STREAM [send]: cannot write to internal pipe");
145 rrdpush_unlock(host);
148 static inline void rrdpush_flush(RRDHOST *host) {
150 if(buffer_strlen(host->rrdpush_buffer))
151 error("STREAM [send]: discarding %zu bytes of metrics already in the buffer.", buffer_strlen(host->rrdpush_buffer));
153 buffer_flush(host->rrdpush_buffer);
154 reset_all_charts(host);
155 rrdpush_unlock(host);
159 default_rrdpush_enabled = config_get_boolean("stream", "enabled", default_rrdpush_enabled);
160 default_rrdpush_exclusive = config_get_boolean("stream", "exclusive", default_rrdpush_exclusive);
161 remote_netdata_config = config_get("stream", "stream metrics to", "");
162 api_key = config_get("stream", "api key", "");
164 if(!default_rrdpush_enabled || !remote_netdata_config || !*remote_netdata_config || !api_key || !*api_key) {
165 default_rrdpush_enabled = 0;
166 default_rrdpush_exclusive = 0;
169 return default_rrdpush_enabled;
172 static inline void rrdpush_sender_lock(RRDHOST *host) {
173 if(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL) != 0)
174 error("STREAM [send]: cannot set pthread cancel state to DISABLE.");
179 static inline void rrdpush_sender_unlock(RRDHOST *host) {
180 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
181 error("STREAM [send]: cannot set pthread cancel state to DISABLE.");
183 rrdpush_unlock(host);
186 void rrdpush_sender_cleanup(RRDHOST *host) {
189 host->rrdpush_connected = 0;
191 if(host->rrdpush_socket != -1) close(host->rrdpush_socket);
194 if(host->rrdpush_pipe[PIPE_READ] != -1) close(host->rrdpush_pipe[PIPE_READ]);
195 if(host->rrdpush_pipe[PIPE_WRITE] != -1) close(host->rrdpush_pipe[PIPE_WRITE]);
196 host->rrdpush_pipe[PIPE_READ] = -1;
197 host->rrdpush_pipe[PIPE_WRITE] = -1;
199 buffer_free(host->rrdpush_buffer);
200 host->rrdpush_buffer = NULL;
202 host->rrdpush_spawn = 0;
203 host->rrdpush_enabled = 0;
205 rrdpush_unlock(host);
208 void *rrdpush_sender_thread(void *ptr) {
209 RRDHOST *host = (RRDHOST *)ptr;
211 info("STREAM [send]: thread created (task id %d)", gettid());
213 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
214 error("STREAM [send]: cannot set pthread cancel type to DEFERRED.");
216 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
217 error("STREAM [send]: cannot set pthread cancel state to ENABLE.");
219 int timeout = (int)config_get_number("stream", "timeout seconds", 60);
220 int default_port = (int)config_get_number("stream", "default port", 19999);
221 size_t max_size = (size_t)config_get_number("stream", "buffer size bytes", 1024 * 1024);
222 unsigned int reconnect_delay = (unsigned int)config_get_number("stream", "reconnect delay seconds", 5);
223 remote_clock_resync_iterations = (unsigned int)config_get_number("stream", "initial clock resync iterations", remote_clock_resync_iterations);
224 char connected_to[CONNECTED_TO_SIZE + 1] = "";
226 if(!host->rrdpush_enabled || !remote_netdata_config || !*remote_netdata_config || !api_key || !*api_key)
229 // initialize rrdpush globals
230 host->rrdpush_buffer = buffer_create(1);
231 host->rrdpush_connected = 0;
232 if(pipe(host->rrdpush_pipe) == -1) fatal("STREAM [send]: cannot create required pipe.");
234 // initialize local variables
236 size_t reconnects_counter = 0;
237 size_t sent_bytes = 0;
238 size_t sent_connection = 0;
240 struct timeval tv = {
245 struct pollfd fds[2], *ifd, *ofd;
251 for(; host->rrdpush_enabled && !netdata_exit ;) {
253 if(unlikely(host->rrdpush_socket == -1)) {
254 // stop appending data into rrdpush_buffer
255 // they will be lost, so there is no point to do it
256 host->rrdpush_connected = 0;
258 info("STREAM [send to %s]: connecting...", remote_netdata_config);
259 host->rrdpush_socket = connect_to_one_of(remote_netdata_config, default_port, &tv, &reconnects_counter, connected_to, CONNECTED_TO_SIZE);
261 if(unlikely(host->rrdpush_socket == -1)) {
262 error("STREAM [send to %s]: failed to connect", remote_netdata_config);
263 sleep(reconnect_delay);
267 info("STREAM [send to %s]: initializing communication...", connected_to);
270 snprintfz(http, 1000,
271 "STREAM key=%s&hostname=%s&machine_guid=%s&os=%s&update_every=%d HTTP/1.1\r\n"
272 "User-Agent: netdata-push-service/%s\r\n"
273 "Accept: */*\r\n\r\n"
275 , localhost->hostname
276 , localhost->machine_guid
278 , default_rrd_update_every
282 if(send_timeout(host->rrdpush_socket, http, strlen(http), 0, timeout) == -1) {
283 close(host->rrdpush_socket);
284 host->rrdpush_socket = -1;
285 error("STREAM [send to %s]: failed to send http header to netdata", connected_to);
286 sleep(reconnect_delay);
290 info("STREAM [send to %s]: waiting response from remote netdata...", connected_to);
292 if(recv_timeout(host->rrdpush_socket, http, 1000, 0, timeout) == -1) {
293 close(host->rrdpush_socket);
294 host->rrdpush_socket = -1;
295 error("STREAM [send to %s]: failed to initialize communication", connected_to);
296 sleep(reconnect_delay);
300 if(strncmp(http, "STREAM", 6)) {
301 close(host->rrdpush_socket);
302 host->rrdpush_socket = -1;
303 error("STREAM [send to %s]: server is not replying properly.", connected_to);
304 sleep(reconnect_delay);
308 info("STREAM [send to %s]: established communication - sending metrics...", connected_to);
310 if(fcntl(host->rrdpush_socket, F_SETFL, O_NONBLOCK) < 0)
311 error("STREAM [send to %s]: cannot set non-blocking mode for socket.", connected_to);
316 // allow appending data into rrdpush_buffer
317 host->rrdpush_connected = 1;
320 ifd->fd = host->rrdpush_pipe[PIPE_READ];
321 ifd->events = POLLIN;
324 ofd->fd = host->rrdpush_socket;
326 if(begin < buffer_strlen(host->rrdpush_buffer)) {
327 ofd->events = POLLOUT;
335 if(netdata_exit) break;
336 int retval = poll(fds, fdmax, timeout * 1000);
337 if(netdata_exit) break;
339 if(unlikely(retval == -1)) {
340 if(errno == EAGAIN || errno == EINTR)
343 error("STREAM [send to %s]: failed to poll().", connected_to);
344 close(host->rrdpush_socket);
345 host->rrdpush_socket = -1;
348 else if(unlikely(!retval)) {
353 if(ifd->revents & POLLIN) {
354 char buffer[1000 + 1];
355 if(read(host->rrdpush_pipe[PIPE_READ], buffer, 1000) == -1)
356 error("STREAM [send to %s]: cannot read from internal pipe.", connected_to);
359 if(ofd->revents & POLLOUT && begin < buffer_strlen(host->rrdpush_buffer)) {
360 rrdpush_sender_lock(host);
361 ssize_t ret = send(host->rrdpush_socket, &host->rrdpush_buffer->buffer[begin], buffer_strlen(host->rrdpush_buffer) - begin, MSG_DONTWAIT);
363 if(errno != EAGAIN && errno != EINTR) {
364 error("STREAM [send to %s]: failed to send metrics - closing connection - we have sent %zu bytes on this connection.", connected_to, sent_connection);
365 close(host->rrdpush_socket);
366 host->rrdpush_socket = -1;
370 sent_connection += ret;
373 if(begin == buffer_strlen(host->rrdpush_buffer)) {
374 buffer_flush(host->rrdpush_buffer);
378 rrdpush_sender_unlock(host);
381 // protection from overflow
382 if(host->rrdpush_buffer->len > max_size) {
384 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);
385 if(host->rrdpush_socket != -1) {
386 close(host->rrdpush_socket);
387 host->rrdpush_socket = -1;
393 debug(D_WEB_CLIENT, "STREAM [send]: sending thread exits.");
395 rrdpush_sender_cleanup(host);
402 // ----------------------------------------------------------------------------
405 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) {
407 int history = default_rrd_history_entries;
408 RRD_MEMORY_MODE mode = default_rrd_memory_mode;
409 int health_enabled = default_health_enabled;
410 time_t alarms_delay = 60;
412 update_every = (int)appconfig_get_number(&stream_config, machine_guid, "update every", update_every);
413 if(update_every < 0) update_every = 1;
415 history = (int)appconfig_get_number(&stream_config, key, "default history", history);
416 history = (int)appconfig_get_number(&stream_config, machine_guid, "history", history);
417 if(history < 5) history = 5;
419 mode = rrd_memory_mode_id(appconfig_get(&stream_config, key, "default memory mode", rrd_memory_mode_name(mode)));
420 mode = rrd_memory_mode_id(appconfig_get(&stream_config, machine_guid, "memory mode", rrd_memory_mode_name(mode)));
422 health_enabled = appconfig_get_boolean_ondemand(&stream_config, key, "health enabled by default", health_enabled);
423 health_enabled = appconfig_get_boolean_ondemand(&stream_config, machine_guid, "health enabled", health_enabled);
425 alarms_delay = appconfig_get_number(&stream_config, key, "default postpone alarms on connect seconds", alarms_delay);
426 alarms_delay = appconfig_get_number(&stream_config, machine_guid, "postpone alarms on connect seconds", alarms_delay);
428 if(!strcmp(machine_guid, "localhost"))
431 host = rrdhost_find_or_create(hostname, machine_guid, os, update_every, history, mode, health_enabled?1:0);
433 info("STREAM [receive from [%s]:%s]: metrics for host '%s' with machine_guid '%s': update every = %d, history = %d, memory mode = %s, health %s",
434 client_ip, client_port,
435 hostname, machine_guid,
438 rrd_memory_mode_name(mode),
439 (health_enabled == CONFIG_BOOLEAN_NO)?"disabled":((health_enabled == CONFIG_BOOLEAN_YES)?"enabled":"auto")
442 struct plugind cd = {
444 .update_every = default_rrd_update_every,
446 .serial_failures = 0,
447 .successful_collections = 0,
449 .started_t = now_realtime_sec(),
453 // put the client IP and port into the buffers used by plugins.d
454 snprintfz(cd.id, CONFIG_MAX_NAME, "%s:%s", client_ip, client_port);
455 snprintfz(cd.filename, FILENAME_MAX, "%s:%s", client_ip, client_port);
456 snprintfz(cd.fullfilename, FILENAME_MAX, "%s:%s", client_ip, client_port);
457 snprintfz(cd.cmd, PLUGINSD_CMD_MAX, "%s:%s", client_ip, client_port);
459 info("STREAM [receive from [%s]:%s]: initializing communication...", client_ip, client_port);
460 if(send_timeout(fd, "STREAM", 6, 0, 60) != 6) {
461 error("STREAM [receive from [%s]:%s]: cannot send STREAM command.", client_ip, client_port);
465 // remove the non-blocking flag from the socket
466 if(fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) & ~O_NONBLOCK) == -1)
467 error("STREAM [receive from [%s]:%s]: cannot remove the non-blocking flag from socket %d", client_ip, client_port, fd);
469 // convert the socket to a FILE *
470 FILE *fp = fdopen(fd, "r");
472 error("STREAM [receive from [%s]:%s]: failed to get a FILE for FD %d.", client_ip, client_port, fd);
476 rrdhost_wrlock(host);
478 if(health_enabled != CONFIG_BOOLEAN_NO)
479 host->health_delay_up_to = now_realtime_sec() + alarms_delay;
480 rrdhost_unlock(host);
482 // call the plugins.d processor to receive the metrics
483 info("STREAM [receive from [%s]:%s]: receiving metrics... (host '%s', machine GUID '%s').", client_ip, client_port, host->hostname, host->machine_guid);
484 size_t count = pluginsd_process(host, &cd, fp, 1);
485 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);
487 rrdhost_wrlock(host);
489 if(!host->use_counter && health_enabled == CONFIG_BOOLEAN_AUTO)
490 host->health_enabled = 0;
491 rrdhost_unlock(host);
499 struct rrdpush_thread {
510 void *rrdpush_receiver_thread(void *ptr) {
511 struct rrdpush_thread *rpt = (struct rrdpush_thread *)ptr;
513 if (pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
514 error("STREAM [receive]: cannot set pthread cancel type to DEFERRED.");
516 if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
517 error("STREAM [receive]: cannot set pthread cancel state to ENABLE.");
520 info("STREAM [%s]:%s: receive thread created (task id %d)", rpt->client_ip, rpt->client_port, gettid());
521 rrdpush_receive(rpt->fd, rpt->key, rpt->hostname, rpt->machine_guid, rpt->os, rpt->update_every, rpt->client_ip, rpt->client_port);
522 info("STREAM [receive from [%s]:%s]: receive thread ended (task id %d)", rpt->client_ip, rpt->client_port, gettid());
526 freez(rpt->hostname);
527 freez(rpt->machine_guid);
529 freez(rpt->client_ip);
530 freez(rpt->client_port);
537 static inline int rrdpush_receive_validate_api_key(const char *key) {
538 return appconfig_get_boolean(&stream_config, key, "enabled", 0);
541 void rrdpush_sender_thread_spawn(RRDHOST *host) {
542 if(pthread_create(&host->rrdpush_thread, NULL, rrdpush_sender_thread, (void *)host))
543 error("STREAM [send for host %s]: failed to create new thread for client.", host->hostname);
545 else if(pthread_detach(host->rrdpush_thread))
546 error("STREAM [send for host %s]: cannot request detach newly created thread.", host->hostname);
548 host->rrdpush_spawn = 1;
551 int rrdpush_receiver_thread_spawn(RRDHOST *host, struct web_client *w, char *url) {
554 info("STREAM [receive from [%s]:%s]: new client connection.", w->client_ip, w->client_port);
556 char *key = NULL, *hostname = NULL, *machine_guid = NULL, *os = NULL;
557 int update_every = default_rrd_update_every;
560 char *value = mystrsep(&url, "?&");
561 if(!value || !*value) continue;
563 char *name = mystrsep(&value, "=");
564 if(!name || !*name) continue;
565 if(!value || !*value) continue;
567 if(!strcmp(name, "key"))
569 else if(!strcmp(name, "hostname"))
571 else if(!strcmp(name, "machine_guid"))
572 machine_guid = value;
573 else if(!strcmp(name, "update_every"))
574 update_every = (int)strtoul(value, NULL, 0);
575 else if(!strcmp(name, "os"))
580 error("STREAM [receive from [%s]:%s]: request without an API key. Forbidding access.", w->client_ip, w->client_port);
581 buffer_flush(w->response.data);
582 buffer_sprintf(w->response.data, "You need an API key for this request.");
586 if(!hostname || !*hostname) {
587 error("STREAM [receive from [%s]:%s]: request without a hostname. Forbidding access.", w->client_ip, w->client_port);
588 buffer_flush(w->response.data);
589 buffer_sprintf(w->response.data, "You need to send a hostname too.");
593 if(!machine_guid || !*machine_guid) {
594 error("STREAM [receive from [%s]:%s]: request without a machine GUID. Forbidding access.", w->client_ip, w->client_port);
595 buffer_flush(w->response.data);
596 buffer_sprintf(w->response.data, "You need to send a machine GUID too.");
600 if(!rrdpush_receive_validate_api_key(key)) {
601 error("STREAM [receive from [%s]:%s]: API key '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, key);
602 buffer_flush(w->response.data);
603 buffer_sprintf(w->response.data, "Your API key is not permitted access.");
607 if(!appconfig_get_boolean(&stream_config, machine_guid, "enabled", 1)) {
608 error("STREAM [receive from [%s]:%s]: machine GUID '%s' is not allowed. Forbidding access.", w->client_ip, w->client_port, machine_guid);
609 buffer_flush(w->response.data);
610 buffer_sprintf(w->response.data, "Your machine guide is not permitted access.");
614 struct rrdpush_thread *rpt = mallocz(sizeof(struct rrdpush_thread));
616 rpt->key = strdupz(key);
617 rpt->hostname = strdupz(hostname);
618 rpt->machine_guid = strdupz(machine_guid);
619 rpt->os = strdupz(os);
620 rpt->client_ip = strdupz(w->client_ip);
621 rpt->client_port = strdupz(w->client_port);
622 rpt->update_every = update_every;
625 debug(D_SYSTEM, "STREAM [receive from [%s]:%s]: starting receiving thread.", w->client_ip, w->client_port);
627 if(pthread_create(&thread, NULL, rrdpush_receiver_thread, (void *)rpt))
628 error("STREAM [receive from [%s]:%s]: failed to create new thread for client.", w->client_ip, w->client_port);
630 else if(pthread_detach(thread))
631 error("STREAM [receive from [%s]:%s]: cannot request detach newly created thread.", w->client_ip, w->client_port);
633 // prevent the caller from closing the streaming socket
635 w->ifd = w->ofd = -1;
639 buffer_flush(w->response.data);