mqtt plugin: Compile fixes.
[collectd.git] / src / mqtt.c
1 /**
2  * collectd - src/mqtt.c
3  * Copyright (C) 2014       Marc Falzon <marc at baha dot mu>
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  **/
23
24 // Reference: http://mosquitto.org/api/files/mosquitto-h.html
25
26
27 #include "collectd.h"
28 #include "common.h"
29 #include "plugin.h"
30 #include "utils_cache.h"
31 #include "utils_complain.h"
32
33 #include <pthread.h>
34
35 #include <mosquitto.h>
36
37 #define MQTT_MAX_TOPIC_SIZE         1024
38 #define MQTT_MAX_MESSAGE_SIZE       MQTT_MAX_TOPIC_SIZE + 1024
39 #define MQTT_DEFAULT_HOST           "localhost"
40 #define MQTT_DEFAULT_PORT           1883
41 #define MQTT_DEFAULT_CLIENT_ID      "collectd"
42 #define MQTT_DEFAULT_TOPIC_PREFIX   "collectd"
43
44 /*
45  * Data types
46  */
47 struct mqtt_client_conf
48 {
49     struct mosquitto    *mosq;
50     bool                connected;
51     char                *host;
52     int                 port;
53     char                *client_id;
54     char                *topic_prefix;
55     c_complain_t        complaint_cantpublish;
56     pthread_mutex_t     lock;
57 };
58
59 static char const *mosquitto_strerror (int code)
60 {
61     switch (code)
62     {
63         case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
64         case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
65         case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
66         case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
67         case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
68         case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
69         case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
70         case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
71         case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
72         case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
73         case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
74         case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
75         case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
76         case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
77         case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
78     }
79
80     return "UNKNOWN ERROR CODE";
81 }
82
83 /*
84  * Functions
85  */
86 static int mqtt_reconnect_broker (struct mqtt_client_conf *conf)
87 {
88     int status;
89
90     if (conf->connected)
91         return (0);
92
93     pthread_mutex_lock (&conf->lock);
94
95     status = mosquitto_reconnect (conf->mosq);
96
97     if (status != MOSQ_ERR_SUCCESS) {
98         ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
99             (status == MOSQ_ERR_ERRNO ?
100                 strerror(errno) : mosquitto_strerror (status)));
101         pthread_mutex_unlock (&conf->lock);
102         return (-1);
103     }
104
105     conf->connected = true;
106
107     c_release (LOG_INFO,
108         &conf->complaint_cantpublish,
109         "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
110         conf->host, conf->port);
111
112     pthread_mutex_unlock (&conf->lock);
113
114     return (0);
115 } /* mqtt_reconnect_broker */
116
117 static int mqtt_publish_message (struct mqtt_client_conf *conf, char *topic,
118     void const *payload, size_t payload_len)
119 {
120     char errbuf[1024];
121     int status;
122
123     status = mosquitto_publish(conf->mosq,
124         /* message id */ NULL,
125         topic,
126         (int) payload_len,
127         payload,
128         /* qos */ 0,
129         /* retain */ false);
130
131     if (status != MOSQ_ERR_SUCCESS)
132     {
133         c_complain (LOG_ERR,
134             &conf->complaint_cantpublish,
135             "plugin mqtt: mosquitto_publish failed: %s",
136             status == MOSQ_ERR_ERRNO ?
137             sstrerror(errno, errbuf, sizeof (errbuf)) :
138                 mosquitto_strerror(status));
139         /*
140         Mark our connection "down" regardless of the error as a safety measure;
141         we will try to reconnect the next time we have to publish a message
142         */
143         conf->connected = false;
144
145         return (-1);
146     }
147
148     return (0);
149 } /* mqtt_publish_message */
150
151 static int mqtt_format_metric_value (char *buf, size_t buf_len,
152     const data_set_t *data_set, const value_list_t *vl, int ds_num)
153 {
154     gauge_t *rates = NULL;
155     gauge_t *value = NULL;
156     size_t metric_value_len;
157     int status = 0;
158
159     memset (buf, 0, buf_len);
160
161     if (data_set->ds[ds_num].type == DS_TYPE_GAUGE)
162         value = &vl->values[ds_num].gauge;
163     else {
164         rates = uc_get_rate (data_set, vl);
165         value = &rates[ds_num];
166     }
167
168     metric_value_len = ssnprintf (buf, buf_len, "%f", *value);
169
170     if (metric_value_len >= buf_len)
171         return (-ENOMEM);
172
173     if (rates)
174         sfree (rates);
175
176     return (status);
177 } /* mqtt_format_metric_value */
178
179 static int mqtt_format_message_topic (char *buf, size_t buf_len,
180     char const *prefix, const value_list_t *vl, const char *ds_name)
181 {
182     size_t topic_buf_len;
183
184     memset (buf, 0, buf_len);
185
186     /*
187         MQTT message topic format:
188         [<prefix>/]<hostname>/<plugin>/<plugin instance>/<type>/<type instance>/<ds>/
189     */
190     topic_buf_len = (size_t) ssnprintf (buf, buf_len,
191         "%s/%s/%s/%s/%s/%s/%s",
192         prefix,
193         vl->host,
194         vl->plugin,
195         vl->plugin_instance[0] != '\0' ? vl->plugin_instance : "(null)",
196         vl->type,
197         vl->type_instance[0] != '\0' ? vl->type_instance : "(null)",
198         ds_name);
199
200     if (topic_buf_len >= buf_len)
201     {
202         ERROR ("mqtt_format_message_topic: topic buffer too small: "
203                 "Need %zu bytes.", topic_buf_len + 1);
204         return (-ENOMEM);
205     }
206
207     return (0);
208 } /* mqtt_format_message_topic */
209
210 static int mqtt_format_payload (char *buf, size_t buf_len,
211     const data_set_t *data_set, const value_list_t *vl, int ds_num)
212 {
213     char metric_path[10 * DATA_MAX_NAME_LEN];
214     char metric_value[512];
215     size_t payload_buf_len;
216     int status = 0;
217
218     memset (buf, 0, buf_len);
219
220     ssnprintf (metric_path, sizeof (metric_path),
221         "%s.%s%s%s.%s%s%s%s%s",
222         vl->host,
223         vl->plugin,
224         vl->plugin_instance[0] != '\0' ? "." : "",
225         vl->plugin_instance[0] != '\0' ? vl->plugin_instance : "",
226         vl->type,
227         vl->type_instance[0] != '\0' ? "." : "",
228         vl->type_instance[0] != '\0' ? vl->type_instance : "",
229         strcmp(data_set->ds[ds_num].name, "value") != 0 ? "." : "",
230         strcmp(data_set->ds[ds_num].name, "value") != 0 ?
231             data_set->ds[ds_num].name : "");
232
233     status = mqtt_format_metric_value (metric_value,
234         sizeof (metric_value),
235         data_set,
236         vl,
237         ds_num);
238
239     if (status != 0)
240     {
241         ERROR ("mqtt_format_payload: error with mqtt_format_metric_value");
242         return (status);
243     }
244
245     payload_buf_len = (size_t) ssnprintf (buf, buf_len,
246         "%s %s %u",
247         metric_path,
248         metric_value,
249         (unsigned int) CDTIME_T_TO_TIME_T (vl->time));
250
251     if (payload_buf_len >= buf_len)
252     {
253         ERROR ("mqtt_format_payload: payload buffer too small: "
254                 "Need %zu bytes.", payload_buf_len + 1);
255         return (-ENOMEM);
256     }
257
258     return (status);
259 } /* mqtt_format_payload */
260
261 static int mqtt_write (const data_set_t *data_set, const value_list_t *vl,
262     user_data_t *user_data)
263 {
264     struct mqtt_client_conf *conf;
265     char msg_topic[MQTT_MAX_TOPIC_SIZE];
266     char msg_payload[MQTT_MAX_MESSAGE_SIZE];
267     int status = 0;
268     int i;
269
270     if (user_data == NULL)
271         return (EINVAL);
272
273     conf = user_data->data;
274
275     if (!conf->connected)
276     {
277         status = mqtt_reconnect_broker (conf);
278
279         if (status != 0) {
280             ERROR ("plugin mqtt: unable to reconnect to broker");
281             return (status);
282         }
283     }
284
285     for (i = 0; i < data_set->ds_num; i++)
286     {
287         status = mqtt_format_message_topic (msg_topic, sizeof (msg_topic),
288             conf->topic_prefix, vl, data_set->ds[i].name);
289         if (status != 0)
290         {
291             ERROR ("plugin mqtt: error with mqtt_format_message_topic");
292             return (status);
293         }
294
295         status = mqtt_format_payload (msg_payload,
296             sizeof (msg_payload),
297             data_set,
298             vl,
299             i);
300
301         if (status != 0)
302         {
303             ERROR ("mqtt_write: error with mqtt_format_payload");
304             return (status);
305         }
306
307         status = mqtt_publish_message (conf,
308             msg_topic,
309             msg_payload,
310             sizeof (msg_payload));
311         if (status != 0)
312         {
313             ERROR ("plugin mqtt: unable to publish message");
314             return (status);
315         }
316
317         DEBUG ("\x1B[36m[debug]\x1B[0m\x1B[37m mqtt_write[%02X]\x1B[0m "
318             "published message: topic=%s payload=%s",
319             (unsigned)pthread_self(),
320             msg_topic,
321             msg_payload);
322     }
323
324     return (status);
325 } /* mqtt_write */
326
327 static int mqtt_config (oconfig_item_t *ci)
328 {
329     struct mqtt_client_conf *conf;
330     user_data_t user_data;
331     char errbuf[1024];
332     int status;
333
334     DEBUG ("\x1B[36m[debug]\x1B[0m\x1B[37m mqtt_config[%02X]\x1B[0m ",
335         (unsigned)pthread_self());
336
337     conf = malloc (sizeof (*conf));
338     if (conf == NULL)
339     {
340         ERROR ("write_mqtt plugin: malloc failed.");
341         return (-1);
342     }
343
344     memset (conf, 0, sizeof (*conf));
345
346     conf->connected = false;
347     conf->host = MQTT_DEFAULT_HOST;
348     conf->port = MQTT_DEFAULT_PORT;
349     conf->client_id = MQTT_DEFAULT_CLIENT_ID;
350     conf->topic_prefix = MQTT_DEFAULT_TOPIC_PREFIX;
351     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
352
353     memset (&user_data, 0, sizeof (user_data));
354     user_data.data = conf;
355
356     conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
357     if (conf->mosq == NULL)
358     {
359         ERROR ("mqtt plugin: mosquitto_new failed");
360         free (conf);
361         return (-1);
362     }
363
364     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
365             /* keepalive = */ 10, /* clean session = */ 1);
366     if (status != MOSQ_ERR_SUCCESS) {
367         ERROR ("mqtt_config: mosquitto_connect failed: %s",
368             (status == MOSQ_ERR_ERRNO ?
369                 sstrerror(errno, errbuf, sizeof (errbuf)) :
370                 mosquitto_strerror (status)));
371         return (-1);
372     }
373
374     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
375         conf->host, conf->port);
376
377     conf->connected = true;
378
379     plugin_register_write ("mqtt", mqtt_write, &user_data);
380
381     return (0);
382 } /* mqtt_config */
383
384 static int mqtt_init (void)
385 {
386     mosquitto_lib_init();
387
388     return (0);
389 } /* mqtt_init */
390
391 void module_register (void)
392 {
393     plugin_register_complex_config ("mqtt", mqtt_config);
394     plugin_register_init ("mqtt", mqtt_init);
395 } /* void module_register */
396
397 /* vim: set sw=4 sts=4 et fdm=marker : */