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