3 #define BACKEND_SOURCE_DATA_AS_COLLECTED 0x00000001
4 #define BACKEND_SOURCE_DATA_AVERAGE 0x00000002
5 #define BACKEND_SOURCE_DATA_SUM 0x00000004
7 static inline calculated_number backend_calculate_value_from_stored_data(RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
8 time_t first_t = rrdset_first_entry_t(st);
9 time_t last_t = rrdset_last_entry_t(st);
11 if(unlikely(before < first_t || after > last_t))
12 // the chart has not been updated in the wanted timeframe
15 // align the time-frame
16 // for 'after' also skip the first value by adding st->update_every
17 after = after - after % st->update_every + st->update_every;
18 before = before - before % st->update_every;
20 if(unlikely(after < first_t))
23 if(unlikely(after > before))
24 // this can happen when the st->update_every > before - after
27 if(unlikely(before > last_t))
31 calculated_number sum = 0;
33 long start_at_slot = rrdset_time2slot(st, before),
34 stop_at_slot = rrdset_time2slot(st, after),
37 for(slot = start_at_slot; !stop_now ; slot--) {
38 if(unlikely(slot < 0)) slot = st->entries - 1;
39 if(unlikely(slot == stop_at_slot)) stop_now = 1;
41 storage_number n = rd->values[slot];
42 if(unlikely(!does_storage_number_exist(n))) continue;
44 calculated_number value = unpack_storage_number(n);
49 if(unlikely(!counter))
52 if(unlikely(options & BACKEND_SOURCE_DATA_SUM))
55 return sum / (calculated_number)counter;
58 static inline int format_dimension_collected_graphite_plaintext(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
63 buffer_sprintf(b, "%s.%s.%s.%s " COLLECTED_NUMBER_FORMAT " %u\n", prefix, hostname, st->id, rd->id, rd->last_collected_value, (uint32_t)rd->last_collected_time.tv_sec);
67 static inline int format_dimension_stored_graphite_plaintext(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
69 calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
71 buffer_sprintf(b, "%s.%s.%s.%s " CALCULATED_NUMBER_FORMAT " %u\n", prefix, hostname, st->id, rd->id, value, (uint32_t) before);
77 static inline int format_dimension_collected_opentsdb_telnet(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
82 buffer_sprintf(b, "put %s.%s.%s %u " COLLECTED_NUMBER_FORMAT " host=%s\n", prefix, st->id, rd->id, (uint32_t)rd->last_collected_time.tv_sec, rd->last_collected_value, hostname);
86 static inline int format_dimension_stored_opentsdb_telnet(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
88 calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
90 buffer_sprintf(b, "put %s.%s.%s %u " CALCULATED_NUMBER_FORMAT " host=%s\n", prefix, st->id, rd->id, (uint32_t) before, value, hostname);
96 static inline int format_dimension_collected_json_plaintext(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
101 buffer_sprintf(b, "{"
103 "\"hostname\":\"%s\","
105 "\"chart_id\":\"%s\","
106 "\"chart_name\":\"%s\","
108 "\"context\": \"%s\","
114 "\"value\":" COLLECTED_NUMBER_FORMAT ","
116 "\"timestamp\": %u}\n",
129 rd->last_collected_value,
131 (uint32_t)rd->last_collected_time.tv_sec
137 static inline int format_dimension_stored_json_plaintext(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) {
139 calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
141 buffer_sprintf(b, "{"
143 "\"hostname\":\"%s\","
145 "\"chart_id\":\"%s\","
146 "\"chart_name\":\"%s\","
148 "\"context\": \"%s\","
154 "\"value\":" CALCULATED_NUMBER_FORMAT ","
156 "\"timestamp\": %u}\n",
179 static inline int process_graphite_response(BUFFER *b) {
181 const char *s = buffer_tostring(b);
182 char *d = sample, *e = &sample[sizeof(sample) - 1];
184 for(; *s && d < e ;s++) {
186 if(unlikely(!isprint(c))) c = ' ';
191 info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
196 static inline int process_json_response(BUFFER *b) {
198 const char *s = buffer_tostring(b);
199 char *d = sample, *e = &sample[sizeof(sample) - 1];
201 for(; *s && d < e ;s++) {
203 if(unlikely(!isprint(c))) c = ' ';
208 info("Received %zu bytes from json backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
213 static inline int process_opentsdb_response(BUFFER *b) {
215 const char *s = buffer_tostring(b);
216 char *d = sample, *e = &sample[sizeof(sample) - 1];
218 for(; *s && d < e ;s++) {
220 if(unlikely(!isprint(c))) c = ' ';
225 info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
230 void *backends_main(void *ptr) {
231 struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
233 BUFFER *b = buffer_create(1), *response = buffer_create(1);
234 int (*backend_request_formatter)(BUFFER *b, const char *prefix, RRDHOST *host, const char *hostname, RRDSET *st, RRDDIM *rd, time_t after, time_t before, uint32_t options) = NULL;
235 int (*backend_response_checker)(BUFFER *b) = NULL;
237 info("BACKEND thread created with task id %d", gettid());
239 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
240 error("Cannot set pthread cancel type to DEFERRED.");
242 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
243 error("Cannot set pthread cancel state to ENABLE.");
245 // ------------------------------------------------------------------------
246 // collect configuration options
248 struct timeval timeout = {
252 int default_port = 0;
255 int enabled = config_get_boolean("backend", "enabled", 0);
256 const char *source = config_get("backend", "data source", "average");
257 const char *type = config_get("backend", "type", "graphite");
258 const char *destination = config_get("backend", "destination", "localhost");
259 const char *prefix = config_get("backend", "prefix", "netdata");
260 const char *hostname = config_get("backend", "hostname", localhost.hostname);
261 int frequency = (int)config_get_number("backend", "update every", 10);
262 int buffer_on_failures = (int)config_get_number("backend", "buffer on failures", 10);
263 long timeoutms = config_get_number("backend", "timeout ms", frequency * 2 * 1000);
265 // ------------------------------------------------------------------------
266 // validate configuration options
267 // and prepare for sending data to our backend
268 if(!enabled || frequency < 1)
271 if(!strcmp(source, "as collected")) {
272 options = BACKEND_SOURCE_DATA_AS_COLLECTED;
274 else if(!strcmp(source, "average")) {
275 options = BACKEND_SOURCE_DATA_AVERAGE;
277 else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
278 options = BACKEND_SOURCE_DATA_SUM;
281 error("Invalid data source method '%s' for backend given. Disabling backed.", source);
285 if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
287 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
288 backend_request_formatter = format_dimension_collected_graphite_plaintext;
290 backend_request_formatter = format_dimension_stored_graphite_plaintext;
292 backend_response_checker = process_graphite_response;
294 else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
296 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
297 backend_request_formatter = format_dimension_collected_opentsdb_telnet;
299 backend_request_formatter = format_dimension_stored_opentsdb_telnet;
301 backend_response_checker = process_opentsdb_response;
303 else if (!strcmp(type, "json") || !strcmp(type, "json:plaintext"))
307 if (options == BACKEND_SOURCE_DATA_AS_COLLECTED)
309 backend_request_formatter = format_dimension_collected_json_plaintext;
313 backend_request_formatter = format_dimension_stored_json_plaintext;
316 backend_response_checker = process_json_response;
319 error("Unknown backend type '%s'", type);
323 if(backend_request_formatter == NULL || backend_response_checker == NULL) {
324 error("backend is misconfigured - disabling it.");
329 error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
330 timeoutms = frequency * 2 * 1000;
332 timeout.tv_sec = (timeoutms * 1000) / 1000000;
333 timeout.tv_usec = (timeoutms * 1000) % 1000000;
335 // ------------------------------------------------------------------------
336 // prepare the charts for monitoring the backend
338 struct rusage thread;
341 chart_buffered_metrics = 0,
342 chart_lost_metrics = 0,
343 chart_sent_metrics = 0,
344 chart_buffered_bytes = 0,
345 chart_received_bytes = 0,
346 chart_sent_bytes = 0,
347 chart_receptions = 0,
348 chart_transmission_successes = 0,
349 chart_transmission_failures = 0,
350 chart_data_lost_events = 0,
351 chart_lost_bytes = 0,
352 chart_backend_reconnects = 0,
353 chart_backend_latency = 0;
355 RRDSET *chart_metrics = rrdset_find("netdata.backend_metrics");
357 chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
358 rrddim_add(chart_metrics, "buffered", NULL, 1, 1, RRDDIM_ABSOLUTE);
359 rrddim_add(chart_metrics, "lost", NULL, 1, 1, RRDDIM_ABSOLUTE);
360 rrddim_add(chart_metrics, "sent", NULL, 1, 1, RRDDIM_ABSOLUTE);
363 RRDSET *chart_bytes = rrdset_find("netdata.backend_bytes");
365 chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
366 rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRDDIM_ABSOLUTE);
367 rrddim_add(chart_bytes, "lost", NULL, 1, 1024, RRDDIM_ABSOLUTE);
368 rrddim_add(chart_bytes, "sent", NULL, 1, 1024, RRDDIM_ABSOLUTE);
369 rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRDDIM_ABSOLUTE);
372 RRDSET *chart_ops = rrdset_find("netdata.backend_ops");
374 chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
375 rrddim_add(chart_ops, "write", NULL, 1, 1, RRDDIM_ABSOLUTE);
376 rrddim_add(chart_ops, "discard", NULL, 1, 1, RRDDIM_ABSOLUTE);
377 rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRDDIM_ABSOLUTE);
378 rrddim_add(chart_ops, "failure", NULL, 1, 1, RRDDIM_ABSOLUTE);
379 rrddim_add(chart_ops, "read", NULL, 1, 1, RRDDIM_ABSOLUTE);
383 * this is misleading - we can only measure the time we need to send data
384 * this time is not related to the time required for the data to travel to
385 * the backend database and the time that server needed to process them
387 * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
389 RRDSET *chart_latency = rrdset_find("netdata.backend_latency");
391 chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
392 rrddim_add(chart_latency, "latency", NULL, 1, 1000, RRDDIM_ABSOLUTE);
396 RRDSET *chart_rusage = rrdset_find("netdata.backend_thread_cpu");
398 chart_rusage = rrdset_create("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
399 rrddim_add(chart_rusage, "user", NULL, 1, 1000, RRDDIM_INCREMENTAL);
400 rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRDDIM_INCREMENTAL);
403 // ------------------------------------------------------------------------
404 // prepare the backend main loop
406 info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
408 usec_t step_ut = frequency * USEC_PER_SEC;
409 time_t after = now_realtime_sec();
415 // ------------------------------------------------------------------------
416 // Wait for the next iteration point.
417 heartbeat_next(&hb, step_ut);
418 time_t before = now_realtime_sec();
420 // ------------------------------------------------------------------------
421 // add to the buffer the data we need to send to the backend
423 int pthreadoldcancelstate;
425 if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
426 error("Cannot set pthread cancel state to DISABLE.");
428 rrdhost_rdlock(&localhost);
429 for(st = localhost.rrdset_root; st ;st = st->next) {
430 pthread_rwlock_rdlock(&st->rwlock);
433 for(rd = st->dimensions; rd ;rd = rd->next) {
434 if(rd->last_collected_time.tv_sec >= after)
435 chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
438 pthread_rwlock_unlock(&st->rwlock);
440 rrdhost_unlock(&localhost);
442 if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
443 error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
445 // ------------------------------------------------------------------------
447 chart_buffered_bytes = (collected_number)buffer_strlen(b);
449 // reset the monitoring chart counters
450 chart_received_bytes =
454 chart_transmission_successes =
455 chart_transmission_failures =
456 chart_data_lost_events =
458 chart_backend_reconnects =
459 chart_backend_latency = 0;
461 if(unlikely(netdata_exit)) break;
463 //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
464 //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
466 // prepare for the next iteration
467 // to add incrementally data to buffer
470 // ------------------------------------------------------------------------
471 // if we are connected, receive a response, without blocking
473 if(likely(sock != -1)) {
476 // loop through to collect all data
477 while(sock != -1 && errno != EWOULDBLOCK) {
478 buffer_need_bytes(response, 4096);
480 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
482 // we received some data
484 chart_received_bytes += r;
488 error("Backend '%s' closed the socket", destination);
493 // failed to receive data
494 if(errno != EAGAIN && errno != EWOULDBLOCK) {
495 error("Cannot receive data from backend '%s'.", destination);
500 // if we received data, process them
501 if(buffer_strlen(response))
502 backend_response_checker(response);
505 // ------------------------------------------------------------------------
506 // if we are not connected, connect to a backend server
508 if(unlikely(sock == -1)) {
509 usec_t start_ut = now_monotonic_usec();
510 const char *s = destination;
514 // skip separators, moving both s(tart) and e(nd)
515 while(isspace(*e) || *e == ',') s = ++e;
517 // move e(nd) to the first separator
518 while(*e && !isspace(*e) && *e != ',') e++;
520 // is there anything?
521 if(!*s || s == e) break;
524 strncpyz(buf, s, e - s);
525 chart_backend_reconnects++;
526 sock = connect_to(buf, default_port, &timeout);
527 if(sock != -1) break;
530 chart_backend_latency += now_monotonic_usec() - start_ut;
533 if(unlikely(netdata_exit)) break;
535 // ------------------------------------------------------------------------
536 // if we are connected, send our buffer to the backend server
538 if(likely(sock != -1)) {
539 size_t len = buffer_strlen(b);
540 usec_t start_ut = now_monotonic_usec();
543 flags += MSG_NOSIGNAL;
546 ssize_t written = send(sock, buffer_tostring(b), len, flags);
547 chart_backend_latency += now_monotonic_usec() - start_ut;
548 if(written != -1 && (size_t)written == len) {
549 // we sent the data successfully
550 chart_transmission_successes++;
551 chart_sent_bytes += written;
552 chart_sent_metrics = chart_buffered_metrics;
554 // reset the failures count
561 // oops! we couldn't send (all or some of the) data
562 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
563 chart_transmission_failures++;
566 chart_sent_bytes += written;
568 // increment the counter we check for data loss
571 // close the socket - we will re-open it next time
577 error("Failed to update database backend '%s'", destination);
578 chart_transmission_failures++;
580 // increment the counter we check for data loss
584 if(failures > buffer_on_failures) {
585 // too bad! we are going to lose data
586 chart_lost_bytes += buffer_strlen(b);
587 error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
590 chart_data_lost_events++;
591 chart_lost_metrics = chart_buffered_metrics;
594 if(unlikely(netdata_exit)) break;
596 // ------------------------------------------------------------------------
597 // update the monitoring charts
599 if(chart_ops->counter_done) rrdset_next(chart_ops);
600 rrddim_set(chart_ops, "read", chart_receptions);
601 rrddim_set(chart_ops, "write", chart_transmission_successes);
602 rrddim_set(chart_ops, "discard", chart_data_lost_events);
603 rrddim_set(chart_ops, "failure", chart_transmission_failures);
604 rrddim_set(chart_ops, "reconnect", chart_backend_reconnects);
605 rrdset_done(chart_ops);
607 if(chart_metrics->counter_done) rrdset_next(chart_metrics);
608 rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
609 rrddim_set(chart_metrics, "lost", chart_lost_metrics);
610 rrddim_set(chart_metrics, "sent", chart_sent_metrics);
611 rrdset_done(chart_metrics);
613 if(chart_bytes->counter_done) rrdset_next(chart_bytes);
614 rrddim_set(chart_bytes, "buffered", chart_buffered_bytes);
615 rrddim_set(chart_bytes, "lost", chart_lost_bytes);
616 rrddim_set(chart_bytes, "sent", chart_sent_bytes);
617 rrddim_set(chart_bytes, "received", chart_received_bytes);
618 rrdset_done(chart_bytes);
621 if(chart_latency->counter_done) rrdset_next(chart_latency);
622 rrddim_set(chart_latency, "latency", chart_backend_latency);
623 rrdset_done(chart_latency);
626 getrusage(RUSAGE_THREAD, &thread);
627 if(chart_rusage->counter_done) rrdset_next(chart_rusage);
628 rrddim_set(chart_rusage, "user", thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
629 rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
630 rrdset_done(chart_rusage);
632 if(likely(buffer_strlen(b) == 0))
633 chart_buffered_metrics = 0;
635 if(unlikely(netdata_exit)) break;
643 buffer_free(response);
645 info("BACKEND thread exiting");
647 static_thread->enabled = 0;