]> mj.ucw.cz Git - home-hw.git/blob - prometheus/burrow-prometheus.c
272deae0b39324b86371d5c5afc7ccf9cd289a6b
[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 static struct mosquitto *mosq;
29
30 struct attr {
31         const char *pm;
32         const char *topic;
33 };
34
35 static const struct attr attr_table[] = {
36         { "# HELP loft_temp Temperature in the loft [degC]", NULL },
37         { "# TYPE loft_temp gauge", NULL },
38         { "loft_temp", "burrow/loft/temperature" },
39         { "# HELP loft_fan Fan speed in the loft", NULL },
40         { "# TYPE loft_fan gauge", NULL },
41         { "loft_fan", "burrow/loft/fan" },
42 };
43
44 static char *attr_values[ARRAY_SIZE(attr_table)];
45 static pthread_mutex_t attr_mutex = PTHREAD_MUTEX_INITIALIZER;
46
47 static void mqtt_publish(const char *topic, const char *fmt, ...)
48 {
49         va_list args;
50         va_start(args, fmt);
51         char m[256];
52         int l = vsnprintf(m, sizeof(m), fmt, args);
53         if (mosquitto_publish(mosq, NULL, topic, l, m, 0, true) != MOSQ_ERR_SUCCESS)
54                 msg(L_ERROR, "Mosquitto: publish failed");
55         va_end(args);
56 }
57
58 static void mqtt_conn_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int status)
59 {
60         if (!status) {
61                 msg(L_DEBUG, "MQTT: Connection established, subscribing");
62                 if (mosquitto_subscribe(mosq, NULL, "burrow/#", 1) != MOSQ_ERR_SUCCESS)
63                         die("Mosquitto: subscribe failed");
64
65                 // mqtt_publish("burrow/loft/status", "ok");
66         }
67 }
68
69 static void mqtt_log_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, int level, const char *message)
70 {
71         // msg(L_INFO, "MQTT(%d): %s", level, message);
72 }
73
74 static void mqtt_msg_callback(struct mosquitto *mosq UNUSED, void *obj UNUSED, const struct mosquitto_message *m)
75 {
76         char val[256];
77         if (m->payloadlen >= sizeof(val) - 1) {
78                 msg(L_ERROR, "Invalid value for topic %s", m->topic);
79                 return;
80         }
81         memcpy(val, m->payload, m->payloadlen);
82         val[m->payloadlen] = 0;
83         msg(L_DEBUG, "MQTT < %s %s", m->topic, val);
84
85         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
86                 if (attr_table[i].topic && !strcmp(attr_table[i].topic, m->topic)) {
87                         pthread_mutex_lock(&attr_mutex);
88                         if (attr_values[i]) {
89                                 xfree(attr_values[i]);
90                                 attr_values[i] = NULL;
91                         }
92                         if (val[0])
93                                 attr_values[i] = xstrdup(val);
94                         pthread_mutex_unlock(&attr_mutex);
95                 }
96         }
97 }
98
99 struct http {
100         struct mempool *mp;
101         int sk;
102         char *iobuf;
103         uint iobuf_pos, iobuf_max;
104         char *linebuf;
105         struct fbpool fbpool;
106 };
107
108 #define IO_TIMEOUT 60000        // in ms
109 #define IOBUF_SIZE 1024
110 #define LINEBUF_SIZE 1024
111
112 static void http_send(struct http *http)
113 {
114         byte *buf = fbpool_end(&http->fbpool);
115         uint len = mp_size(http->mp, buf);
116
117         while (len) {
118                 struct pollfd pfd = { .fd = http->sk, .events = POLLOUT, .revents = 0 };
119                 int res = poll(&pfd, 1, IO_TIMEOUT);
120                 if (res < 0)
121                         die("Poll failed: %m");
122                 if (!res) {
123                         msg(L_ERROR, "HTTP write timed out");
124                         return;
125                 }
126
127                 res = write(http->sk, buf, len);
128                 if (res < 0) {
129                         msg(L_ERROR, "HTTP write failed: %m");
130                         return;
131                 }
132                 buf += res;
133                 len -= res;
134         }
135 }
136
137 static void http_error(struct http *http, const char *err)
138 {
139         msg(L_INFO, "HTTP error: %s", err);
140         fbpool_start(&http->fbpool, http->mp, 0);
141         bprintf(&http->fbpool.fb, "HTTP/1.1 %s\r\n", err);
142         http_send(http);
143 }
144
145 static int http_get_char(struct http *http) {
146         if (http->iobuf_pos >= http->iobuf_max) {
147                 struct pollfd pfd = { .fd = http->sk, .events = POLLIN, .revents = 0 };
148                 int res = poll(&pfd, 1, IO_TIMEOUT);
149                 if (res < 0)
150                         die("Poll failed: %m");
151                 if (!res) {
152                         msg(L_ERROR, "HTTP read timed out");
153                         return -1;
154                 }
155                 int len = read(http->sk, http->iobuf, IOBUF_SIZE);
156                 if (len < 0) {
157                         msg(L_ERROR, "HTTP read error: %m");
158                         return -1;
159                 }
160                 if (!len) {
161                         msg(L_ERROR, "HTTP connection closed");
162                         return -1;
163                 }
164                 http->iobuf_pos = 0;
165                 http->iobuf_max = len;
166         }
167         return http->iobuf[http->iobuf_pos++];
168 }
169
170 static bool http_get_line(struct http *http)
171 {
172         uint i = 0;
173         for (;;) {
174                 int c = http_get_char(http);
175                 if (c < 0)
176                         return false;
177                 if (c == '\n') {
178                         if (i > 0 && http->linebuf[i-1] == '\r')
179                                 i--;
180                         http->linebuf[i] = 0;
181                         return true;
182                 }
183                 if (i >= IOBUF_SIZE-1) {
184                         http_error(http, "400 Line too long");
185                         return false;
186                 }
187                 http->linebuf[i++] = c;
188         }
189 }
190
191 static void http_connection(struct http *http)
192 {
193         http->iobuf = mp_alloc(http->mp, IOBUF_SIZE);
194         http->linebuf = mp_alloc(http->mp, LINEBUF_SIZE);
195         fbpool_init(&http->fbpool);
196
197         if (!http_get_line(http))
198                 return;
199         // msg(L_DEBUG, "Request line: <%s>", http->linebuf);
200         char *words[3];
201         if (str_wordsplit(http->linebuf, words, 3) != 3) {
202                 http_error(http, "400 Invalid request line");
203                 return;
204         }
205         if (strcmp(words[0], "GET")) {
206                 http_error(http, "501 Method not implemented");
207                 return;
208         }
209
210         for (;;) {
211                 if (!http_get_line(http))
212                         return;
213                 if (!http->linebuf[0])
214                         break;
215                 // msg(L_DEBUG, "Header line: <%s>", http->linebuf);
216         }
217
218         fbpool_start(&http->fbpool, http->mp, 0);
219         struct fastbuf *fb = &http->fbpool.fb;
220         bprintf(fb, "HTTP/1.1 200 OK\r\n");
221         bprintf(fb, "Content-type: text/plain; version=0.0.4\r\n");
222         bprintf(fb, "\r\n");
223         for (uint i=0; i < ARRAY_SIZE(attr_table); i++) {
224                 if (attr_table[i].topic) {
225                         pthread_mutex_lock(&attr_mutex);
226                         bprintf(fb, "%s %s\n", attr_table[i].pm, attr_values[i] ? : "");
227                         pthread_mutex_unlock(&attr_mutex);
228                 } else {
229                         bprintf(fb, "%s\n", attr_table[i].pm);
230                 }
231         }
232         http_send(http);
233 }
234
235 static int use_daemon;
236 static int use_debug;
237
238 static struct opt_section options = {
239         OPT_ITEMS {
240                 OPT_HELP("A daemon for controlling the solid state relay module via MQTT"),
241                 OPT_HELP(""),
242                 OPT_HELP("Options:"),
243                 OPT_BOOL('d', "debug", use_debug, 0, "\tLog debugging messages"),
244                 OPT_BOOL(0, "daemon", use_daemon, 0, "\tDaemonize"),
245                 OPT_HELP_OPTION,
246                 OPT_CONF_OPTIONS,
247                 OPT_END
248         }
249 };
250
251 int main(int argc UNUSED, char **argv)
252 {
253         log_init(argv[0]);
254         opt_parse(&options, argv+1);
255
256         if (use_daemon) {
257                 struct log_stream *ls = log_new_syslog("daemon", LOG_PID);
258                 log_set_default_stream(ls);
259         }
260         if (!use_debug)
261                 log_default_stream()->levels &= ~(1U << L_DEBUG);
262
263         mosquitto_lib_init();
264         mosq = mosquitto_new("prometheus", 1, NULL);
265         if (!mosq)
266                 die("Mosquitto: initialization failed");
267
268         mosquitto_connect_callback_set(mosq, mqtt_conn_callback);
269         mosquitto_log_callback_set(mosq, mqtt_log_callback);
270         mosquitto_message_callback_set(mosq, mqtt_msg_callback);
271
272 #if 0
273         // FIXME: Publish online/offline status
274         if (mosquitto_will_set(mosq, "burrow/loft/status", 4, "dead", 0, true) != MOSQ_ERR_SUCCESS)
275                 die("Mosquitto: unable to set will");
276 #endif
277
278         if (mosquitto_connect_async(mosq, "10.32.184.5", 1883, 60) != MOSQ_ERR_SUCCESS)
279                 die("Mosquitto: connect failed");
280
281         if (mosquitto_loop_start(mosq))
282                 die("Mosquitto: cannot start service thread");
283
284         int listen_sk = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
285         if (listen_sk < 0)
286                 die("Cannot create listening socket: %m");
287
288         int one = 1;
289         if (setsockopt(listen_sk, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)) < 0)
290                 die("Cannot set SO_REUSEADDR: %m");
291
292         struct sockaddr_in sin = { .sin_family = AF_INET, .sin_port = htons(1422), .sin_addr = INADDR_ANY };
293         if (bind(listen_sk, (const struct sockaddr *) &sin, sizeof(sin)) < 0)
294                 die("Cannot bind listening socket: %m");
295
296         if (listen(listen_sk, 64) < 0)
297                 die("Cannot listen: %m");
298
299         for (;;) {
300                 int sk = accept(listen_sk, NULL, NULL);
301                 if (sk < 0) {
302                         msg(L_ERROR, "HTTP accept failed: %m");
303                         continue;
304                 }
305                 msg(L_DEBUG, "HTTP accepted connection");
306                 struct mempool *mp = mp_new(4096);
307                 struct http *http = mp_alloc_zero(mp, sizeof(*http));
308                 http->mp = mp;
309                 http->sk = sk;
310                 http_connection(http);
311                 mp_delete(mp);
312                 close(sk);
313         }
314 }