]> mj.ucw.cz Git - home-hw.git/blob - prometheus/burrow-prometheus.c
51de6ba7786691f3500e200a85081626e1604aef
[home-hw.git] / prometheus / burrow-prometheus.c
1 /*
2  *      A gateway between MQTT and Prometheus
3  *
4  *      (c) 2018 Martin Mares <mj@ucw.cz>
5  */
6
7 #include <ucw/lib.h>
8 #include <ucw/fastbuf.h>
9 #include <ucw/log.h>
10 #include <ucw/mempool.h>
11 #include <ucw/opt.h>
12 #include <ucw/string.h>
13
14 #include <netinet/in.h>
15 #include <pthread.h>
16 #include <stdarg.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/poll.h>
21 #include <sys/socket.h>
22 #include <syslog.h>
23 #include <time.h>
24 #include <unistd.h>
25
26 #include <mosquitto.h>
27
28 #define MEASUREMENT_TIMEOUT 120
29
30 static struct mosquitto *mosq;
31
32 struct attr {
33         const char *metric;
34         const char *help;
35         const char *type;
36         const char *topic;
37 };
38
39 static const struct attr attr_table[] = {
40         {
41                 .metric = "temp_loft",
42                 .help = "Temperature in the loft [degC]",
43                 .type = "gauge",
44                 .topic = "burrow/temp/loft",
45         },
46         {
47                 .metric = "loft_fan",
48                 .help = "Fan speed in the loft (0-3)",
49                 .type = "gauge",
50                 .topic = "burrow/loft/fan"
51         },
52         {
53                 .metric = "loft_circ",
54                 .help = "Warm water circulation (0-1)",
55                 .type = "gauge",
56                 .topic = "burrow/loft/circulation"
57         },
58         {
59                 .metric = "temp_ursarium",
60                 .help = "Temperature in the Ursarium [degC]",
61                 .type = "gauge",
62                 .topic = "burrow/temp/ursarium"
63         },
64         {
65                 .metric = "temp_catarium",
66                 .help = "Temperature in the Catarium [degC]",
67                 .type = "gauge",
68                 .topic = "burrow/temp/catarium"
69         },
70         {
71                 .metric = "temp_garage",
72                 .help = "Temperature in the garage [degC]",
73                 .type = "gauge",
74                 .topic = "burrow/temp/garage"
75         },
76         {
77                 .metric = "temp_kitchen",
78                 .help = "Temperature in the kitchen [degC]",
79                 .type = "gauge",
80                 .topic = "burrow/temp/kitchen"
81         },
82         {
83                 .metric = "rh_ursarium",
84                 .help = "Relative humidity in the Ursarium [%]",
85                 .type = "gauge",
86                 .topic = "burrow/temp/ursarium-rh"
87         },
88         {
89                 .metric = "temp_catarium_clock",
90                 .help = "Temperature on Catarium clock [degC]",
91                 .type = "gauge",
92                 .topic = "burrow/temp/clock"
93         },
94         {
95                 .metric = "press_catarium_clock",
96                 .help = "Pressure on Catarium clock [Pa]",
97                 .type = "gauge",
98                 .topic = "burrow/pressure/clock"
99         },
100         {
101                 .metric = "air_inside_intake",
102                 .help = "Temperature of air intake from inside [degC]",
103                 .type = "gauge",
104                 .topic = "burrow/air/inside-intake",
105         },
106         {
107                 .metric = "air_inside_exhaust",
108                 .help = "Temperature of air exhaust to inside [degC]",
109                 .type = "gauge",
110                 .topic = "burrow/air/inside-exhaust",
111         },
112         {
113                 .metric = "air_outside_intake",
114                 .help = "Temperature of air intake from outside [degC]",
115                 .type = "gauge",
116                 .topic = "burrow/air/outside-intake",
117         },
118         {
119                 .metric = "air_outside_exhaust",
120                 .help = "Temperature of air exhaust to outside [degC]",
121                 .type = "gauge",
122                 .topic = "burrow/air/outside-exhaust",
123         },
124         {
125                 .metric = "air_chilled",
126                 .help = "Temperature of chilled air [degC]",
127                 .type = "gauge",
128                 .topic = "burrow/air/chilled",
129         },
130         {
131                 .metric = "air_bypass",
132                 .help = "Heat exchanger bypass (0-1)",
133                 .type = "gauge",
134                 .topic = "burrow/air/bypass"
135         },
136 };
137
138 static char *attr_values[ARRAY_SIZE(attr_table)];
139 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
140
141 static void mqtt_publish(const char *topic, const char *fmt, ...)
142 {
143         va_list args;
144         va_start(args, fmt);
145         char m[256];
146         int l = vsnprintf(m, sizeof(m), fmt, args);
147         if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
148                 msg(L_ERROR, "Mosquitto: publish failed");
149         va_end(args);
150 }
151
152 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
153 {
154         if (!status) {
155                 msg(L_DEBUG, "MQTT: Connection established, subscribing");
156                 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
157                         die("Mosquitto: subscribe failed");
158
159                 mqtt_publish("status/prometheus", "ok");
160         }
161 }
162
163 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
164 {
165         // msg(L_INFO, "MQTT(%d): %s", level, message);
166 }
167
168 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
169 {
170         char val[256];
171         if (m->payloadlen >= sizeof(val) - 1) {
172                 msg(L_ERROR, "Invalid value for topic %s", m->topic);
173                 return;
174         }
175         memcpy(val, m->payload, m->payloadlen);
176         val[m->payloadlen] = 0;
177         msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
178
179         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
180                 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
181                         pthread_mutex_lock(&attr_mutex);
182                         if (attr_values[i]) {
183                                 xfree(attr_values[i]);
184                                 attr_values[i] = NULL;
185                         }
186                         if (val[0])
187                                 attr_values[i] = xstrdup(val);
188                         pthread_mutex_unlock(&attr_mutex);
189                 }
190         }
191 }
192
193 struct http {
194         struct mempool *mp;
195         int sk;
196         char *iobuf;
197         uint iobuf_pos, iobuf_max;
198         char *linebuf;
199         struct fbpool fbpool;
200 };
201
202 #define IO_TIMEOUT 60000        // in ms
203 #define IOBUF_SIZE 1024
204 #define LINEBUF_SIZE 1024
205
206 static void http_send(struct http *http)
207 {
208         byte *buf = fbpool_end(&http->fbpool);
209         uint len = mp_size(http->mp, buf);
210
211         while (len) {
212                 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
213                 int res = poll(&pfd, 1, IO_TIMEOUT);
214                 if (res < 0)
215                         die("Poll failed: %m");
216                 if (!res) {
217                         msg(L_ERROR, "HTTP write timed out");
218                         return;
219                 }
220
221                 res = write(http->sk, buf, len);
222                 if (res < 0) {
223                         msg(L_ERROR, "HTTP write failed: %m");
224                         return;
225                 }
226                 buf += res;
227                 len -= res;
228         }
229 }
230
231 static void http_error(struct http *http, const char *err)
232 {
233         msg(L_INFO, "HTTP error: %s", err);
234         fbpool_start(&http->fbpool, http->mp, 0);
235         bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
236         http_send(http);
237 }
238
239 static int http_get_char(struct http *http) {
240         if (http->iobuf_pos >= http->iobuf_max) {
241                 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
242                 int res = poll(&pfd, 1, IO_TIMEOUT);
243                 if (res < 0)
244                         die("Poll failed: %m");
245                 if (!res) {
246                         msg(L_ERROR, "HTTP read timed out");
247                         return -1;
248                 }
249                 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
250                 if (len < 0) {
251                         msg(L_ERROR, "HTTP read error: %m");
252                         return -1;
253                 }
254                 if (!len) {
255                         msg(L_ERROR, "HTTP connection closed");
256                         return -1;
257                 }
258                 http->iobuf_pos = 0;
259                 http->iobuf_max = len;
260         }
261         return http->iobuf[http->iobuf_pos++];
262 }
263
264 static bool http_get_line(struct http *http)
265 {
266         uint i = 0;
267         for (;;) {
268                 int c = http_get_char(http);
269                 if (c < 0)
270                         return false;
271                 if (c == '\n') {
272                         if (i > 0 && http->linebuf[i-1] == '\r')
273                                 i--;
274                         http->linebuf[i] = 0;
275                         return true;
276                 }
277                 if (i >= IOBUF_SIZE-1) {
278                         http_error(http, "400 Line too long");
279                         return false;
280                 }
281                 http->linebuf[i++] = c;
282         }
283 }
284
285 static void http_answer(struct fastbuf *fb)
286 {
287         char val[256], *w[2];
288         time_t now = time(NULL);
289
290         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
291                 const struct attr *a = &attr_table[i];
292
293                 pthread_mutex_lock(&attr_mutex);
294                 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
295                 pthread_mutex_unlock(&attr_mutex);
296
297                 if (!val[0])
298                         continue;
299                 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
300                 if (fields < 1)
301                         continue;
302                 if (fields >= 2) {
303                         time_t t = atoll(w[1]);
304                         if (t < now - MEASUREMENT_TIMEOUT)
305                                 continue;
306                 }
307
308                 if (a->help)
309                         bprintf(fb, "# HELP %s %s\n", a->metric, a->help);
310                 if (a->type)
311                         bprintf(fb, "# TYPE %s %s\n", a->metric, a->type);
312                 bprintf(fb, "%s %s", a->metric, val);
313 #if 0
314                 // Prometheus does not like our timestamps -- why?
315                 if (fields >= 2)
316                         bprintf(fb, " %s", w[1]);
317 #endif
318                 bputc(fb, '\n');
319         }
320 }
321
322 static void http_connection(struct http *http)
323 {
324         http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
325         http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
326         fbpool_init(&http->fbpool);
327
328         if (!http_get_line(http))
329                 return;
330         // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
331         char *words[3];
332         if (str_wordsplit(http->linebuf, words, 3) != 3) {
333                 http_error(http, "400 Invalid request line");
334                 return;
335         }
336         if (strcmp(words[0], "GET")) {
337                 http_error(http, "501 Method not implemented");
338                 return;
339         }
340
341         for (;;) {
342                 if (!http_get_line(http))
343                         return;
344                 if (!http->linebuf[0])
345                         break;
346                 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
347         }
348
349         fbpool_start(&http->fbpool, http->mp, 0);
350         struct fastbuf *fb = &http->fbpool.fb;
351         bprintf(fb, "HTTP/1.1 200 OK\r\n");
352         bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
353         bprintf(fb, "\r\n");
354         http_answer(fb);
355         http_send(http);
356 }
357
358 static int use_daemon;
359 static int use_debug;
360
361 static struct opt_section options = {
362         OPT_ITEMS {
363                 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
364                 OPT_HELP(""),
365                 OPT_HELP("Options:"),
366                 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
367                 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
368                 OPT_HELP_OPTION,
369                 OPT_CONF_OPTIONS,
370                 OPT_END
371         }
372 };
373
374 int main(int argc UNUSED, char **argv)
375 {
376         log_init(argv[0]);
377         opt_parse(&options, argv+1);
378
379         if (use_daemon) {
380                 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
381                 log_set_default_stream(ls);
382         }
383         if (!use_debug)
384                 log_default_stream()->levels &= ~(1U << L_DEBUG);
385
386         mosquitto_lib_init();
387         mosq = mosquitto_new("prometheus", 1, NULL);
388         if (!mosq)
389                 die("Mosquitto: initialization failed");
390
391         mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
392         mosquitto_log_callback_set(mosq, mqtt_log_callback);
393         mosquitto_message_callback_set(mosq, mqtt_msg_callback);
394
395         if (mosquitto_will_set(mosq, "status/prometheus", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
396                 die("Mosquitto: unable to set will");
397
398         if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
399                 die("Mosquitto: connect failed");
400
401         if (mosquitto_loop_start(mosq))
402                 die("Mosquitto: cannot start service thread");
403
404         int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
405         if (listen_sk < 0)
406                 die("Cannot create listening socket: %m");
407
408         int one = 1;
409         if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
410                 die("Cannot set SO_REUSEADDR: %m");
411
412         struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
413         if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
414                 die("Cannot bind listening socket: %m");
415
416         if (listen(listen_sk, 64) < 0)
417                 die("Cannot listen: %m");
418
419         for (;;) {
420                 int sk = accept(listen_sk, NULL, NULL);
421                 if (sk < 0) {
422                         msg(L_ERROR, "HTTP accept failed: %m");
423                         continue;
424                 }
425                 msg(L_DEBUG, "HTTP accepted connection");
426                 struct mempool *mp = mp_new(4096);
427                 struct http *http = mp_alloc_zero(mp, sizeof(*http));
428                 http->mp = mp;
429                 http->sk = sk;
430                 http_connection(http);
431                 mp_delete(mp);
432                 close(sk);
433         }
434 }