mqtt plugin: Send only the acutally used part of the payload buffer.
[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_TOPIC_PREFIX   "collectd"
42
43 /*
44  * Data types
45  */
46 struct mqtt_client_conf
47 {
48     char               *name;
49
50     struct mosquitto   *mosq;
51     _Bool               connected;
52
53     char               *host;
54     int                 port;
55     char               *username;
56     char               *password;
57
58     char               *client_id;
59     char               *topic_prefix;
60     _Bool               store_rates;
61     _Bool               retain;
62     int qos;
63
64     c_complain_t        complaint_cantpublish;
65     pthread_mutex_t     lock;
66 };
67 typedef struct mqtt_client_conf mqtt_client_conf_t;
68
69 static char const *mosquitto_strerror (int code)
70 {
71     switch (code)
72     {
73         case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
74         case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
75         case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
76         case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
77         case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
78         case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
79         case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
80         case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
81         case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
82         case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
83         case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
84         case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
85         case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
86         case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
87         case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
88     }
89
90     return "UNKNOWN ERROR CODE";
91 }
92
93 static void mqtt_free (mqtt_client_conf_t *conf)
94 {
95     if (conf == NULL)
96         return;
97
98     if (conf->connected)
99         (void) mosquitto_disconnect (conf->mosq);
100     conf->connected = 0;
101     (void) mosquitto_destroy (conf->mosq);
102
103     sfree (conf->host);
104     sfree (conf->username);
105     sfree (conf->password);
106     sfree (conf->client_id);
107     sfree (conf->topic_prefix);
108     sfree (conf);
109 }
110
111 /*
112  * Functions
113  */
114 /* must hold conf->lock when calling. */
115 static int mqtt_reconnect (mqtt_client_conf_t *conf)
116 {
117     int status;
118
119     if (conf->connected)
120         return (0);
121
122     status = mosquitto_reconnect (conf->mosq);
123     if (status != MOSQ_ERR_SUCCESS)
124     {
125         char errbuf[1024];
126         ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
127                 (status == MOSQ_ERR_ERRNO)
128                 ? sstrerror(errno, errbuf, sizeof (errbuf))
129                 : mosquitto_strerror (status));
130         return (-1);
131     }
132
133     conf->connected = 1;
134
135     c_release (LOG_INFO,
136             &conf->complaint_cantpublish,
137             "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
138             conf->host, conf->port);
139
140     return (0);
141 } /* mqtt_reconnect */
142
143 /* must hold conf->lock when calling. */
144 static int mqtt_connect (mqtt_client_conf_t *conf)
145 {
146     char const *client_id;
147     int status;
148
149     if (conf->mosq != NULL)
150         return mqtt_reconnect (conf);
151
152     if (conf->client_id)
153         client_id = conf->client_id;
154     else
155         client_id = hostname_g;
156
157     conf->mosq = mosquitto_new (client_id, /* user data = */ conf);
158     if (conf->mosq == NULL)
159     {
160         ERROR ("mqtt plugin: mosquitto_new failed");
161         return (-1);
162     }
163
164     if (conf->username && conf->password)
165     {
166         status = mosquitto_username_pw_set (conf->mosq, conf->username, conf->password);
167         if (status != MOSQ_ERR_SUCCESS)
168         {
169             char errbuf[1024];
170             ERROR ("mqtt plugin: mosquitto_username_pw_set failed: %s",
171                     (status == MOSQ_ERR_ERRNO)
172                     ? sstrerror (errno, errbuf, sizeof (errbuf))
173                     : mosquitto_strerror (status));
174
175             mosquitto_destroy (conf->mosq);
176             conf->mosq = NULL;
177             return (-1);
178         }
179     }
180
181     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
182             /* keepalive = */ 10, /* clean session = */ 1);
183     if (status != MOSQ_ERR_SUCCESS)
184     {
185         char errbuf[1024];
186         ERROR ("mqtt plugin: mosquitto_connect failed: %s",
187                 (status == MOSQ_ERR_ERRNO)
188                 ? sstrerror (errno, errbuf, sizeof (errbuf))
189                 : mosquitto_strerror (status));
190
191         mosquitto_destroy (conf->mosq);
192         conf->mosq = NULL;
193         return (-1);
194     }
195
196     conf->connected = 1;
197     return (0);
198 } /* mqtt_connect */
199
200 static int publish (mqtt_client_conf_t *conf, char const *topic,
201     void const *payload, size_t payload_len)
202 {
203     int status;
204
205     pthread_mutex_lock (&conf->lock);
206
207     status = mqtt_connect (conf);
208     if (status != 0) {
209         pthread_mutex_unlock (&conf->lock);
210         ERROR ("mqtt plugin: unable to reconnect to broker");
211         return (status);
212     }
213
214     status = mosquitto_publish(conf->mosq,
215             /* message id */ NULL,
216             topic,
217             (uint32_t) payload_len, payload,
218             /* qos */ conf->qos,
219             /* retain */ conf->retain);
220     if (status != MOSQ_ERR_SUCCESS)
221     {
222         char errbuf[1024];
223         c_complain (LOG_ERR,
224                 &conf->complaint_cantpublish,
225                 "plugin mqtt: mosquitto_publish failed: %s",
226                 status == MOSQ_ERR_ERRNO ?
227                 sstrerror(errno, errbuf, sizeof (errbuf)) :
228                 mosquitto_strerror(status));
229         /* Mark our connection "down" regardless of the error as a safety
230          * measure; we will try to reconnect the next time we have to publish a
231          * message */
232         conf->connected = 0;
233
234         pthread_mutex_unlock (&conf->lock);
235         return (-1);
236     }
237
238     pthread_mutex_unlock (&conf->lock);
239     return (0);
240 } /* int publish */
241
242 static int format_topic (char *buf, size_t buf_len,
243     data_set_t const *ds, value_list_t const *vl,
244     mqtt_client_conf_t *conf)
245 {
246     char name[MQTT_MAX_TOPIC_SIZE];
247     int status;
248
249     if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
250         return (FORMAT_VL (buf, buf_len, vl));
251
252     status = FORMAT_VL (name, sizeof (name), vl);
253     if (status != 0)
254         return (status);
255
256     status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
257     if ((status < 0) || (((size_t) status) >= buf_len))
258         return (ENOMEM);
259
260     return (0);
261 } /* int format_topic */
262
263 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
264     user_data_t *user_data)
265 {
266     mqtt_client_conf_t *conf;
267     char topic[MQTT_MAX_TOPIC_SIZE];
268     char payload[MQTT_MAX_MESSAGE_SIZE];
269     int status = 0;
270
271     if ((user_data == NULL) || (user_data->data == NULL))
272         return (EINVAL);
273     conf = user_data->data;
274
275     status = format_topic (topic, sizeof (topic), ds, vl, conf);
276     if (status != 0)
277     {
278         ERROR ("mqtt plugin: format_topic failed with status %d.", status);
279         return (status);
280     }
281
282     status = format_values (payload, sizeof (payload),
283             ds, vl, conf->store_rates);
284     if (status != 0)
285     {
286         ERROR ("mqtt plugin: format_values failed with status %d.", status);
287         return (status);
288     }
289
290     status = publish (conf, topic, payload, strlen (payload) + 1);
291     if (status != 0)
292     {
293         ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
294         return (status);
295     }
296
297     return (status);
298 } /* mqtt_write */
299
300 /*
301  * <Publish "name">
302  *   Host "example.com"
303  *   Port 1883
304  *   Prefix "collectd"
305  *   ClientId "collectd"
306  *   User "guest"
307  *   Password "secret"
308  *   StoreRates true
309  *   Retain false
310  *   QoS 0
311  * </Publish>
312  */
313 static int mqtt_config_broker (oconfig_item_t *ci)
314 {
315     mqtt_client_conf_t *conf;
316     user_data_t user_data;
317     int status;
318     int i;
319
320     conf = calloc (1, sizeof (*conf));
321     if (conf == NULL)
322     {
323         ERROR ("mqtt plugin: malloc failed.");
324         return (-1);
325     }
326
327     conf->name = NULL;
328     status = cf_util_get_string (ci, &conf->name);
329     if (status != 0)
330     {
331         mqtt_free (conf);
332         return (status);
333     }
334
335     conf->host = strdup (MQTT_DEFAULT_HOST);
336     conf->port = MQTT_DEFAULT_PORT;
337     conf->client_id = NULL;
338     conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
339     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
340
341     for (i = 0; i < ci->children_num; i++)
342     {
343         oconfig_item_t *child = ci->children + i;
344         if (strcasecmp ("Host", child->key) == 0)
345             cf_util_get_string (child, &conf->host);
346         else if (strcasecmp ("Port", child->key) == 0)
347         {
348             int tmp = cf_util_get_port_number (child);
349             if (tmp < 0)
350                 ERROR ("mqtt plugin: Invalid port number.");
351             else
352                 conf->port = tmp;
353         }
354         else if (strcasecmp ("Prefix", child->key) == 0)
355             cf_util_get_string (child, &conf->topic_prefix);
356         else if (strcasecmp ("ClientId", child->key) == 0)
357             cf_util_get_string (child, &conf->client_id);
358         else if (strcasecmp ("User", child->key) == 0)
359             cf_util_get_string (child, &conf->username);
360         else if (strcasecmp ("Password", child->key) == 0)
361             cf_util_get_string (child, &conf->password);
362         else if (strcasecmp ("StoreRates", child->key) == 0)
363             cf_util_get_boolean (child, &conf->store_rates);
364         else if (strcasecmp ("Retain", child->key) == 0)
365             cf_util_get_boolean (child, &conf->retain);
366         else if (strcasecmp ("QoS", child->key) == 0)
367         {
368             int tmp = -1;
369             status = cf_util_get_int (child, &tmp);
370             if ((status != 0) || (tmp < 0) || (tmp > 2))
371                 ERROR ("mqtt plugin: Not a valid QoS setting.");
372             else
373                 conf->qos = tmp;
374         }
375         else
376             ERROR ("mqtt plugin: Unknown config option: %s", child->key);
377     }
378
379     memset (&user_data, 0, sizeof (user_data));
380     user_data.data = conf;
381
382     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
383         conf->host, conf->port);
384
385     plugin_register_write ("mqtt", mqtt_write, &user_data);
386     return (0);
387 } /* mqtt_config_broker */
388
389 /*
390  * <Plugin mqtt>
391  *   <Publish "name">
392  *     # ...
393  *   </Publish>
394  * </Plugin>
395  */
396 static int mqtt_config (oconfig_item_t *ci)
397 {
398     int i;
399
400     for (i = 0; i < ci->children_num; i++)
401     {
402         oconfig_item_t *child = ci->children + i;
403
404         if (strcasecmp ("Publish", child->key) == 0)
405             mqtt_config_broker (child);
406         else
407             ERROR ("mqtt plugin: Unknown config option: %s", child->key);
408     }
409
410     return (0);
411 } /* int mqtt_config */
412
413 static int mqtt_init (void)
414 {
415     mosquitto_lib_init();
416
417     return (0);
418 } /* mqtt_init */
419
420 void module_register (void)
421 {
422     plugin_register_complex_config ("mqtt", mqtt_config);
423     plugin_register_init ("mqtt", mqtt_init);
424 } /* void module_register */
425
426 /* vim: set sw=4 sts=4 et fdm=marker : */