]> arthur.barton.de Git - netdata.git/blob - src/backends.c
b1c10d9d0631e3cad91b22fb135a20bfd6202b18
[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     if(!enabled || frequency < 1)
169         goto cleanup;
170
171     if(!strcmp(source, "as collected")) {
172         options = BACKEND_SOURCE_DATA_AS_COLLECTED;
173     }
174     else if(!strcmp(source, "average")) {
175         options = BACKEND_SOURCE_DATA_AVERAGE;
176     }
177     else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
178         options = BACKEND_SOURCE_DATA_SUM;
179     }
180     else {
181         error("Invalid data source method '%s' for backend given. Disabling backed.", source);
182         goto cleanup;
183     }
184
185     if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
186         default_port = 2003;
187         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
188             backend_request_formatter = format_dimension_collected_graphite_plaintext;
189         else
190             backend_request_formatter = format_dimension_stored_graphite_plaintext;
191
192         backend_response_checker = process_graphite_response;
193     }
194     else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
195         default_port = 4242;
196         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
197             backend_request_formatter = format_dimension_collected_opentsdb_telnet;
198         else
199             backend_request_formatter = format_dimension_stored_opentsdb_telnet;
200
201         backend_response_checker = process_opentsdb_response;
202     }
203     else {
204         error("Unknown backend type '%s'", type);
205         goto cleanup;
206     }
207
208     if(backend_request_formatter == NULL || backend_response_checker == NULL) {
209         error("backend is misconfigured - disabling it.");
210         goto cleanup;
211     }
212
213     if(timeoutms < 1) {
214         error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
215         timeoutms = frequency * 2 * 1000;
216     }
217     timeout.tv_sec  = (timeoutms * 1000) / 1000000;
218     timeout.tv_usec = (timeoutms * 1000) % 1000000;
219
220     // ------------------------------------------------------------------------
221     // prepare the charts for monitoring the backend
222
223     struct rusage thread;
224
225     collected_number
226             chart_buffered_metrics = 0,
227             chart_lost_metrics = 0,
228             chart_sent_metrics = 0,
229             chart_buffered_bytes = 0,
230             chart_received_bytes = 0,
231             chart_sent_bytes = 0,
232             chart_receptions = 0,
233             chart_transmission_successes = 0,
234             chart_transmission_failures = 0,
235             chart_data_lost_events = 0,
236             chart_lost_bytes = 0,
237             chart_backend_reconnects = 0,
238             chart_backend_latency = 0;
239
240     RRDSET *chart_metrics = rrdset_find_localhost("netdata.backend_metrics");
241     if(!chart_metrics) {
242         chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
243         rrddim_add(chart_metrics, "buffered", NULL,  1, 1, RRD_ALGORITHM_ABSOLUTE);
244         rrddim_add(chart_metrics, "lost",     NULL,  1, 1, RRD_ALGORITHM_ABSOLUTE);
245         rrddim_add(chart_metrics, "sent",     NULL,  1, 1, RRD_ALGORITHM_ABSOLUTE);
246     }
247
248     RRDSET *chart_bytes = rrdset_find_localhost("netdata.backend_bytes");
249     if(!chart_bytes) {
250         chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
251         rrddim_add(chart_bytes, "buffered", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
252         rrddim_add(chart_bytes, "lost",     NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
253         rrddim_add(chart_bytes, "sent",     NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
254         rrddim_add(chart_bytes, "received", NULL, 1, 1024, RRD_ALGORITHM_ABSOLUTE);
255     }
256
257     RRDSET *chart_ops = rrdset_find_localhost("netdata.backend_ops");
258     if(!chart_ops) {
259         chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
260         rrddim_add(chart_ops, "write",     NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
261         rrddim_add(chart_ops, "discard",   NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
262         rrddim_add(chart_ops, "reconnect", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
263         rrddim_add(chart_ops, "failure",   NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
264         rrddim_add(chart_ops, "read",      NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE);
265     }
266
267     /*
268      * this is misleading - we can only measure the time we need to send data
269      * this time is not related to the time required for the data to travel to
270      * the backend database and the time that server needed to process them
271      *
272      * issue #1432 and https://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-2.html
273      *
274     RRDSET *chart_latency = rrdset_find_localhost("netdata.backend_latency");
275     if(!chart_latency) {
276         chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
277         rrddim_add(chart_latency, "latency",   NULL,  1, 1000, RRD_ALGORITHM_ABSOLUTE);
278     }
279     */
280
281     RRDSET *chart_rusage = rrdset_find_localhost("netdata.backend_thread_cpu");
282     if(!chart_rusage) {
283         chart_rusage = rrdset_create("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
284         rrddim_add(chart_rusage, "user",   NULL, 1, 1000, RRD_ALGORITHM_INCREMENTAL);
285         rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRD_ALGORITHM_INCREMENTAL);
286     }
287
288     // ------------------------------------------------------------------------
289     // prepare the backend main loop
290
291     info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
292
293     usec_t step_ut = frequency * USEC_PER_SEC;
294     time_t after = now_realtime_sec();
295     int failures = 0;
296     heartbeat_t hb;
297     heartbeat_init(&hb);
298
299     for(;;) {
300         // ------------------------------------------------------------------------
301         // Wait for the next iteration point.
302         heartbeat_next(&hb, step_ut);
303         time_t before = now_realtime_sec();
304
305         // ------------------------------------------------------------------------
306         // add to the buffer the data we need to send to the backend
307         RRDSET *st;
308         int pthreadoldcancelstate;
309
310         if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
311             error("Cannot set pthread cancel state to DISABLE.");
312
313         rrdhost_rdlock(&localhost);
314         for(st = localhost.rrdset_root; st ;st = st->next) {
315             pthread_rwlock_rdlock(&st->rwlock);
316
317             RRDDIM *rd;
318             for(rd = st->dimensions; rd ;rd = rd->next) {
319                 if(rd->last_collected_time.tv_sec >= after)
320                     chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
321             }
322
323             pthread_rwlock_unlock(&st->rwlock);
324         }
325         rrdhost_unlock(&localhost);
326
327         if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
328             error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
329
330         // ------------------------------------------------------------------------
331
332         chart_buffered_bytes = (collected_number)buffer_strlen(b);
333
334         // reset the monitoring chart counters
335         chart_received_bytes =
336         chart_sent_bytes =
337         chart_sent_metrics =
338         chart_lost_metrics =
339         chart_transmission_successes =
340         chart_transmission_failures =
341         chart_data_lost_events =
342         chart_lost_bytes =
343         chart_backend_reconnects =
344         chart_backend_latency = 0;
345
346         if(unlikely(netdata_exit)) break;
347
348         //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
349         //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
350
351         // prepare for the next iteration
352         // to add incrementally data to buffer
353         after = before;
354
355         // ------------------------------------------------------------------------
356         // if we are connected, receive a response, without blocking
357
358         if(likely(sock != -1)) {
359             errno = 0;
360
361             // loop through to collect all data
362             while(sock != -1 && errno != EWOULDBLOCK) {
363                 buffer_need_bytes(response, 4096);
364
365                 ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len, MSG_DONTWAIT);
366                 if(likely(r > 0)) {
367                     // we received some data
368                     response->len += r;
369                     chart_received_bytes += r;
370                     chart_receptions++;
371                 }
372                 else if(r == 0) {
373                     error("Backend '%s' closed the socket", destination);
374                     close(sock);
375                     sock = -1;
376                 }
377                 else {
378                     // failed to receive data
379                     if(errno != EAGAIN && errno != EWOULDBLOCK) {
380                         error("Cannot receive data from backend '%s'.", destination);
381                     }
382                 }
383             }
384
385             // if we received data, process them
386             if(buffer_strlen(response))
387                 backend_response_checker(response);
388         }
389
390         // ------------------------------------------------------------------------
391         // if we are not connected, connect to a backend server
392
393         if(unlikely(sock == -1)) {
394             usec_t start_ut = now_monotonic_usec();
395             const char *s = destination;
396             while(*s) {
397                 const char *e = s;
398
399                 // skip separators, moving both s(tart) and e(nd)
400                 while(isspace(*e) || *e == ',') s = ++e;
401
402                 // move e(nd) to the first separator
403                 while(*e && !isspace(*e) && *e != ',') e++;
404
405                 // is there anything?
406                 if(!*s || s == e) break;
407
408                 char buf[e - s + 1];
409                 strncpyz(buf, s, e - s);
410                 chart_backend_reconnects++;
411                 sock = connect_to(buf, default_port, &timeout);
412                 if(sock != -1) break;
413                 s = e;
414             }
415             chart_backend_latency += now_monotonic_usec() - start_ut;
416         }
417
418         if(unlikely(netdata_exit)) break;
419
420         // ------------------------------------------------------------------------
421         // if we are connected, send our buffer to the backend server
422
423         if(likely(sock != -1)) {
424             size_t len = buffer_strlen(b);
425             usec_t start_ut = now_monotonic_usec();
426             int flags = 0;
427 #ifdef MSG_NOSIGNAL
428             flags += MSG_NOSIGNAL;
429 #endif
430
431             ssize_t written = send(sock, buffer_tostring(b), len, flags);
432             chart_backend_latency += now_monotonic_usec() - start_ut;
433             if(written != -1 && (size_t)written == len) {
434                 // we sent the data successfully
435                 chart_transmission_successes++;
436                 chart_sent_bytes += written;
437                 chart_sent_metrics = chart_buffered_metrics;
438
439                 // reset the failures count
440                 failures = 0;
441
442                 // empty the buffer
443                 buffer_flush(b);
444             }
445             else {
446                 // oops! we couldn't send (all or some of the) data
447                 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
448                 chart_transmission_failures++;
449
450                 if(written != -1)
451                     chart_sent_bytes += written;
452
453                 // increment the counter we check for data loss
454                 failures++;
455
456                 // close the socket - we will re-open it next time
457                 close(sock);
458                 sock = -1;
459             }
460         }
461         else {
462             error("Failed to update database backend '%s'", destination);
463             chart_transmission_failures++;
464
465             // increment the counter we check for data loss
466             failures++;
467         }
468
469         if(failures > buffer_on_failures) {
470             // too bad! we are going to lose data
471             chart_lost_bytes += buffer_strlen(b);
472             error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
473             buffer_flush(b);
474             failures = 0;
475             chart_data_lost_events++;
476             chart_lost_metrics = chart_buffered_metrics;
477         }
478
479         if(unlikely(netdata_exit)) break;
480
481         // ------------------------------------------------------------------------
482         // update the monitoring charts
483
484         if(chart_ops->counter_done) rrdset_next(chart_ops);
485         rrddim_set(chart_ops, "read",         chart_receptions);
486         rrddim_set(chart_ops, "write",        chart_transmission_successes);
487         rrddim_set(chart_ops, "discard",      chart_data_lost_events);
488         rrddim_set(chart_ops, "failure",      chart_transmission_failures);
489         rrddim_set(chart_ops, "reconnect",    chart_backend_reconnects);
490         rrdset_done(chart_ops);
491
492         if(chart_metrics->counter_done) rrdset_next(chart_metrics);
493         rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
494         rrddim_set(chart_metrics, "lost",     chart_lost_metrics);
495         rrddim_set(chart_metrics, "sent",     chart_sent_metrics);
496         rrdset_done(chart_metrics);
497
498         if(chart_bytes->counter_done) rrdset_next(chart_bytes);
499         rrddim_set(chart_bytes, "buffered",   chart_buffered_bytes);
500         rrddim_set(chart_bytes, "lost",       chart_lost_bytes);
501         rrddim_set(chart_bytes, "sent",       chart_sent_bytes);
502         rrddim_set(chart_bytes, "received",   chart_received_bytes);
503         rrdset_done(chart_bytes);
504
505         /*
506         if(chart_latency->counter_done) rrdset_next(chart_latency);
507         rrddim_set(chart_latency, "latency",  chart_backend_latency);
508         rrdset_done(chart_latency);
509         */
510
511         getrusage(RUSAGE_THREAD, &thread);
512         if(chart_rusage->counter_done) rrdset_next(chart_rusage);
513         rrddim_set(chart_rusage, "user",   thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
514         rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
515         rrdset_done(chart_rusage);
516
517         if(likely(buffer_strlen(b) == 0))
518             chart_buffered_metrics = 0;
519
520         if(unlikely(netdata_exit)) break;
521     }
522
523 cleanup:
524     if(sock != -1)
525         close(sock);
526
527     buffer_free(b);
528     buffer_free(response);
529
530     info("BACKEND thread exiting");
531
532     static_thread->enabled = 0;
533     pthread_exit(NULL);
534     return NULL;
535 }