-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
output_influx.c
481 lines (420 loc) · 14.2 KB
/
output_influx.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
/** @file
InfluxDB output for rtl_433 events.
Copyright (C) 2019 Daniel Krueger
based on output_mqtt.c
Copyright (C) 2019 Christian Zuckschwerdt
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
*/
// note: our unit header includes unistd.h for gethostname() via data.h
#include "output_influx.h"
#include "optparse.h"
#include "util.h"
#include "fatal.h"
#include "r_util.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include "mongoose.h"
/* InfluxDB client abstraction / printer */
typedef struct {
struct data_output output;
struct mg_mgr *mgr;
struct mg_connection *conn;
int prev_status;
int prev_resp_code;
char hostname[64];
char url[400];
char extra_headers[150];
int databufidxfill;
struct mbuf databufs[2];
} influx_client_t;
static void influx_client_send(influx_client_t *ctx);
static void influx_client_event(struct mg_connection *nc, int ev, void *ev_data)
{
// note that while shutting down the ctx is NULL
influx_client_t *ctx = (influx_client_t *)nc->user_data;
struct http_message *hm = (struct http_message *)ev_data;
switch (ev) {
case MG_EV_CONNECT: {
int connect_status = *(int *)ev_data;
if (connect_status != 0) {
// Error, print only once
if (ctx) {
if (ctx->prev_status != connect_status)
fprintf(stderr, "InfluxDB connect error: %s\n", strerror(connect_status));
ctx->conn = NULL;
}
}
if (ctx)
ctx->prev_status = connect_status;
break;
}
case MG_EV_HTTP_CHUNK: // response is normally empty (so mongoose thinks we received a chunk only)
case MG_EV_HTTP_REPLY:
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
if (hm->resp_code == 204) {
// mark influx data as sent
}
else {
if (ctx && ctx->prev_resp_code != hm->resp_code)
fprintf(stderr, "InfluxDB replied HTTP code: %d with message:\n%s\n", hm->resp_code, hm->body.p);
}
if (ctx) {
ctx->prev_resp_code = hm->resp_code;
}
break;
case MG_EV_CLOSE:
if (ctx) {
ctx->conn = NULL;
influx_client_send(ctx);
}
break;
}
}
static influx_client_t *influx_client_init(influx_client_t *ctx, char const *url, char const *token)
{
strncpy(ctx->url, url, sizeof(ctx->url));
ctx->url[sizeof(ctx->url) - 1] = '\0';
snprintf(ctx->extra_headers, sizeof (ctx->extra_headers), "Authorization: Token %s\r\n", token);
return ctx;
}
static void influx_client_send(influx_client_t *ctx)
{
struct mbuf *buf = &ctx->databufs[ctx->databufidxfill];
/*fprintf(stderr, "Influx %p msg: \"%s\" with %lu/%lu %s\n",
(void*)ctx, buf->buf, buf->len, buf->size,
ctx->conn ? "buffering" : "to be sent");*/
if (ctx->conn || !buf->len)
return;
struct mg_connect_opts opts = {.user_data = ctx};
if ((ctx->conn = mg_connect_http_opt(ctx->mgr, influx_client_event, opts, ctx->url, ctx->extra_headers, buf->buf)) == NULL) {
fprintf(stderr, "Connect to InfluxDB (%s) failed\n", ctx->url);
}
else {
ctx->databufidxfill ^= 1;
buf->len = 0;
*buf->buf = '\0';
}
}
/* Helper */
/// clean the tag/identifier inplace to [-.A-Za-z0-9], esp. not whitespace, =, comma and replace any leading _ by x
static char *influx_sanitize_tag(char *tag, char *end)
{
for (char *p = tag; *p && p != end; ++p)
if (*p != '-' && *p != '.' && (*p < 'A' || *p > 'Z') && (*p < 'a' || *p > 'z') && (*p < '0' || *p > '9'))
*p = '_';
for (char *p = tag; *p && p != end; ++p)
if (*p == '_')
*p = 'x';
else
break;
return tag;
}
/// reserve additional space of size len at end of mbuf a; returns actual free space
static size_t mbuf_reserve(struct mbuf *a, size_t len)
{
// insert undefined values at end of current buffer (it will increase the buffer if necessary)
len = mbuf_insert(a, a->len, NULL, len);
// reduce the buffer length again by actual inserted number of bytes
a->len -= len;
len = a->size - a->len;
if (len)
a->buf[a->len] = '\0';
return len;
}
static char *mbuf_snprintf(struct mbuf *a, char const *format, ...)
#if defined(__GNUC__) || defined(__clang__)
__attribute__((format(printf, 2, 3)))
#endif
;
static char *mbuf_snprintf(struct mbuf *a, char const *format, ...)
{
char *str = &a->buf[a->len];
int size;
va_list ap;
va_start(ap, format);
size = vsnprintf(str, a->size - a->len, format, ap);
va_end(ap);
if (size > 0) {
// vsnprintf might return size larger than actually filled
size_t len = strlen(str);
a->len += len;
}
return str;
}
static void mbuf_remove_part(struct mbuf *a, char *pos, size_t len)
{
if (pos >= a->buf && pos < &a->buf[a->len] && &pos[len] <= &a->buf[a->len]) {
memmove(pos, &pos[len], a->len - (pos - a->buf) - len);
a->len -= len;
}
}
static void R_API_CALLCONV print_influx_array(data_output_t *output, data_array_t *array, char const *format)
{
UNUSED(array);
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
struct mbuf *buf = &influx->databufs[influx->databufidxfill];
mbuf_snprintf(buf, "\"array\""); // TODO
}
static void R_API_CALLCONV print_influx_data_escaped(data_output_t *output, data_t *data, char const *format)
{
char str[1000];
data_print_jsons(data, str, sizeof (str));
output->print_string(output, str, format);
}
static void R_API_CALLCONV print_influx_string_escaped(data_output_t *output, char const *str, char const *format)
{
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
struct mbuf *databuf = &influx->databufs[influx->databufidxfill];
size_t size = databuf->size - databuf->len;
char *buf = &databuf->buf[databuf->len];
if (size < strlen(str) + 3) {
return;
}
*buf++ = '"';
size--;
for (; *str && size >= 3; ++str) {
if (*str == '\r') {
*buf++ = '\\';
size--;
*buf++ = 'r';
size--;
continue;
}
if (*str == '\n') {
*buf++ = '\\';
size--;
*buf++ = 'n';
size--;
continue;
}
if (*str == '\t') {
*buf++ = '\\';
size--;
*buf++ = 't';
size--;
continue;
}
if (*str == '"' || *str == '\\') {
*buf++ = '\\';
size--;
}
*buf++ = *str;
size--;
}
if (size >= 2) {
*buf++ = '"';
size--;
}
*buf = '\0';
databuf->len = databuf->size - size;
}
static void R_API_CALLCONV print_influx_string(data_output_t *output, char const *str, char const *format)
{
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
struct mbuf *buf = &influx->databufs[influx->databufidxfill];
mbuf_snprintf(buf, "%s", str);
}
// Generate InfluxDB line protocol
static void R_API_CALLCONV print_influx_data(data_output_t *output, data_t *data, char const *format)
{
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
char *str;
char *end;
struct mbuf *buf = &influx->databufs[influx->databufidxfill];
bool comma = false;
data_t *data_org = data;
data_t *data_model = NULL;
data_t *data_time = NULL;
for (data_t *d = data; d; d = d->next) {
if (!strcmp(d->key, "model"))
data_model = d;
if (!strcmp(d->key, "time"))
data_time = d;
}
if (!data_model) {
// data isn't from device (maybe report for example)
// use hostname for measurement
mbuf_reserve(buf, 20000);
mbuf_snprintf(buf, "rtl_433_%s", influx->hostname);
}
else {
// use model for measurement
mbuf_reserve(buf, 1000);
str = &buf->buf[buf->len];
print_value(output, data_model->type, data_model->value, data_model->format);
influx_sanitize_tag(str, NULL);
}
// write tags
while (data) {
if (!strcmp(data->key, "model")
|| !strcmp(data->key, "time")) {
// skip
}
else if (!strcmp(data->key, "type")
|| !strcmp(data->key, "subtype")
|| !strcmp(data->key, "id")
|| !strcmp(data->key, "channel")
|| !strcmp(data->key, "mic")) {
str = mbuf_snprintf(buf, ",%s=", data->key);
str++;
end = &buf->buf[buf->len - 1];
influx_sanitize_tag(str, end);
str = end + 1;
print_value(output, data->type, data->value, data->format);
influx_sanitize_tag(str, NULL);
}
data = data->next;
}
mbuf_snprintf(buf, " ");
// activate escaped output functions
influx->output.print_data = print_influx_data_escaped;
influx->output.print_string = print_influx_string_escaped;
// write fields
data = data_org;
while (data) {
if (!strcmp(data->key, "model")
|| !strcmp(data->key, "time")) {
// skip
}
else if (!strcmp(data->key, "type")
|| !strcmp(data->key, "subtype")
|| !strcmp(data->key, "id")
|| !strcmp(data->key, "channel")
|| !strcmp(data->key, "mic")) {
// skip
}
else {
str = mbuf_snprintf(buf, comma ? ",%s=" : "%s=", data->key);
if (comma)
str++;
end = &buf->buf[buf->len - 1];
influx_sanitize_tag(str, end);
str = end + 1;
print_value(output, data->type, data->value, data->format);
comma = true;
}
data = data->next;
}
// restore original output functions
influx->output.print_data = print_influx_data;
influx->output.print_string = print_influx_string;
// write time if available
if (data_time) {
str = mbuf_snprintf(buf, " ");
print_value(output, data_time->type, data_time->value, data_time->format);
if (str[1] == '@' // relative time format configured
|| str[11] == ' ' // date time format configured
|| str[11] == 'T') { // ISO date time format configured
// -> bad, because InfluxDB doesn't under stand those formats -> remove timestamp
buf->len = str - buf->buf;
}
else if ((str = strchr(str, '.'))) {
// unix usec timestamp format configured
mbuf_remove_part(buf, str, 1);
mbuf_snprintf(buf, "000");
}
else {
// unix timestamp with seconds resolution configured
mbuf_snprintf(buf, "000000000");
}
}
mbuf_snprintf(buf, "\n");
influx_client_send(influx);
}
static void R_API_CALLCONV print_influx_double(data_output_t *output, double data, char const *format)
{
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
struct mbuf *buf = &influx->databufs[influx->databufidxfill];
mbuf_snprintf(buf, "%f", data);
}
static void R_API_CALLCONV print_influx_int(data_output_t *output, int data, char const *format)
{
UNUSED(format);
influx_client_t *influx = (influx_client_t *)output;
struct mbuf *buf = &influx->databufs[influx->databufidxfill];
mbuf_snprintf(buf, "%d", data);
}
static void R_API_CALLCONV data_output_influx_free(data_output_t *output)
{
influx_client_t *influx = (influx_client_t *)output;
if (!influx)
return;
// remove ctx from our connections
if (influx->conn) {
influx->conn->user_data = NULL;
influx->conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
free(influx);
}
struct data_output *data_output_influx_create(struct mg_mgr *mgr, char *opts)
{
influx_client_t *influx = calloc(1, sizeof(influx_client_t));
if (!influx) {
FATAL_CALLOC("data_output_influx_create()");
}
gethostname(influx->hostname, sizeof(influx->hostname) - 1);
influx->hostname[sizeof(influx->hostname) - 1] = '\0';
// only use hostname, not domain part
char *dot = strchr(influx->hostname, '.');
if (dot)
*dot = '\0';
influx_sanitize_tag(influx->hostname, NULL);
char *token = NULL;
// param/opts starts with URL
char *url = opts;
opts = strchr(opts, ',');
if (opts) {
*opts = '\0';
opts++;
}
if (strncmp(url, "influx", 6) == 0) {
url += 2;
memcpy(url, "http", 4);
}
// check if valid URL has been provided
struct mg_str host, path, query;
if (mg_parse_uri(mg_mk_str(url), NULL, NULL, &host, NULL, &path,
&query, NULL) != 0
|| !host.len || !path.len || !query.len) {
fprintf(stderr, "Invalid URL to InfluxDB specified.%s%s%s\n"
"Something like \"influx://<host>/write?org=<org>&bucket=<bucket>\" required at least.\n",
!host.len ? " No host specified." : "",
!path.len ? " No path component specified." : "",
!query.len ? " No query parameters specified." : "");
exit(1);
}
// parse auth and format options
char *key, *val;
while (getkwargs(&opts, &key, &val)) {
key = remove_ws(key);
val = trim_ws(val);
if (!key || !*key)
continue;
else if (!strcasecmp(key, "t") || !strcasecmp(key, "token"))
token = val;
else {
fprintf(stderr, "Invalid key \"%s\" option.\n", key);
exit(1);
}
}
influx->output.print_data = print_influx_data;
influx->output.print_array = print_influx_array;
influx->output.print_string = print_influx_string;
influx->output.print_double = print_influx_double;
influx->output.print_int = print_influx_int;
influx->output.output_free = data_output_influx_free;
fprintf(stderr, "Publishing data to InfluxDB (%s)\n", url);
influx->mgr = mgr;
influx_client_init(influx, url, token);
return &influx->output;
}