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 process_graphite_response(BUFFER *b) {
98 const char *s = buffer_tostring(b);
99 char *d = sample, *e = &sample[sizeof(sample) - 1];
101 for(; *s && d < e ;s++) {
103 if(unlikely(!isprint(c))) c = ' ';
108 info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
113 static inline int process_opentsdb_response(BUFFER *b) {
115 const char *s = buffer_tostring(b);
116 char *d = sample, *e = &sample[sizeof(sample) - 1];
118 for(; *s && d < e ;s++) {
120 if(unlikely(!isprint(c))) c = ' ';
125 info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
130 void *backends_main(void *ptr) {
131 int default_port = 0;
133 struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
135 BUFFER *b = buffer_create(1), *response = buffer_create(1);
136 int (*backend_request_formatter)(BUFFER *, const char *, RRDHOST *, const char *, RRDSET *, RRDDIM *, time_t, time_t, uint32_t) = NULL;
137 int (*backend_response_checker)(BUFFER *) = NULL;
139 info("BACKEND thread created with task id %d", gettid());
141 if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
142 error("Cannot set pthread cancel type to DEFERRED.");
144 if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
145 error("Cannot set pthread cancel state to ENABLE.");
147 // ------------------------------------------------------------------------
148 // collect configuration options
150 struct timeval timeout = {
155 int enabled = config_get_boolean("backend", "enabled", 0);
156 const char *source = config_get("backend", "data source", "average");
157 const char *type = config_get("backend", "type", "graphite");
158 const char *destination = config_get("backend", "destination", "localhost");
159 const char *prefix = config_get("backend", "prefix", "netdata");
160 const char *hostname = config_get("backend", "hostname", localhost->hostname);
161 int frequency = (int)config_get_number("backend", "update every", 10);
162 int buffer_on_failures = (int)config_get_number("backend", "buffer on failures", 10);
163 long timeoutms = config_get_number("backend", "timeout ms", frequency * 2 * 1000);
165 // ------------------------------------------------------------------------
166 // validate configuration options
167 // and prepare for sending data to our backend
169 if(!enabled || frequency < 1)
172 if(!strcmp(source, "as collected")) {
173 options = BACKEND_SOURCE_DATA_AS_COLLECTED;
175 else if(!strcmp(source, "average")) {
176 options = BACKEND_SOURCE_DATA_AVERAGE;
178 else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
179 options = BACKEND_SOURCE_DATA_SUM;
182 error("Invalid data source method '%s' for backend given. Disabling backed.", source);
187 error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
188 timeoutms = frequency * 2 * 1000;
190 timeout.tv_sec = (timeoutms * 1000) / 1000000;
191 timeout.tv_usec = (timeoutms * 1000) % 1000000;
194 // ------------------------------------------------------------------------
195 // select the backend type
197 if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
199 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
200 backend_request_formatter = format_dimension_collected_graphite_plaintext;
202 backend_request_formatter = format_dimension_stored_graphite_plaintext;
204 backend_response_checker = process_graphite_response;
206 else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
208 if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
209 backend_request_formatter = format_dimension_collected_opentsdb_telnet;
211 backend_request_formatter = format_dimension_stored_opentsdb_telnet;
213 backend_response_checker = process_opentsdb_response;
216 error("Unknown backend type '%s'", type);
220 if(backend_request_formatter == NULL || backend_response_checker == NULL) {
221 error("backend is misconfigured - disabling it.");
226 // ------------------------------------------------------------------------
227 // prepare the charts for monitoring the backend operation
229 struct rusage thread;
232 chart_buffered_metrics = 0,
233 chart_lost_metrics = 0,
234 chart_sent_metrics = 0,
235 chart_buffered_bytes = 0,
236 chart_received_bytes = 0,
237 chart_sent_bytes = 0,
238 chart_receptions = 0,
239 chart_transmission_successes = 0,
240 chart_transmission_failures = 0,
241 chart_data_lost_events = 0,
242 chart_lost_bytes = 0,
243 chart_backend_reconnects = 0,
244 chart_backend_latency = 0;
246 RRDSET *chart_metrics = rrdset_create_localhost("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
247 rrddim_add(chart_metrics, "buffered", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
248 rrddim_add(chart_metrics, "lost", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
249 rrddim_add(chart_metrics, "sent", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
251 RRDSET *chart_bytes = rrdset_create_localhost("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
252 rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
253 rrddim_add(chart_bytes, "lost", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
254 rrddim_add(chart_bytes, "sent", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
255 rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
257 RRDSET *chart_ops = rrdset_create_localhost("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
258 rrddim_add(chart_ops, "write", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
259 rrddim_add(chart_ops, "discard", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
260 rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
261 rrddim_add(chart_ops, "failure", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
262 rrddim_add(chart_ops, "read", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
265 * this is misleading - we can only measure the time we need to send data
266 * this time is not related to the time required for the data to travel to
267 * the backend database and the time that server needed to process them
269 * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
271 RRDSET *chart_latency = rrdset_create_localhost("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
272 rrddim_add(chart_latency, "latency", NULL, 1, 1000, RRD_ALGORITHM_ABSOLUTE);
275 RRDSET *chart_rusage = rrdset_create_localhost("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
276 rrddim_add(chart_rusage, "user", NULL, 1, 1000, RRD_ALGORITHM_INCREMENTAL);
277 rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRD_ALGORITHM_INCREMENTAL);
280 // ------------------------------------------------------------------------
281 // prepare the backend main loop
283 info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
285 usec_t step_ut = frequency * USEC_PER_SEC;
286 time_t after = now_realtime_sec();
293 // ------------------------------------------------------------------------
294 // Wait for the next iteration point.
295 heartbeat_next(&hb, step_ut);
296 time_t before = now_realtime_sec();
299 // ------------------------------------------------------------------------
300 // add to the buffer the data we need to send to the backend
302 int pthreadoldcancelstate;
304 if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
305 error("Cannot set pthread cancel state to DISABLE.");
309 rrdhost_foreach_read(host) {
310 if(host->rrd_memory_mode == RRD_MEMORY_MODE_NONE)
313 rrdhost_rdlock(host);
316 rrdset_foreach_read(st, host) {
320 rrddim_foreach_read(rd, st) {
321 if(rd->last_collected_time.tv_sec >= after)
322 chart_buffered_metrics += backend_request_formatter(b, prefix, host, (host == localhost)?hostname:host->hostname, st, rd, after, before, options);
326 rrdhost_unlock(host);
330 if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
331 error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
333 // ------------------------------------------------------------------------
335 chart_buffered_bytes = (collected_number)buffer_strlen(b);
337 // reset the monitoring chart counters
338 chart_received_bytes =
342 chart_transmission_successes =
343 chart_transmission_failures =
344 chart_data_lost_events =
346 chart_backend_reconnects =
347 chart_backend_latency = 0;
349 if(unlikely(netdata_exit)) break;
351 //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
352 //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
354 // prepare for the next iteration
355 // to add incrementally data to buffer
358 // ------------------------------------------------------------------------
359 // if we are connected, receive a response, without blocking
361 if(likely(sock != -1)) {
364 // loop through to collect all data
365 while(sock != -1 && errno != EWOULDBLOCK) {
366 buffer_need_bytes(response, 4096);
368 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
370 // we received some data
372 chart_received_bytes += r;
376 error("Backend '%s' closed the socket", destination);
381 // failed to receive data
382 if(errno != EAGAIN && errno != EWOULDBLOCK) {
383 error("Cannot receive data from backend '%s'.", destination);
388 // if we received data, process them
389 if(buffer_strlen(response))
390 backend_response_checker(response);
393 // ------------------------------------------------------------------------
394 // if we are not connected, connect to a backend server
396 if(unlikely(sock == -1)) {
397 usec_t start_ut = now_monotonic_usec();
398 size_t reconnects = 0;
400 sock = connect_to_one_of(destination, default_port, &timeout, &reconnects, NULL, 0);
402 chart_backend_reconnects += reconnects;
403 chart_backend_latency += now_monotonic_usec() - start_ut;
406 if(unlikely(netdata_exit)) break;
408 // ------------------------------------------------------------------------
409 // if we are connected, send our buffer to the backend server
411 if(likely(sock != -1)) {
412 size_t len = buffer_strlen(b);
413 usec_t start_ut = now_monotonic_usec();
416 flags += MSG_NOSIGNAL;
419 ssize_t written = send(sock, buffer_tostring(b), len, flags);
420 chart_backend_latency += now_monotonic_usec() - start_ut;
421 if(written != -1 && (size_t)written == len) {
422 // we sent the data successfully
423 chart_transmission_successes++;
424 chart_sent_bytes += written;
425 chart_sent_metrics = chart_buffered_metrics;
427 // reset the failures count
434 // oops! we couldn't send (all or some of the) data
435 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
436 chart_transmission_failures++;
439 chart_sent_bytes += written;
441 // increment the counter we check for data loss
444 // close the socket - we will re-open it next time
450 error("Failed to update database backend '%s'", destination);
451 chart_transmission_failures++;
453 // increment the counter we check for data loss
457 if(failures > buffer_on_failures) {
458 // too bad! we are going to lose data
459 chart_lost_bytes += buffer_strlen(b);
460 error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
463 chart_data_lost_events++;
464 chart_lost_metrics = chart_buffered_metrics;
467 if(unlikely(netdata_exit)) break;
469 // ------------------------------------------------------------------------
470 // update the monitoring charts
472 if(likely(chart_ops->counter_done)) rrdset_next(chart_ops);
473 rrddim_set(chart_ops, "read", chart_receptions);
474 rrddim_set(chart_ops, "write", chart_transmission_successes);
475 rrddim_set(chart_ops, "discard", chart_data_lost_events);
476 rrddim_set(chart_ops, "failure", chart_transmission_failures);
477 rrddim_set(chart_ops, "reconnect", chart_backend_reconnects);
478 rrdset_done(chart_ops);
480 if(likely(chart_metrics->counter_done)) rrdset_next(chart_metrics);
481 rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
482 rrddim_set(chart_metrics, "lost", chart_lost_metrics);
483 rrddim_set(chart_metrics, "sent", chart_sent_metrics);
484 rrdset_done(chart_metrics);
486 if(likely(chart_bytes->counter_done)) rrdset_next(chart_bytes);
487 rrddim_set(chart_bytes, "buffered", chart_buffered_bytes);
488 rrddim_set(chart_bytes, "lost", chart_lost_bytes);
489 rrddim_set(chart_bytes, "sent", chart_sent_bytes);
490 rrddim_set(chart_bytes, "received", chart_received_bytes);
491 rrdset_done(chart_bytes);
494 if(likely(chart_latency->counter_done)) rrdset_next(chart_latency);
495 rrddim_set(chart_latency, "latency", chart_backend_latency);
496 rrdset_done(chart_latency);
499 getrusage(RUSAGE_THREAD, &thread);
500 if(likely(chart_rusage->counter_done)) rrdset_next(chart_rusage);
501 rrddim_set(chart_rusage, "user", thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
502 rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
503 rrdset_done(chart_rusage);
505 if(likely(buffer_strlen(b) == 0))
506 chart_buffered_metrics = 0;
508 if(unlikely(netdata_exit)) break;
516 buffer_free(response);
518 info("BACKEND thread exiting");
520 static_thread->enabled = 0;