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