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\","
107 "\"context\": \"%s\","
113 "\"value\":" COLLECTED_NUMBER_FORMAT ","
114 "\"timestamp\": %u}\n", prefix, hostname, st->type, st->family, st->context, st->units, st->title, st->id, rd->id, rd->last_collected_value, (uint32_t)rd->last_collected_time.tv_sec);
118 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) {
120 calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
122 buffer_sprintf(b, "{"
124 "\"hostname\":\"%s\","
128 "\"context\": \"%s\","
134 "\"value\":" CALCULATED_NUMBER_FORMAT ","
135 "\"timestamp\": %u}\n", prefix, hostname, st->type, st->family, st->context, st->units, st->title, st->id, rd->id, value, (uint32_t)before);
141 static inline int process_graphite_response(BUFFER *b) {
143 const char *s = buffer_tostring(b);
144 char *d = sample, *e = &sample[sizeof(sample) - 1];
146 for(; *s && d < e ;s++) {
148 if(unlikely(!isprint(c))) c = ' ';
153 info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
158 static inline int process_json_response(BUFFER *b) {
160 const char *s = buffer_tostring(b);
161 char *d = sample, *e = &sample[sizeof(sample) - 1];
163 for(; *s && d < e ;s++) {
165 if(unlikely(!isprint(c))) c = ' ';
170 info("Received %zu bytes from json backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
175 static inline int process_opentsdb_response(BUFFER *b) {
177 const char *s = buffer_tostring(b);
178 char *d = sample, *e = &sample[sizeof(sample) - 1];
180 for(; *s && d < e ;s++) {
182 if(unlikely(!isprint(c))) c = ' ';
187 info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
192 void *backends_main(void *ptr) {
193 struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
195 BUFFER *b = buffer_create(1), *response = buffer_create(1);
196 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;
197 int (*backend_response_checker)(BUFFER *b) = NULL;
199 info("BACKEND thread created with task id %d", gettid());
201 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
202 error("Cannot set pthread cancel type to DEFERRED.");
204 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
205 error("Cannot set pthread cancel state to ENABLE.");
207 // ------------------------------------------------------------------------
208 // collect configuration options
210 struct timeval timeout = {
214 int default_port = 0;
217 int enabled = config_get_boolean("backend", "enabled", 0);
218 const char *source = config_get("backend", "data source", "average");
219 const char *type = config_get("backend", "type", "graphite");
220 const char *destination = config_get("backend", "destination", "localhost");
221 const char *prefix = config_get("backend", "prefix", "netdata");
222 const char *hostname = config_get("backend", "hostname", localhost.hostname);
223 int frequency = (int)config_get_number("backend", "update every", 10);
224 int buffer_on_failures = (int)config_get_number("backend", "buffer on failures", 10);
225 long timeoutms = config_get_number("backend", "timeout ms", frequency * 2 * 1000);
227 // ------------------------------------------------------------------------
228 // validate configuration options
229 // and prepare for sending data to our backend
230 if(!enabled || frequency < 1)
233 if(!strcmp(source, "as collected")) {
234 options = BACKEND_SOURCE_DATA_AS_COLLECTED;
236 else if(!strcmp(source, "average")) {
237 options = BACKEND_SOURCE_DATA_AVERAGE;
239 else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
240 options = BACKEND_SOURCE_DATA_SUM;
243 error("Invalid data source method '%s' for backend given. Disabling backed.", source);
247 if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
249 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
250 backend_request_formatter = format_dimension_collected_graphite_plaintext;
252 backend_request_formatter = format_dimension_stored_graphite_plaintext;
254 backend_response_checker = process_graphite_response;
256 else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
258 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
259 backend_request_formatter = format_dimension_collected_opentsdb_telnet;
261 backend_request_formatter = format_dimension_stored_opentsdb_telnet;
263 backend_response_checker = process_opentsdb_response;
265 else if (!strcmp(type, "json") || !strcmp(type, "json:plaintext"))
269 if (options == BACKEND_SOURCE_DATA_AS_COLLECTED)
271 backend_request_formatter = format_dimension_collected_json_plaintext;
275 backend_request_formatter = format_dimension_stored_json_plaintext;
278 backend_response_checker = process_json_response;
281 error("Unknown backend type '%s'", type);
285 if(backend_request_formatter == NULL || backend_response_checker == NULL) {
286 error("backend is misconfigured - disabling it.");
291 error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
292 timeoutms = frequency * 2 * 1000;
294 timeout.tv_sec = (timeoutms * 1000) / 1000000;
295 timeout.tv_usec = (timeoutms * 1000) % 1000000;
297 // ------------------------------------------------------------------------
298 // prepare the charts for monitoring the backend
300 struct rusage thread;
303 chart_buffered_metrics = 0,
304 chart_lost_metrics = 0,
305 chart_sent_metrics = 0,
306 chart_buffered_bytes = 0,
307 chart_received_bytes = 0,
308 chart_sent_bytes = 0,
309 chart_receptions = 0,
310 chart_transmission_successes = 0,
311 chart_transmission_failures = 0,
312 chart_data_lost_events = 0,
313 chart_lost_bytes = 0,
314 chart_backend_reconnects = 0,
315 chart_backend_latency = 0;
317 RRDSET *chart_metrics = rrdset_find("netdata.backend_metrics");
319 chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
320 rrddim_add(chart_metrics, "buffered", NULL, 1, 1, RRDDIM_ABSOLUTE);
321 rrddim_add(chart_metrics, "lost", NULL, 1, 1, RRDDIM_ABSOLUTE);
322 rrddim_add(chart_metrics, "sent", NULL, 1, 1, RRDDIM_ABSOLUTE);
325 RRDSET *chart_bytes = rrdset_find("netdata.backend_bytes");
327 chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
328 rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRDDIM_ABSOLUTE);
329 rrddim_add(chart_bytes, "lost", NULL, 1, 1024, RRDDIM_ABSOLUTE);
330 rrddim_add(chart_bytes, "sent", NULL, 1, 1024, RRDDIM_ABSOLUTE);
331 rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRDDIM_ABSOLUTE);
334 RRDSET *chart_ops = rrdset_find("netdata.backend_ops");
336 chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
337 rrddim_add(chart_ops, "write", NULL, 1, 1, RRDDIM_ABSOLUTE);
338 rrddim_add(chart_ops, "discard", NULL, 1, 1, RRDDIM_ABSOLUTE);
339 rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRDDIM_ABSOLUTE);
340 rrddim_add(chart_ops, "failure", NULL, 1, 1, RRDDIM_ABSOLUTE);
341 rrddim_add(chart_ops, "read", NULL, 1, 1, RRDDIM_ABSOLUTE);
345 * this is misleading - we can only measure the time we need to send data
346 * this time is not related to the time required for the data to travel to
347 * the backend database and the time that server needed to process them
349 * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
351 RRDSET *chart_latency = rrdset_find("netdata.backend_latency");
353 chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
354 rrddim_add(chart_latency, "latency", NULL, 1, 1000, RRDDIM_ABSOLUTE);
358 RRDSET *chart_rusage = rrdset_find("netdata.backend_thread_cpu");
360 chart_rusage = rrdset_create("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
361 rrddim_add(chart_rusage, "user", NULL, 1, 1000, RRDDIM_INCREMENTAL);
362 rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRDDIM_INCREMENTAL);
365 // ------------------------------------------------------------------------
366 // prepare the backend main loop
368 info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
370 usec_t step_ut = frequency * USEC_PER_SEC;
371 time_t after = now_realtime_sec();
377 // ------------------------------------------------------------------------
378 // Wait for the next iteration point.
379 heartbeat_next(&hb, step_ut);
380 time_t before = now_realtime_sec();
382 // ------------------------------------------------------------------------
383 // add to the buffer the data we need to send to the backend
385 int pthreadoldcancelstate;
387 if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
388 error("Cannot set pthread cancel state to DISABLE.");
390 rrdhost_rdlock(&localhost);
391 for(st = localhost.rrdset_root; st ;st = st->next) {
392 pthread_rwlock_rdlock(&st->rwlock);
395 for(rd = st->dimensions; rd ;rd = rd->next) {
396 if(rd->last_collected_time.tv_sec >= after)
397 chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
400 pthread_rwlock_unlock(&st->rwlock);
402 rrdhost_unlock(&localhost);
404 if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
405 error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
407 // ------------------------------------------------------------------------
409 chart_buffered_bytes = (collected_number)buffer_strlen(b);
411 // reset the monitoring chart counters
412 chart_received_bytes =
416 chart_transmission_successes =
417 chart_transmission_failures =
418 chart_data_lost_events =
420 chart_backend_reconnects =
421 chart_backend_latency = 0;
423 if(unlikely(netdata_exit)) break;
425 //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
426 //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
428 // prepare for the next iteration
429 // to add incrementally data to buffer
432 // ------------------------------------------------------------------------
433 // if we are connected, receive a response, without blocking
435 if(likely(sock != -1)) {
438 // loop through to collect all data
439 while(sock != -1 && errno != EWOULDBLOCK) {
440 buffer_need_bytes(response, 4096);
442 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
444 // we received some data
446 chart_received_bytes += r;
450 error("Backend '%s' closed the socket", destination);
455 // failed to receive data
456 if(errno != EAGAIN && errno != EWOULDBLOCK) {
457 error("Cannot receive data from backend '%s'.", destination);
462 // if we received data, process them
463 if(buffer_strlen(response))
464 backend_response_checker(response);
467 // ------------------------------------------------------------------------
468 // if we are not connected, connect to a backend server
470 if(unlikely(sock == -1)) {
471 usec_t start_ut = now_monotonic_usec();
472 const char *s = destination;
476 // skip separators, moving both s(tart) and e(nd)
477 while(isspace(*e) || *e == ',') s = ++e;
479 // move e(nd) to the first separator
480 while(*e && !isspace(*e) && *e != ',') e++;
482 // is there anything?
483 if(!*s || s == e) break;
486 strncpyz(buf, s, e - s);
487 chart_backend_reconnects++;
488 sock = connect_to(buf, default_port, &timeout);
489 if(sock != -1) break;
492 chart_backend_latency += now_monotonic_usec() - start_ut;
495 if(unlikely(netdata_exit)) break;
497 // ------------------------------------------------------------------------
498 // if we are connected, send our buffer to the backend server
500 if(likely(sock != -1)) {
501 size_t len = buffer_strlen(b);
502 usec_t start_ut = now_monotonic_usec();
505 flags += MSG_NOSIGNAL;
508 ssize_t written = send(sock, buffer_tostring(b), len, flags);
509 chart_backend_latency += now_monotonic_usec() - start_ut;
510 if(written != -1 && (size_t)written == len) {
511 // we sent the data successfully
512 chart_transmission_successes++;
513 chart_sent_bytes += written;
514 chart_sent_metrics = chart_buffered_metrics;
516 // reset the failures count
523 // oops! we couldn't send (all or some of the) data
524 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
525 chart_transmission_failures++;
528 chart_sent_bytes += written;
530 // increment the counter we check for data loss
533 // close the socket - we will re-open it next time
539 error("Failed to update database backend '%s'", destination);
540 chart_transmission_failures++;
542 // increment the counter we check for data loss
546 if(failures > buffer_on_failures) {
547 // too bad! we are going to lose data
548 chart_lost_bytes += buffer_strlen(b);
549 error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
552 chart_data_lost_events++;
553 chart_lost_metrics = chart_buffered_metrics;
556 if(unlikely(netdata_exit)) break;
558 // ------------------------------------------------------------------------
559 // update the monitoring charts
561 if(chart_ops->counter_done) rrdset_next(chart_ops);
562 rrddim_set(chart_ops, "read", chart_receptions);
563 rrddim_set(chart_ops, "write", chart_transmission_successes);
564 rrddim_set(chart_ops, "discard", chart_data_lost_events);
565 rrddim_set(chart_ops, "failure", chart_transmission_failures);
566 rrddim_set(chart_ops, "reconnect", chart_backend_reconnects);
567 rrdset_done(chart_ops);
569 if(chart_metrics->counter_done) rrdset_next(chart_metrics);
570 rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
571 rrddim_set(chart_metrics, "lost", chart_lost_metrics);
572 rrddim_set(chart_metrics, "sent", chart_sent_metrics);
573 rrdset_done(chart_metrics);
575 if(chart_bytes->counter_done) rrdset_next(chart_bytes);
576 rrddim_set(chart_bytes, "buffered", chart_buffered_bytes);
577 rrddim_set(chart_bytes, "lost", chart_lost_bytes);
578 rrddim_set(chart_bytes, "sent", chart_sent_bytes);
579 rrddim_set(chart_bytes, "received", chart_received_bytes);
580 rrdset_done(chart_bytes);
583 if(chart_latency->counter_done) rrdset_next(chart_latency);
584 rrddim_set(chart_latency, "latency", chart_backend_latency);
585 rrdset_done(chart_latency);
588 getrusage(RUSAGE_THREAD, &thread);
589 if(chart_rusage->counter_done) rrdset_next(chart_rusage);
590 rrddim_set(chart_rusage, "user", thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
591 rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
592 rrdset_done(chart_rusage);
594 if(likely(buffer_strlen(b) == 0))
595 chart_buffered_metrics = 0;
597 if(unlikely(netdata_exit)) break;
605 buffer_free(response);
607 info("BACKEND thread exiting");
609 static_thread->enabled = 0;