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\","
106 "\"value\":" COLLECTED_NUMBER_FORMAT ","
107 "\"timestamp\": %u}\n", prefix, hostname, st->id, rd->id, rd->last_collected_value, (uint32_t)rd->last_collected_time.tv_sec);
111 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) {
113 calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
115 buffer_sprintf(b, "{"
117 "\"hostname\":\"%s\","
120 "\"value\":" CALCULATED_NUMBER_FORMAT ","
121 "\"timestamp\": %u}\n", prefix, hostname, st->id, rd->id, value, (uint32_t) before);
127 static inline int process_graphite_response(BUFFER *b) {
129 const char *s = buffer_tostring(b);
130 char *d = sample, *e = &sample[sizeof(sample) - 1];
132 for(; *s && d < e ;s++) {
134 if(unlikely(!isprint(c))) c = ' ';
139 info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
144 static inline int process_json_response(BUFFER *b) {
146 const char *s = buffer_tostring(b);
147 char *d = sample, *e = &sample[sizeof(sample) - 1];
149 for(; *s && d < e ;s++) {
151 if(unlikely(!isprint(c))) c = ' ';
156 info("Received %zu bytes from json backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
161 static inline int process_opentsdb_response(BUFFER *b) {
163 const char *s = buffer_tostring(b);
164 char *d = sample, *e = &sample[sizeof(sample) - 1];
166 for(; *s && d < e ;s++) {
168 if(unlikely(!isprint(c))) c = ' ';
173 info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
178 void *backends_main(void *ptr) {
179 struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
181 BUFFER *b = buffer_create(1), *response = buffer_create(1);
182 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;
183 int (*backend_response_checker)(BUFFER *b) = NULL;
185 info("BACKEND thread created with task id %d", gettid());
187 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
188 error("Cannot set pthread cancel type to DEFERRED.");
190 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
191 error("Cannot set pthread cancel state to ENABLE.");
193 // ------------------------------------------------------------------------
194 // collect configuration options
196 struct timeval timeout = {
200 int default_port = 0;
203 int enabled = config_get_boolean("backend", "enabled", 0);
204 const char *source = config_get("backend", "data source", "average");
205 const char *type = config_get("backend", "type", "graphite");
206 const char *destination = config_get("backend", "destination", "localhost");
207 const char *prefix = config_get("backend", "prefix", "netdata");
208 const char *hostname = config_get("backend", "hostname", localhost.hostname);
209 int frequency = (int)config_get_number("backend", "update every", 10);
210 int buffer_on_failures = (int)config_get_number("backend", "buffer on failures", 10);
211 long timeoutms = config_get_number("backend", "timeout ms", frequency * 2 * 1000);
213 // ------------------------------------------------------------------------
214 // validate configuration options
215 // and prepare for sending data to our backend
216 if(!enabled || frequency < 1)
219 if(!strcmp(source, "as collected")) {
220 options = BACKEND_SOURCE_DATA_AS_COLLECTED;
222 else if(!strcmp(source, "average")) {
223 options = BACKEND_SOURCE_DATA_AVERAGE;
225 else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
226 options = BACKEND_SOURCE_DATA_SUM;
229 error("Invalid data source method '%s' for backend given. Disabling backed.", source);
233 if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
235 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
236 backend_request_formatter = format_dimension_collected_graphite_plaintext;
238 backend_request_formatter = format_dimension_stored_graphite_plaintext;
240 backend_response_checker = process_graphite_response;
242 else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
244 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
245 backend_request_formatter = format_dimension_collected_opentsdb_telnet;
247 backend_request_formatter = format_dimension_stored_opentsdb_telnet;
249 backend_response_checker = process_opentsdb_response;
251 else if (!strcmp(type, "json") || !strcmp(type, "json:plaintext"))
255 if (options == BACKEND_SOURCE_DATA_AS_COLLECTED)
257 backend_request_formatter = format_dimension_collected_json_plaintext;
261 backend_request_formatter = format_dimension_stored_json_plaintext;
264 backend_response_checker = process_json_response;
267 error("Unknown backend type '%s'", type);
271 if(backend_request_formatter == NULL || backend_response_checker == NULL) {
272 error("backend is misconfigured - disabling it.");
277 error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
278 timeoutms = frequency * 2 * 1000;
280 timeout.tv_sec = (timeoutms * 1000) / 1000000;
281 timeout.tv_usec = (timeoutms * 1000) % 1000000;
283 // ------------------------------------------------------------------------
284 // prepare the charts for monitoring the backend
286 struct rusage thread;
289 chart_buffered_metrics = 0,
290 chart_lost_metrics = 0,
291 chart_sent_metrics = 0,
292 chart_buffered_bytes = 0,
293 chart_received_bytes = 0,
294 chart_sent_bytes = 0,
295 chart_receptions = 0,
296 chart_transmission_successes = 0,
297 chart_transmission_failures = 0,
298 chart_data_lost_events = 0,
299 chart_lost_bytes = 0,
300 chart_backend_reconnects = 0,
301 chart_backend_latency = 0;
303 RRDSET *chart_metrics = rrdset_find("netdata.backend_metrics");
305 chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
306 rrddim_add(chart_metrics, "buffered", NULL, 1, 1, RRDDIM_ABSOLUTE);
307 rrddim_add(chart_metrics, "lost", NULL, 1, 1, RRDDIM_ABSOLUTE);
308 rrddim_add(chart_metrics, "sent", NULL, 1, 1, RRDDIM_ABSOLUTE);
311 RRDSET *chart_bytes = rrdset_find("netdata.backend_bytes");
313 chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
314 rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRDDIM_ABSOLUTE);
315 rrddim_add(chart_bytes, "lost", NULL, 1, 1024, RRDDIM_ABSOLUTE);
316 rrddim_add(chart_bytes, "sent", NULL, 1, 1024, RRDDIM_ABSOLUTE);
317 rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRDDIM_ABSOLUTE);
320 RRDSET *chart_ops = rrdset_find("netdata.backend_ops");
322 chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
323 rrddim_add(chart_ops, "write", NULL, 1, 1, RRDDIM_ABSOLUTE);
324 rrddim_add(chart_ops, "discard", NULL, 1, 1, RRDDIM_ABSOLUTE);
325 rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRDDIM_ABSOLUTE);
326 rrddim_add(chart_ops, "failure", NULL, 1, 1, RRDDIM_ABSOLUTE);
327 rrddim_add(chart_ops, "read", NULL, 1, 1, RRDDIM_ABSOLUTE);
331 * this is misleading - we can only measure the time we need to send data
332 * this time is not related to the time required for the data to travel to
333 * the backend database and the time that server needed to process them
335 * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
337 RRDSET *chart_latency = rrdset_find("netdata.backend_latency");
339 chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
340 rrddim_add(chart_latency, "latency", NULL, 1, 1000, RRDDIM_ABSOLUTE);
344 RRDSET *chart_rusage = rrdset_find("netdata.backend_thread_cpu");
346 chart_rusage = rrdset_create("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
347 rrddim_add(chart_rusage, "user", NULL, 1, 1000, RRDDIM_INCREMENTAL);
348 rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRDDIM_INCREMENTAL);
351 // ------------------------------------------------------------------------
352 // prepare the backend main loop
354 info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
356 usec_t step_ut = frequency * USEC_PER_SEC;
357 time_t after = now_realtime_sec();
363 // ------------------------------------------------------------------------
364 // Wait for the next iteration point.
365 heartbeat_next(&hb, step_ut);
366 time_t before = now_realtime_sec();
368 // ------------------------------------------------------------------------
369 // add to the buffer the data we need to send to the backend
371 int pthreadoldcancelstate;
373 if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
374 error("Cannot set pthread cancel state to DISABLE.");
376 rrdhost_rdlock(&localhost);
377 for(st = localhost.rrdset_root; st ;st = st->next) {
378 pthread_rwlock_rdlock(&st->rwlock);
381 for(rd = st->dimensions; rd ;rd = rd->next) {
382 if(rd->last_collected_time.tv_sec >= after)
383 chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
386 pthread_rwlock_unlock(&st->rwlock);
388 rrdhost_unlock(&localhost);
390 if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
391 error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
393 // ------------------------------------------------------------------------
395 chart_buffered_bytes = (collected_number)buffer_strlen(b);
397 // reset the monitoring chart counters
398 chart_received_bytes =
402 chart_transmission_successes =
403 chart_transmission_failures =
404 chart_data_lost_events =
406 chart_backend_reconnects =
407 chart_backend_latency = 0;
409 if(unlikely(netdata_exit)) break;
411 //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
412 //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
414 // prepare for the next iteration
415 // to add incrementally data to buffer
418 // ------------------------------------------------------------------------
419 // if we are connected, receive a response, without blocking
421 if(likely(sock != -1)) {
424 // loop through to collect all data
425 while(sock != -1 && errno != EWOULDBLOCK) {
426 buffer_need_bytes(response, 4096);
428 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
430 // we received some data
432 chart_received_bytes += r;
436 error("Backend '%s' closed the socket", destination);
441 // failed to receive data
442 if(errno != EAGAIN && errno != EWOULDBLOCK) {
443 error("Cannot receive data from backend '%s'.", destination);
448 // if we received data, process them
449 if(buffer_strlen(response))
450 backend_response_checker(response);
453 // ------------------------------------------------------------------------
454 // if we are not connected, connect to a backend server
456 if(unlikely(sock == -1)) {
457 usec_t start_ut = now_monotonic_usec();
458 const char *s = destination;
462 // skip separators, moving both s(tart) and e(nd)
463 while(isspace(*e) || *e == ',') s = ++e;
465 // move e(nd) to the first separator
466 while(*e && !isspace(*e) && *e != ',') e++;
468 // is there anything?
469 if(!*s || s == e) break;
472 strncpyz(buf, s, e - s);
473 chart_backend_reconnects++;
474 sock = connect_to(buf, default_port, &timeout);
475 if(sock != -1) break;
478 chart_backend_latency += now_monotonic_usec() - start_ut;
481 if(unlikely(netdata_exit)) break;
483 // ------------------------------------------------------------------------
484 // if we are connected, send our buffer to the backend server
486 if(likely(sock != -1)) {
487 size_t len = buffer_strlen(b);
488 usec_t start_ut = now_monotonic_usec();
491 flags += MSG_NOSIGNAL;
494 ssize_t written = send(sock, buffer_tostring(b), len, flags);
495 chart_backend_latency += now_monotonic_usec() - start_ut;
496 if(written != -1 && (size_t)written == len) {
497 // we sent the data successfully
498 chart_transmission_successes++;
499 chart_sent_bytes += written;
500 chart_sent_metrics = chart_buffered_metrics;
502 // reset the failures count
509 // oops! we couldn't send (all or some of the) data
510 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
511 chart_transmission_failures++;
514 chart_sent_bytes += written;
516 // increment the counter we check for data loss
519 // close the socket - we will re-open it next time
525 error("Failed to update database backend '%s'", destination);
526 chart_transmission_failures++;
528 // increment the counter we check for data loss
532 if(failures > buffer_on_failures) {
533 // too bad! we are going to lose data
534 chart_lost_bytes += buffer_strlen(b);
535 error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
538 chart_data_lost_events++;
539 chart_lost_metrics = chart_buffered_metrics;
542 if(unlikely(netdata_exit)) break;
544 // ------------------------------------------------------------------------
545 // update the monitoring charts
547 if(chart_ops->counter_done) rrdset_next(chart_ops);
548 rrddim_set(chart_ops, "read", chart_receptions);
549 rrddim_set(chart_ops, "write", chart_transmission_successes);
550 rrddim_set(chart_ops, "discard", chart_data_lost_events);
551 rrddim_set(chart_ops, "failure", chart_transmission_failures);
552 rrddim_set(chart_ops, "reconnect", chart_backend_reconnects);
553 rrdset_done(chart_ops);
555 if(chart_metrics->counter_done) rrdset_next(chart_metrics);
556 rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
557 rrddim_set(chart_metrics, "lost", chart_lost_metrics);
558 rrddim_set(chart_metrics, "sent", chart_sent_metrics);
559 rrdset_done(chart_metrics);
561 if(chart_bytes->counter_done) rrdset_next(chart_bytes);
562 rrddim_set(chart_bytes, "buffered", chart_buffered_bytes);
563 rrddim_set(chart_bytes, "lost", chart_lost_bytes);
564 rrddim_set(chart_bytes, "sent", chart_sent_bytes);
565 rrddim_set(chart_bytes, "received", chart_received_bytes);
566 rrdset_done(chart_bytes);
569 if(chart_latency->counter_done) rrdset_next(chart_latency);
570 rrddim_set(chart_latency, "latency", chart_backend_latency);
571 rrdset_done(chart_latency);
574 getrusage(RUSAGE_THREAD, &thread);
575 if(chart_rusage->counter_done) rrdset_next(chart_rusage);
576 rrddim_set(chart_rusage, "user", thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
577 rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
578 rrdset_done(chart_rusage);
580 if(likely(buffer_strlen(b) == 0))
581 chart_buffered_metrics = 0;
583 if(unlikely(netdata_exit)) break;
591 buffer_free(response);
593 info("BACKEND thread exiting");
595 static_thread->enabled = 0;