]> mj.ucw.cz Git - home-hw.git/blob - prometheus/burrow-prometheus.c
Prometheus: Experimental air temperature gauges
[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
132 static char *attr_values[ARRAY_SIZE(attr_table)];
133 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
134
135 static void mqtt_publish(const char *topic, const char *fmt, ...)
136 {
137         va_list args;
138         va_start(args, fmt);
139         char m[256];
140         int l = vsnprintf(m, sizeof(m), fmt, args);
141         if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
142                 msg(L_ERROR, "Mosquitto: publish failed");
143         va_end(args);
144 }
145
146 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
147 {
148         if (!status) {
149                 msg(L_DEBUG, "MQTT: Connection established, subscribing");
150                 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
151                         die("Mosquitto: subscribe failed");
152
153                 mqtt_publish("status/prometheus", "ok");
154         }
155 }
156
157 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
158 {
159         // msg(L_INFO, "MQTT(%d): %s", level, message);
160 }
161
162 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
163 {
164         char val[256];
165         if (m->payloadlen >= sizeof(val) - 1) {
166                 msg(L_ERROR, "Invalid value for topic %s", m->topic);
167                 return;
168         }
169         memcpy(val, m->payload, m->payloadlen);
170         val[m->payloadlen] = 0;
171         msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
172
173         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
174                 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
175                         pthread_mutex_lock(&attr_mutex);
176                         if (attr_values[i]) {
177                                 xfree(attr_values[i]);
178                                 attr_values[i] = NULL;
179                         }
180                         if (val[0])
181                                 attr_values[i] = xstrdup(val);
182                         pthread_mutex_unlock(&attr_mutex);
183                 }
184         }
185 }
186
187 struct http {
188         struct mempool *mp;
189         int sk;
190         char *iobuf;
191         uint iobuf_pos, iobuf_max;
192         char *linebuf;
193         struct fbpool fbpool;
194 };
195
196 #define IO_TIMEOUT 60000        // in ms
197 #define IOBUF_SIZE 1024
198 #define LINEBUF_SIZE 1024
199
200 static void http_send(struct http *http)
201 {
202         byte *buf = fbpool_end(&http->fbpool);
203         uint len = mp_size(http->mp, buf);
204
205         while (len) {
206                 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
207                 int res = poll(&pfd, 1, IO_TIMEOUT);
208                 if (res < 0)
209                         die("Poll failed: %m");
210                 if (!res) {
211                         msg(L_ERROR, "HTTP write timed out");
212                         return;
213                 }
214
215                 res = write(http->sk, buf, len);
216                 if (res < 0) {
217                         msg(L_ERROR, "HTTP write failed: %m");
218                         return;
219                 }
220                 buf += res;
221                 len -= res;
222         }
223 }
224
225 static void http_error(struct http *http, const char *err)
226 {
227         msg(L_INFO, "HTTP error: %s", err);
228         fbpool_start(&http->fbpool, http->mp, 0);
229         bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
230         http_send(http);
231 }
232
233 static int http_get_char(struct http *http) {
234         if (http->iobuf_pos >= http->iobuf_max) {
235                 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
236                 int res = poll(&pfd, 1, IO_TIMEOUT);
237                 if (res < 0)
238                         die("Poll failed: %m");
239                 if (!res) {
240                         msg(L_ERROR, "HTTP read timed out");
241                         return -1;
242                 }
243                 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
244                 if (len < 0) {
245                         msg(L_ERROR, "HTTP read error: %m");
246                         return -1;
247                 }
248                 if (!len) {
249                         msg(L_ERROR, "HTTP connection closed");
250                         return -1;
251                 }
252                 http->iobuf_pos = 0;
253                 http->iobuf_max = len;
254         }
255         return http->iobuf[http->iobuf_pos++];
256 }
257
258 static bool http_get_line(struct http *http)
259 {
260         uint i = 0;
261         for (;;) {
262                 int c = http_get_char(http);
263                 if (c < 0)
264                         return false;
265                 if (c == '\n') {
266                         if (i > 0 && http->linebuf[i-1] == '\r')
267                                 i--;
268                         http->linebuf[i] = 0;
269                         return true;
270                 }
271                 if (i >= IOBUF_SIZE-1) {
272                         http_error(http, "400 Line too long");
273                         return false;
274                 }
275                 http->linebuf[i++] = c;
276         }
277 }
278
279 static void http_answer(struct fastbuf *fb)
280 {
281         char val[256], *w[2];
282         time_t now = time(NULL);
283
284         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
285                 const struct attr *a = &attr_table[i];
286
287                 pthread_mutex_lock(&attr_mutex);
288                 snprintf(val, sizeof(val), "%s", attr_values[i] ? : "");
289                 pthread_mutex_unlock(&attr_mutex);
290
291                 if (!val[0])
292                         continue;
293                 int fields = str_wordsplit(val, w, ARRAY_SIZE(w));
294                 if (fields < 1)
295                         continue;
296                 if (fields >= 2) {
297                         time_t t = atoll(w[1]);
298                         if (t < now - MEASUREMENT_TIMEOUT)
299                                 continue;
300                 }
301
302                 if (a->help)
303                         bprintf(fb, "# HELP %s %s\n", a->metric, a->help);
304                 if (a->type)
305                         bprintf(fb, "# TYPE %s %s\n", a->metric, a->type);
306                 bprintf(fb, "%s %s", a->metric, val);
307 #if 0
308                 // Prometheus does not like our timestamps -- why?
309                 if (fields >= 2)
310                         bprintf(fb, " %s", w[1]);
311 #endif
312                 bputc(fb, '\n');
313         }
314 }
315
316 static void http_connection(struct http *http)
317 {
318         http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
319         http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
320         fbpool_init(&http->fbpool);
321
322         if (!http_get_line(http))
323                 return;
324         // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
325         char *words[3];
326         if (str_wordsplit(http->linebuf, words, 3) != 3) {
327                 http_error(http, "400 Invalid request line");
328                 return;
329         }
330         if (strcmp(words[0], "GET")) {
331                 http_error(http, "501 Method not implemented");
332                 return;
333         }
334
335         for (;;) {
336                 if (!http_get_line(http))
337                         return;
338                 if (!http->linebuf[0])
339                         break;
340                 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
341         }
342
343         fbpool_start(&http->fbpool, http->mp, 0);
344         struct fastbuf *fb = &http->fbpool.fb;
345         bprintf(fb, "HTTP/1.1 200 OK\r\n");
346         bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
347         bprintf(fb, "\r\n");
348         http_answer(fb);
349         http_send(http);
350 }
351
352 static int use_daemon;
353 static int use_debug;
354
355 static struct opt_section options = {
356         OPT_ITEMS {
357                 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
358                 OPT_HELP(""),
359                 OPT_HELP("Options:"),
360                 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
361                 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
362                 OPT_HELP_OPTION,
363                 OPT_CONF_OPTIONS,
364                 OPT_END
365         }
366 };
367
368 int main(int argc UNUSED, char **argv)
369 {
370         log_init(argv[0]);
371         opt_parse(&options, argv+1);
372
373         if (use_daemon) {
374                 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
375                 log_set_default_stream(ls);
376         }
377         if (!use_debug)
378                 log_default_stream()->levels &= ~(1U << L_DEBUG);
379
380         mosquitto_lib_init();
381         mosq = mosquitto_new("prometheus", 1, NULL);
382         if (!mosq)
383                 die("Mosquitto: initialization failed");
384
385         mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
386         mosquitto_log_callback_set(mosq, mqtt_log_callback);
387         mosquitto_message_callback_set(mosq, mqtt_msg_callback);
388
389         if (mosquitto_will_set(mosq, "status/prometheus", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
390                 die("Mosquitto: unable to set will");
391
392         if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
393                 die("Mosquitto: connect failed");
394
395         if (mosquitto_loop_start(mosq))
396                 die("Mosquitto: cannot start service thread");
397
398         int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
399         if (listen_sk < 0)
400                 die("Cannot create listening socket: %m");
401
402         int one = 1;
403         if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
404                 die("Cannot set SO_REUSEADDR: %m");
405
406         struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
407         if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
408                 die("Cannot bind listening socket: %m");
409
410         if (listen(listen_sk, 64) < 0)
411                 die("Cannot listen: %m");
412
413         for (;;) {
414                 int sk = accept(listen_sk, NULL, NULL);
415                 if (sk < 0) {
416                         msg(L_ERROR, "HTTP accept failed: %m");
417                         continue;
418                 }
419                 msg(L_DEBUG, "HTTP accepted connection");
420                 struct mempool *mp = mp_new(4096);
421                 struct http *http = mp_alloc_zero(mp, sizeof(*http));
422                 http->mp = mp;
423                 http->sk = sk;
424                 http_connection(http);
425                 mp_delete(mp);
426                 close(sk);
427         }
428 }