]> arthur.barton.de Git - netdata.git/blob - src/backends.c
backend now sends all metrics for all hosts
[netdata.git] / src / backends.c
1 #include "common.h"
2
3 #define BACKEND_SOURCE_DATA_AS_COLLECTED 0x00000001
4 #define BACKEND_SOURCE_DATA_AVERAGE      0x00000002
5 #define BACKEND_SOURCE_DATA_SUM          0x00000004
6
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);
10
11     if(unlikely(before < first_t || after > last_t))
12         // the chart has not been updated in the wanted timeframe
13         return NAN;
14
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;
19
20     if(unlikely(after < first_t))
21         after = first_t;
22
23     if(unlikely(after > before))
24         // this can happen when the st->update_every > before - after
25         before = after;
26
27     if(unlikely(before > last_t))
28         before = last_t;
29
30     size_t counter = 0;
31     calculated_number sum = 0;
32
33     long    start_at_slot = rrdset_time2slot(st, before),
34             stop_at_slot  = rrdset_time2slot(st, after),
35             slot, stop_now = 0;
36
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;
40
41         storage_number n = rd->values[slot];
42         if(unlikely(!does_storage_number_exist(n))) continue;
43
44         calculated_number value = unpack_storage_number(n);
45         sum += value;
46         counter++;
47     }
48
49     if(unlikely(!counter))
50         return NAN;
51
52     if(unlikely(options & BACKEND_SOURCE_DATA_SUM))
53         return sum;
54
55     return sum / (calculated_number)counter;
56 }
57
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) {
59     (void)host;
60     (void)after;
61     (void)before;
62     (void)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);
64     return 1;
65 }
66
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) {
68     (void)host;
69     calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
70     if(!isnan(value)) {
71         buffer_sprintf(b, "%s.%s.%s.%s " CALCULATED_NUMBER_FORMAT " %u\n", prefix, hostname, st->id, rd->id, value, (uint32_t) before);
72         return 1;
73     }
74     return 0;
75 }
76
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) {
78     (void)host;
79     (void)after;
80     (void)before;
81     (void)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);
83     return 1;
84 }
85
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) {
87     (void)host;
88     calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
89     if(!isnan(value)) {
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);
91         return 1;
92     }
93     return 0;
94 }
95
96 static inline int process_graphite_response(BUFFER *b) {
97     char sample[1024];
98     const char *s = buffer_tostring(b);
99     char *d = sample, *e = &sample[sizeof(sample) - 1];
100
101     for(; *s && d < e ;s++) {
102         char c = *s;
103         if(unlikely(!isprint(c))) c = ' ';
104         *d++ = c;
105     }
106     *d = '\0';
107
108     info("Received %zu bytes from graphite backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
109     buffer_flush(b);
110     return 0;
111 }
112
113 static inline int process_opentsdb_response(BUFFER *b) {
114     char sample[1024];
115     const char *s = buffer_tostring(b);
116     char *d = sample, *e = &sample[sizeof(sample) - 1];
117
118     for(; *s && d < e ;s++) {
119         char c = *s;
120         if(unlikely(!isprint(c))) c = ' ';
121         *d++ = c;
122     }
123     *d = '\0';
124
125     info("Received %zu bytes from opentsdb backend. Ignoring them. Sample: '%s'", buffer_strlen(b), sample);
126     buffer_flush(b);
127     return 0;
128 }
129
130 void *backends_main(void *ptr) {
131     struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr;
132
133     BUFFER *b = buffer_create(1), *response = buffer_create(1);
134     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;
135     int (*backend_response_checker)(BUFFER *b) = NULL;
136
137     info("BACKEND thread created with task id %d", gettid());
138
139     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
140         error("Cannot set pthread cancel type to DEFERRED.");
141
142     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
143         error("Cannot set pthread cancel state to ENABLE.");
144
145     // ------------------------------------------------------------------------
146     // collect configuration options
147
148     struct timeval timeout = {
149             .tv_sec = 0,
150             .tv_usec = 0
151     };
152     int default_port = 0;
153     int sock = -1;
154     uint32_t options;
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);
164
165     // ------------------------------------------------------------------------
166     // validate configuration options
167     // and prepare for sending data to our backend
168
169     if(!enabled || frequency < 1)
170         goto cleanup;
171
172     if(!strcmp(source, "as collected")) {
173         options = BACKEND_SOURCE_DATA_AS_COLLECTED;
174     }
175     else if(!strcmp(source, "average")) {
176         options = BACKEND_SOURCE_DATA_AVERAGE;
177     }
178     else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
179         options = BACKEND_SOURCE_DATA_SUM;
180     }
181     else {
182         error("Invalid data source method '%s' for backend given. Disabling backed.", source);
183         goto cleanup;
184     }
185
186     if(timeoutms < 1) {
187         error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
188         timeoutms = frequency * 2 * 1000;
189     }
190     timeout.tv_sec  = (timeoutms * 1000) / 1000000;
191     timeout.tv_usec = (timeoutms * 1000) % 1000000;
192
193
194     // ------------------------------------------------------------------------
195     // select the backend type
196
197     if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
198         default_port = 2003;
199         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
200             backend_request_formatter = format_dimension_collected_graphite_plaintext;
201         else
202             backend_request_formatter = format_dimension_stored_graphite_plaintext;
203
204         backend_response_checker = process_graphite_response;
205     }
206     else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
207         default_port = 4242;
208         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
209             backend_request_formatter = format_dimension_collected_opentsdb_telnet;
210         else
211             backend_request_formatter = format_dimension_stored_opentsdb_telnet;
212
213         backend_response_checker = process_opentsdb_response;
214     }
215     else {
216         error("Unknown backend type '%s'", type);
217         goto cleanup;
218     }
219
220     if(backend_request_formatter == NULL || backend_response_checker == NULL) {
221         error("backend is misconfigured - disabling it.");
222         goto cleanup;
223     }
224
225
226     // ------------------------------------------------------------------------
227     // prepare the charts for monitoring the backend operation
228
229     struct rusage thread;
230
231     collected_number
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;
245
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);
250
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);
256
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);
263
264     /*
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
268      *
269      * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
270      *
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);
273     */
274
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);
278
279
280     // ------------------------------------------------------------------------
281     // prepare the backend main loop
282
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);
284
285     usec_t step_ut = frequency * USEC_PER_SEC;
286     time_t after = now_realtime_sec();
287     int failures = 0;
288     heartbeat_t hb;
289     heartbeat_init(&hb);
290
291     for(;;) {
292
293         // ------------------------------------------------------------------------
294         // Wait for the next iteration point.
295         heartbeat_next(&hb, step_ut);
296         time_t before = now_realtime_sec();
297
298
299         // ------------------------------------------------------------------------
300         // add to the buffer the data we need to send to the backend
301
302         int pthreadoldcancelstate;
303
304         if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
305             error("Cannot set pthread cancel state to DISABLE.");
306
307         RRDHOST *host;
308         for(host = localhost; host ; host = host->next) {
309             // for each host
310
311             rrdhost_rdlock(host);
312
313             RRDSET *st;
314             for(st = host->rrdset_root; st; st = st->next) {
315                 // for each chart
316
317                 pthread_rwlock_rdlock(&st->rwlock);
318
319                 RRDDIM *rd;
320                 for(rd = st->dimensions; rd; rd = rd->next) {
321                     // for each dimension
322
323                     if(rd->last_collected_time.tv_sec >= after)
324                         chart_buffered_metrics += backend_request_formatter(b, prefix, host, (host == localhost)?hostname:host->hostname, st, rd, after, before, options);
325                 }
326
327                 pthread_rwlock_unlock(&st->rwlock);
328             }
329
330             rrdhost_unlock(host);
331         }
332
333         if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
334             error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
335
336         // ------------------------------------------------------------------------
337
338         chart_buffered_bytes = (collected_number)buffer_strlen(b);
339
340         // reset the monitoring chart counters
341         chart_received_bytes =
342         chart_sent_bytes =
343         chart_sent_metrics =
344         chart_lost_metrics =
345         chart_transmission_successes =
346         chart_transmission_failures =
347         chart_data_lost_events =
348         chart_lost_bytes =
349         chart_backend_reconnects =
350         chart_backend_latency = 0;
351
352         if(unlikely(netdata_exit)) break;
353
354         //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
355         //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
356
357         // prepare for the next iteration
358         // to add incrementally data to buffer
359         after = before;
360
361         // ------------------------------------------------------------------------
362         // if we are connected, receive a response, without blocking
363
364         if(likely(sock != -1)) {
365             errno = 0;
366
367             // loop through to collect all data
368             while(sock != -1 && errno != EWOULDBLOCK) {
369                 buffer_need_bytes(response, 4096);
370
371                 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
372                 if(likely(r > 0)) {
373                     // we received some data
374                     response->len += r;
375                     chart_received_bytes += r;
376                     chart_receptions++;
377                 }
378                 else if(r == 0) {
379                     error("Backend '%s' closed the socket", destination);
380                     close(sock);
381                     sock = -1;
382                 }
383                 else {
384                     // failed to receive data
385                     if(errno != EAGAIN && errno != EWOULDBLOCK) {
386                         error("Cannot receive data from backend '%s'.", destination);
387                     }
388                 }
389             }
390
391             // if we received data, process them
392             if(buffer_strlen(response))
393                 backend_response_checker(response);
394         }
395
396         // ------------------------------------------------------------------------
397         // if we are not connected, connect to a backend server
398
399         if(unlikely(sock == -1)) {
400             usec_t start_ut = now_monotonic_usec();
401             const char *s = destination;
402             while(*s) {
403                 const char *e = s;
404
405                 // skip separators, moving both s(tart) and e(nd)
406                 while(isspace(*e) || *e == ',') s = ++e;
407
408                 // move e(nd) to the first separator
409                 while(*e && !isspace(*e) && *e != ',') e++;
410
411                 // is there anything?
412                 if(!*s || s == e) break;
413
414                 char buf[e - s + 1];
415                 strncpyz(buf, s, e - s);
416                 chart_backend_reconnects++;
417                 sock = connect_to(buf, default_port, &timeout);
418                 if(sock != -1) break;
419                 s = e;
420             }
421             chart_backend_latency += now_monotonic_usec() - start_ut;
422         }
423
424         if(unlikely(netdata_exit)) break;
425
426         // ------------------------------------------------------------------------
427         // if we are connected, send our buffer to the backend server
428
429         if(likely(sock != -1)) {
430             size_t len = buffer_strlen(b);
431             usec_t start_ut = now_monotonic_usec();
432             int flags = 0;
433 #ifdef MSG_NOSIGNAL
434             flags += MSG_NOSIGNAL;
435 #endif
436
437             ssize_t written = send(sock, buffer_tostring(b), len, flags);
438             chart_backend_latency += now_monotonic_usec() - start_ut;
439             if(written != -1 && (size_t)written == len) {
440                 // we sent the data successfully
441                 chart_transmission_successes++;
442                 chart_sent_bytes += written;
443                 chart_sent_metrics = chart_buffered_metrics;
444
445                 // reset the failures count
446                 failures = 0;
447
448                 // empty the buffer
449                 buffer_flush(b);
450             }
451             else {
452                 // oops! we couldn't send (all or some of the) data
453                 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
454                 chart_transmission_failures++;
455
456                 if(written != -1)
457                     chart_sent_bytes += written;
458
459                 // increment the counter we check for data loss
460                 failures++;
461
462                 // close the socket - we will re-open it next time
463                 close(sock);
464                 sock = -1;
465             }
466         }
467         else {
468             error("Failed to update database backend '%s'", destination);
469             chart_transmission_failures++;
470
471             // increment the counter we check for data loss
472             failures++;
473         }
474
475         if(failures > buffer_on_failures) {
476             // too bad! we are going to lose data
477             chart_lost_bytes += buffer_strlen(b);
478             error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
479             buffer_flush(b);
480             failures = 0;
481             chart_data_lost_events++;
482             chart_lost_metrics = chart_buffered_metrics;
483         }
484
485         if(unlikely(netdata_exit)) break;
486
487         // ------------------------------------------------------------------------
488         // update the monitoring charts
489
490         if(likely(chart_ops->counter_done)) rrdset_next(chart_ops);
491         rrddim_set(chart_ops, "read",         chart_receptions);
492         rrddim_set(chart_ops, "write",        chart_transmission_successes);
493         rrddim_set(chart_ops, "discard",      chart_data_lost_events);
494         rrddim_set(chart_ops, "failure",      chart_transmission_failures);
495         rrddim_set(chart_ops, "reconnect",    chart_backend_reconnects);
496         rrdset_done(chart_ops);
497
498         if(likely(chart_metrics->counter_done)) rrdset_next(chart_metrics);
499         rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
500         rrddim_set(chart_metrics, "lost",     chart_lost_metrics);
501         rrddim_set(chart_metrics, "sent",     chart_sent_metrics);
502         rrdset_done(chart_metrics);
503
504         if(likely(chart_bytes->counter_done)) rrdset_next(chart_bytes);
505         rrddim_set(chart_bytes, "buffered",   chart_buffered_bytes);
506         rrddim_set(chart_bytes, "lost",       chart_lost_bytes);
507         rrddim_set(chart_bytes, "sent",       chart_sent_bytes);
508         rrddim_set(chart_bytes, "received",   chart_received_bytes);
509         rrdset_done(chart_bytes);
510
511         /*
512         if(likely(chart_latency->counter_done)) rrdset_next(chart_latency);
513         rrddim_set(chart_latency, "latency",  chart_backend_latency);
514         rrdset_done(chart_latency);
515         */
516
517         getrusage(RUSAGE_THREAD, &thread);
518         if(likely(chart_rusage->counter_done)) rrdset_next(chart_rusage);
519         rrddim_set(chart_rusage, "user",   thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
520         rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
521         rrdset_done(chart_rusage);
522
523         if(likely(buffer_strlen(b) == 0))
524             chart_buffered_metrics = 0;
525
526         if(unlikely(netdata_exit)) break;
527     }
528
529 cleanup:
530     if(sock != -1)
531         close(sock);
532
533     buffer_free(b);
534     buffer_free(response);
535
536     info("BACKEND thread exiting");
537
538     static_thread->enabled = 0;
539     pthread_exit(NULL);
540     return NULL;
541 }