]> arthur.barton.de Git - netdata.git/blob - src/backends.c
dequeue backends responses from the socket; #1432
[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 - after < st->update_every && after != after - after % st->update_every))
12         // when st->update_every is bigger than the frequency we send data to backend
13         // skip the iterations that are not aligned to the database
14         return NAN;
15
16     // align the time-frame
17     // for 'after' also skip the first value by adding st->update_every
18     after  = after  - after  % st->update_every + st->update_every;
19     before = before - before % st->update_every;
20
21     if(unlikely(after < first_t))
22         after = first_t;
23
24     if(unlikely(after > before))
25         // this can happen when the st->update_every > before - after
26         before = after;
27
28     if(unlikely(before > last_t))
29         before = last_t;
30
31     size_t counter = 0;
32     calculated_number sum = 0;
33
34     long    start_at_slot = rrdset_time2slot(st, before),
35             stop_at_slot  = rrdset_time2slot(st, after),
36             slot, stop_now = 0;
37
38     for(slot = start_at_slot; !stop_now ; slot--) {
39         if(unlikely(slot < 0)) slot = st->entries - 1;
40         if(unlikely(slot == stop_at_slot)) stop_now = 1;
41
42         storage_number n = rd->values[slot];
43         if(unlikely(!does_storage_number_exist(n))) continue;
44
45         calculated_number value = unpack_storage_number(n);
46         sum += value;
47         counter++;
48     }
49
50     if(unlikely(!counter))
51         return NAN;
52
53     if(unlikely(options & BACKEND_SOURCE_DATA_SUM))
54         return sum;
55
56     return sum / (calculated_number)counter;
57 }
58
59 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) {
60     (void)host;
61     (void)after;
62     (void)before;
63     (void)options;
64     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);
65     return 1;
66 }
67
68 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     (void)host;
70     calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
71     if(!isnan(value)) {
72         buffer_sprintf(b, "%s.%s.%s.%s " CALCULATED_NUMBER_FORMAT " %u\n", prefix, hostname, st->id, rd->id, value, (uint32_t) before);
73         return 1;
74     }
75     return 0;
76 }
77
78 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) {
79     (void)host;
80     (void)after;
81     (void)before;
82     (void)options;
83     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);
84     return 1;
85 }
86
87 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     (void)host;
89     calculated_number value = backend_calculate_value_from_stored_data(st, rd, after, before, options);
90     if(!isnan(value)) {
91         buffer_sprintf(b, "put %s.%s.%s %u " CALCULATED_NUMBER_FORMAT " host=%s\n", prefix, st->id, rd->id, (uint32_t) before, value, hostname);
92         return 1;
93     }
94     return 0;
95 }
96
97 static inline int process_graphite_response(BUFFER *b) {
98     info("Received %zu bytes from graphite backend. Ignoring them.", buffer_strlen(b));
99     buffer_flush(b);
100     return 0;
101 }
102
103 static inline int process_opentsdb_response(BUFFER *b) {
104     info("Received %zu bytes from opentsdb backend. Ignoring them.", buffer_strlen(b));
105     buffer_flush(b);
106     return 0;
107 }
108
109 void *backends_main(void *ptr) {
110     (void)ptr;
111
112     BUFFER *b = buffer_create(1), *response = buffer_create(1);
113     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;
114     int (*backend_response_checker)(BUFFER *b) = NULL;
115
116     info("BACKEND thread created with task id %d", gettid());
117
118     if(pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL) != 0)
119         error("Cannot set pthread cancel type to DEFERRED.");
120
121     if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL) != 0)
122         error("Cannot set pthread cancel state to ENABLE.");
123
124     // ------------------------------------------------------------------------
125     // collect configuration options
126
127     struct timeval timeout = {
128             .tv_sec = 0,
129             .tv_usec = 0
130     };
131     int default_port = 0;
132     int sock = -1;
133     uint32_t options;
134     int enabled = config_get_boolean("backend", "enabled", 0);
135     const char *source = config_get("backend", "data source", "average");
136     const char *type = config_get("backend", "type", "graphite");
137     const char *destination = config_get("backend", "destination", "localhost");
138     const char *prefix = config_get("backend", "prefix", "netdata");
139     const char *hostname = config_get("backend", "hostname", localhost.hostname);
140     int frequency = (int)config_get_number("backend", "update every", 10);
141     int buffer_on_failures = (int)config_get_number("backend", "buffer on failures", 10);
142     long timeoutms = config_get_number("backend", "timeout ms", frequency * 2 * 1000);
143
144     // ------------------------------------------------------------------------
145     // validate configuration options
146     // and prepare for sending data to our backend
147     if(!enabled || frequency < 1)
148         goto cleanup;
149
150     if(!strcmp(source, "as collected")) {
151         options = BACKEND_SOURCE_DATA_AS_COLLECTED;
152     }
153     else if(!strcmp(source, "average")) {
154         options = BACKEND_SOURCE_DATA_AVERAGE;
155     }
156     else if(!strcmp(source, "sum") || !strcmp(source, "volume")) {
157         options = BACKEND_SOURCE_DATA_SUM;
158     }
159     else {
160         error("Invalid data source method '%s' for backend given. Disabling backed.", source);
161         goto cleanup;
162     }
163
164     if(!strcmp(type, "graphite") || !strcmp(type, "graphite:plaintext")) {
165         default_port = 2003;
166         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
167             backend_request_formatter = format_dimension_collected_graphite_plaintext;
168         else
169             backend_request_formatter = format_dimension_stored_graphite_plaintext;
170
171         backend_response_checker = process_graphite_response;
172     }
173     else if(!strcmp(type, "opentsdb") || !strcmp(type, "opentsdb:telnet")) {
174         default_port = 4242;
175         if(options == BACKEND_SOURCE_DATA_AS_COLLECTED)
176             backend_request_formatter = format_dimension_collected_opentsdb_telnet;
177         else
178             backend_request_formatter = format_dimension_stored_opentsdb_telnet;
179
180         backend_response_checker = process_opentsdb_response;
181     }
182     else {
183         error("Unknown backend type '%s'", type);
184         goto cleanup;
185     }
186
187     if(backend_request_formatter == NULL || backend_response_checker == NULL) {
188         error("backend is misconfigured - disabling it.");
189         goto cleanup;
190     }
191
192     if(timeoutms < 1) {
193         error("BACKED invalid timeout %ld ms given. Assuming %d ms.", timeoutms, frequency * 2 * 1000);
194         timeoutms = frequency * 2 * 1000;
195     }
196     timeout.tv_sec  = (timeoutms * 1000) / 1000000;
197     timeout.tv_usec = (timeoutms * 1000) % 1000000;
198
199     // ------------------------------------------------------------------------
200     // prepare the charts for monitoring the backend
201
202     struct rusage thread;
203
204     collected_number
205             chart_buffered_metrics = 0,
206             chart_lost_metrics = 0,
207             chart_sent_metrics = 0,
208             chart_buffered_bytes = 0,
209             chart_sent_bytes = 0,
210             chart_transmission_successes = 0,
211             chart_transmission_failures = 0,
212             chart_data_lost_events = 0,
213             chart_lost_bytes = 0,
214             chart_backend_reconnects = 0,
215             chart_backend_latency = 0;
216
217     RRDSET *chart_metrics = rrdset_find("netdata.backend_metrics");
218     if(!chart_metrics) {
219         chart_metrics = rrdset_create("netdata", "backend_metrics", NULL, "backend", NULL, "Netdata Buffered Metrics", "metrics", 130600, frequency, RRDSET_TYPE_LINE);
220         rrddim_add(chart_metrics, "buffered", NULL,   1, 1, RRDDIM_ABSOLUTE);
221         rrddim_add(chart_metrics, "lost",     NULL,   1, 1, RRDDIM_ABSOLUTE);
222         rrddim_add(chart_metrics, "sent",     NULL,   1, 1, RRDDIM_ABSOLUTE);
223     }
224
225     RRDSET *chart_bytes = rrdset_find("netdata.backend_bytes");
226     if(!chart_bytes) {
227         chart_bytes = rrdset_create("netdata", "backend_bytes", NULL, "backend", NULL, "Netdata Backend Data Size", "KB", 130610, frequency, RRDSET_TYPE_AREA);
228         rrddim_add(chart_bytes, "buffered", NULL,  1, 1024, RRDDIM_ABSOLUTE);
229         rrddim_add(chart_bytes, "lost",     NULL,  1, 1024, RRDDIM_ABSOLUTE);
230         rrddim_add(chart_bytes, "sent",     NULL,  1, 1024, RRDDIM_ABSOLUTE);
231     }
232
233     RRDSET *chart_ops = rrdset_find("netdata.backend_ops");
234     if(!chart_ops) {
235         chart_ops = rrdset_create("netdata", "backend_ops", NULL, "backend", NULL, "Netdata Backend Operations", "operations", 130630, frequency, RRDSET_TYPE_LINE);
236         rrddim_add(chart_ops, "write",     NULL,  1, 1, RRDDIM_ABSOLUTE);
237         rrddim_add(chart_ops, "discard",   NULL,  1, 1, RRDDIM_ABSOLUTE);
238         rrddim_add(chart_ops, "reconnect", NULL,  1, 1, RRDDIM_ABSOLUTE);
239         rrddim_add(chart_ops, "failure",   NULL,  1, 1, RRDDIM_ABSOLUTE);
240     }
241
242     RRDSET *chart_latency = rrdset_find("netdata.backend_latency");
243     if(!chart_latency) {
244         chart_latency = rrdset_create("netdata", "backend_latency", NULL, "backend", NULL, "Netdata Backend Latency", "ms", 130620, frequency, RRDSET_TYPE_AREA);
245         rrddim_add(chart_latency, "latency",   NULL,  1, 1000, RRDDIM_ABSOLUTE);
246     }
247
248     RRDSET *chart_rusage = rrdset_find("netdata.backend_thread_cpu");
249     if(!chart_rusage) {
250         chart_rusage = rrdset_create("netdata", "backend_thread_cpu", NULL, "backend", NULL, "NetData Backend Thread CPU usage", "milliseconds/s", 130630, frequency, RRDSET_TYPE_STACKED);
251         rrddim_add(chart_rusage, "user",   NULL, 1, 1000, RRDDIM_INCREMENTAL);
252         rrddim_add(chart_rusage, "system", NULL, 1, 1000, RRDDIM_INCREMENTAL);
253     }
254
255     // ------------------------------------------------------------------------
256     // prepare the backend main loop
257
258     info("BACKEND configured ('%s' on '%s' sending '%s' data, every %d seconds, as host '%s', with prefix '%s')", type, destination, source, frequency, hostname, prefix);
259
260     usec_t step_ut = frequency * USEC_PER_SEC;
261     usec_t random_ut = now_realtime_usec() % (step_ut / 2);
262     time_t before = (time_t)((now_realtime_usec() - step_ut) / USEC_PER_SEC);
263     time_t after = before;
264     int failures = 0;
265
266     for(;;) {
267         // ------------------------------------------------------------------------
268         // wait for the next iteration point
269
270         usec_t now_ut = now_realtime_usec();
271         usec_t next_ut = now_ut - (now_ut % step_ut) + step_ut;
272         before = (time_t)(next_ut / USEC_PER_SEC);
273
274         // add a little delay (1/4 of the step) plus some randomness
275         next_ut += (step_ut / 4) + random_ut;
276
277         while(now_ut < next_ut) {
278             sleep_usec(next_ut - now_ut);
279             now_ut = now_realtime_usec();
280         }
281
282         // ------------------------------------------------------------------------
283         // add to the buffer the data we need to send to the backend
284
285         RRDSET *st;
286         int pthreadoldcancelstate;
287
288         if(unlikely(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &pthreadoldcancelstate) != 0))
289             error("Cannot set pthread cancel state to DISABLE.");
290
291         rrdhost_rdlock(&localhost);
292         for(st = localhost.rrdset_root; st ;st = st->next) {
293             pthread_rwlock_rdlock(&st->rwlock);
294
295             RRDDIM *rd;
296             for(rd = st->dimensions; rd ;rd = rd->next) {
297                 if(rd->last_collected_time.tv_sec >= after)
298                     chart_buffered_metrics += backend_request_formatter(b, prefix, &localhost, hostname, st, rd, after, before, options);
299             }
300
301             pthread_rwlock_unlock(&st->rwlock);
302         }
303         rrdhost_unlock(&localhost);
304
305         if(unlikely(pthread_setcancelstate(pthreadoldcancelstate, NULL) != 0))
306             error("Cannot set pthread cancel state to RESTORE (%d).", pthreadoldcancelstate);
307
308         // ------------------------------------------------------------------------
309
310         chart_buffered_bytes = (collected_number)buffer_strlen(b);
311
312         // reset the monitoring chart counters
313         chart_sent_bytes =
314         chart_sent_metrics =
315         chart_lost_metrics =
316         chart_transmission_successes =
317         chart_transmission_failures =
318         chart_data_lost_events =
319         chart_lost_bytes =
320         chart_backend_reconnects =
321         chart_backend_latency = 0;
322
323         if(unlikely(netdata_exit)) break;
324
325         //fprintf(stderr, "\nBACKEND BEGIN:\n%s\nBACKEND END\n", buffer_tostring(b)); // FIXME
326         //fprintf(stderr, "after = %lu, before = %lu\n", after, before);
327
328         // ------------------------------------------------------------------------
329         // if we are connected, receive a response, without blocking
330
331         if(likely(sock != -1)) {
332             if(likely(fcntl(sock, F_SETFL, O_NONBLOCK) >= 0)) {
333                 errno = 0;
334
335                 // loop through to collect all data
336                 while(sock != -1 && errno != EWOULDBLOCK) {
337                     buffer_need_bytes(response, 4096);
338
339                     ssize_t r = recv(sock, &response->buffer[response->len], response->size - response->len
340                                      , O_NONBLOCK);
341                     if(likely(r > 0)) {
342                         // we received some data
343                         response->len += r;
344                     }
345                     else if(r == 0) {
346                         error("Backend '%s' closed the socket", destination);
347                         close(sock);
348                         sock = -1;
349                     }
350                     else {
351                         // failed to receive data
352                         if(errno != EAGAIN && errno != EWOULDBLOCK)
353                             error("Cannot receive data from backend '%s'.", destination);
354                     }
355                 }
356
357                 if(sock != -1) {
358                     // unset O_NONBLOCK
359                     int val = fcntl(sock, F_GETFL, 0);
360                     if(likely(val >= 0)) {
361                         int flags = O_NONBLOCK;
362                         val &= ~flags;
363                         if(unlikely(fcntl(sock, F_SETFL, val) < 0))
364                             error("Cannot unset O_NONBLOCK from backend's '%s' socket.", destination);
365                     }
366                     else
367                         error("Cannot get active flags from backend's '%s' socket.", destination);
368                 }
369
370                 // if we received data, process them
371                 if(buffer_strlen(response))
372                     backend_response_checker(response);
373             }
374             else {
375                 error("Cannot set O_NONBLOCK from backend's '%s' socket. Receiving data from backend skipped.", destination);
376             }
377         }
378
379         // ------------------------------------------------------------------------
380         // if we are not connected, connect to a backend server
381
382         if(unlikely(sock == -1)) {
383             usec_t start_ut = now_realtime_usec();
384             const char *s = destination;
385             while(*s) {
386                 const char *e = s;
387
388                 // skip separators, moving both s(tart) and e(nd)
389                 while(isspace(*e) || *e == ',') s = ++e;
390
391                 // move e(nd) to the first separator
392                 while(*e && !isspace(*e) && *e != ',') e++;
393
394                 // is there anything?
395                 if(!*s || s == e) break;
396
397                 char buf[e - s + 1];
398                 strncpyz(buf, s, e - s);
399                 chart_backend_reconnects++;
400                 sock = connect_to(buf, default_port, &timeout);
401                 if(sock != -1) break;
402                 s = e;
403             }
404             chart_backend_latency += now_realtime_usec() - start_ut;
405         }
406
407         if(unlikely(netdata_exit)) break;
408
409         // ------------------------------------------------------------------------
410         // if we are connected, send our buffer to the backend server
411
412         if(likely(sock != -1)) {
413             size_t len = buffer_strlen(b);
414             usec_t start_ut = now_realtime_usec();
415             int flags = 0;
416 #ifdef MSG_NOSIGNAL
417             flags += MSG_NOSIGNAL;
418 #endif
419
420             ssize_t written = send(sock, buffer_tostring(b), len, flags);
421             chart_backend_latency += now_realtime_usec() - start_ut;
422             if(written != -1 && (size_t)written == len) {
423                 // we sent the data successfully
424                 chart_transmission_successes++;
425                 chart_sent_bytes += written;
426                 chart_sent_metrics = chart_buffered_metrics;
427
428                 // reset the failures count
429                 failures = 0;
430
431                 // empty the buffer
432                 buffer_flush(b);
433             }
434             else {
435                 // oops! we couldn't send (all or some of the) data
436                 error("Failed to write data to database backend '%s'. Willing to write %zu bytes, wrote %zd bytes. Will re-connect.", destination, len, written);
437                 chart_transmission_failures++;
438
439                 if(written != -1)
440                     chart_sent_bytes += written;
441
442                 // increment the counter we check for data loss
443                 failures++;
444
445                 // close the socket - we will re-open it next time
446                 close(sock);
447                 sock = -1;
448             }
449
450             // either the buffer is empty
451             // or is holding the data we couldn't send
452             // so, make sure the next iteration will continue
453             // from where we are now
454             after = before;
455         }
456         else {
457             error("Failed to update database backend '%s'", destination);
458             chart_transmission_failures++;
459
460             // increment the counter we check for data loss
461             failures++;
462         }
463
464         if(failures > buffer_on_failures) {
465             // too bad! we are going to lose data
466             chart_lost_bytes += buffer_strlen(b);
467             error("Reached %d backend failures. Flushing buffers to protect this host - this results in data loss on back-end server '%s'", failures, destination);
468             buffer_flush(b);
469             failures = 0;
470             chart_data_lost_events++;
471             chart_lost_metrics = chart_buffered_metrics;
472         }
473
474         if(unlikely(netdata_exit)) break;
475
476         // ------------------------------------------------------------------------
477         // update the monitoring charts
478
479         if(chart_ops->counter_done) rrdset_next(chart_ops);
480         rrddim_set(chart_ops, "write",        chart_transmission_successes);
481         rrddim_set(chart_ops, "discard",      chart_data_lost_events);
482         rrddim_set(chart_ops, "failure",      chart_transmission_failures);
483         rrddim_set(chart_ops, "reconnect",    chart_backend_reconnects);
484         rrdset_done(chart_ops);
485
486         if(chart_metrics->counter_done) rrdset_next(chart_metrics);
487         rrddim_set(chart_metrics, "buffered", chart_buffered_metrics);
488         rrddim_set(chart_metrics, "lost",     chart_lost_metrics);
489         rrddim_set(chart_metrics, "sent",     chart_sent_metrics);
490         rrdset_done(chart_metrics);
491
492         if(chart_bytes->counter_done) rrdset_next(chart_bytes);
493         rrddim_set(chart_bytes, "buffered",   chart_buffered_bytes);
494         rrddim_set(chart_bytes, "lost",       chart_lost_bytes);
495         rrddim_set(chart_bytes, "sent",       chart_sent_bytes);
496         rrdset_done(chart_bytes);
497
498         if(chart_latency->counter_done) rrdset_next(chart_latency);
499         rrddim_set(chart_latency, "latency",  chart_backend_latency);
500         rrdset_done(chart_latency);
501
502         getrusage(RUSAGE_THREAD, &thread);
503         if(chart_rusage->counter_done) rrdset_next(chart_rusage);
504         rrddim_set(chart_rusage, "user",   thread.ru_utime.tv_sec * 1000000ULL + thread.ru_utime.tv_usec);
505         rrddim_set(chart_rusage, "system", thread.ru_stime.tv_sec * 1000000ULL + thread.ru_stime.tv_usec);
506         rrdset_done(chart_rusage);
507
508         if(likely(buffer_strlen(b) == 0))
509             chart_buffered_metrics = 0;
510
511         if(unlikely(netdata_exit)) break;
512     }
513
514 cleanup:
515     if(sock != -1)
516         close(sock);
517
518     buffer_free(b);
519     buffer_free(response);
520
521     info("BACKEND thread exiting");
522
523     pthread_exit(NULL);
524     return NULL;
525 }