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