mqtt plugin: Correctly check the return value of format_topic().
[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 typedef struct mqtt_client_conf mqtt_client_conf_t;
59
60 static char const *mosquitto_strerror (int code)
61 {
62     switch (code)
63     {
64         case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
65         case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
66         case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
67         case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
68         case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
69         case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
70         case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
71         case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
72         case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
73         case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
74         case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
75         case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
76         case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
77         case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
78         case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
79     }
80
81     return "UNKNOWN ERROR CODE";
82 }
83
84 /*
85  * Functions
86  */
87 /* must hold conf->lock when calling. */
88 static int mqtt_reconnect_broker (mqtt_client_conf_t *conf)
89 {
90     int status;
91
92     if (conf->connected)
93         return (0);
94
95     status = mosquitto_reconnect (conf->mosq);
96     if (status != MOSQ_ERR_SUCCESS)
97     {
98         char errbuf[1024];
99         ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
100                 (status == MOSQ_ERR_ERRNO)
101                 ? sstrerror(errno, errbuf, sizeof (errbuf))
102                 : mosquitto_strerror (status));
103         return (-1);
104     }
105
106     conf->connected = 1;
107
108     c_release (LOG_INFO,
109             &conf->complaint_cantpublish,
110             "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
111             conf->host, conf->port);
112
113     return (0);
114 } /* mqtt_reconnect_broker */
115
116 static int publish (mqtt_client_conf_t *conf, char const *topic,
117     void const *payload, size_t payload_len)
118 {
119     int const qos = 0; /* TODO: Config option */
120     int status;
121
122     pthread_mutex_lock (&conf->lock);
123
124     status = mqtt_reconnect_broker (conf);
125     if (status != 0) {
126         pthread_mutex_unlock (&conf->lock);
127         ERROR ("mqtt plugin: unable to reconnect to broker");
128         return (status);
129     }
130
131     status = mosquitto_publish(conf->mosq,
132             /* message id */ NULL,
133             topic,
134             (uint32_t) payload_len, payload,
135             /* qos */ qos,
136             /* retain */ false);
137     if (status != MOSQ_ERR_SUCCESS)
138     {
139         char errbuf[1024];
140         c_complain (LOG_ERR,
141                 &conf->complaint_cantpublish,
142                 "plugin mqtt: mosquitto_publish failed: %s",
143                 status == MOSQ_ERR_ERRNO ?
144                 sstrerror(errno, errbuf, sizeof (errbuf)) :
145                 mosquitto_strerror(status));
146         /* Mark our connection "down" regardless of the error as a safety
147          * measure; we will try to reconnect the next time we have to publish a
148          * message */
149         conf->connected = 0;
150
151         pthread_mutex_unlock (&conf->lock);
152         return (-1);
153     }
154
155     pthread_mutex_unlock (&conf->lock);
156     return (0);
157 } /* int publish */
158
159 static int format_topic (char *buf, size_t buf_len,
160     data_set_t const *ds, value_list_t const *vl,
161     mqtt_client_conf_t *conf)
162 {
163     char name[MQTT_MAX_TOPIC_SIZE];
164     int status;
165
166     if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
167         return (FORMAT_VL (buf, buf_len, vl));
168
169     status = FORMAT_VL (name, sizeof (name), vl);
170     if (status != 0)
171         return (status);
172
173     status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
174     if ((status < 0) || (((size_t) status) >= buf_len))
175         return (ENOMEM);
176
177     return (0);
178 } /* int format_topic */
179
180 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
181     user_data_t *user_data)
182 {
183     mqtt_client_conf_t *conf;
184     char topic[MQTT_MAX_TOPIC_SIZE];
185     char payload[MQTT_MAX_MESSAGE_SIZE];
186     int status = 0;
187     _Bool const store_rates = 0; /* TODO: Config option */
188
189     if ((user_data == NULL) || (user_data->data == NULL))
190         return (EINVAL);
191     conf = user_data->data;
192
193     status = format_topic (topic, sizeof (topic), ds, vl, conf);
194     if (status != 0)
195     {
196         ERROR ("mqtt plugin: format_topic failed with status %d.", status);
197         return (status);
198     }
199
200     status = format_values (payload, sizeof (payload),
201             ds, vl, store_rates);
202     if (status != 0)
203     {
204         ERROR ("mqtt plugin: format_values failed with status %d.", status);
205         return (status);
206     }
207
208     status = publish (conf, topic, payload, sizeof (payload));
209     if (status != 0)
210     {
211         ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
212         return (status);
213     }
214
215     return (status);
216 } /* mqtt_write */
217
218 /*
219  * <Plugin mqtt>
220  *   Host "example.com"
221  *   Port 1883
222  *   Prefix "collectd"
223  *   ClientId "collectd"
224  * </Plugin>
225  */
226 static int mqtt_config (oconfig_item_t *ci)
227 {
228     mqtt_client_conf_t *conf;
229     user_data_t user_data;
230     int status;
231     int i;
232
233     conf = calloc (1, sizeof (*conf));
234     if (conf == NULL)
235     {
236         ERROR ("mqtt plugin: malloc failed.");
237         return (-1);
238     }
239
240     conf->connected = 0;
241     conf->host = strdup (MQTT_DEFAULT_HOST);
242     conf->port = MQTT_DEFAULT_PORT;
243     conf->client_id = strdup (MQTT_DEFAULT_CLIENT_ID);
244     conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
245     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
246
247     for (i = 0; i < ci->children_num; i++)
248     {
249         oconfig_item_t *child = ci->children + i;
250         if (strcasecmp ("Host", child->key) == 0)
251             cf_util_get_string (child, &conf->host);
252         else if (strcasecmp ("Port", child->key) == 0)
253         {
254             int tmp = cf_util_get_port_number (child);
255             if (tmp < 0)
256             {
257                 ERROR ("mqtt plugin: Invalid port number.");
258                 continue;
259             }
260             conf->port = tmp;
261         }
262         else if (strcasecmp ("Prefix", child->key) == 0)
263             cf_util_get_string (child, &conf->topic_prefix);
264         else if (strcasecmp ("ClientId", child->key) == 0)
265             cf_util_get_string (child, &conf->client_id);
266         else
267             ERROR ("mqtt plugin: Unknown config option: %s", child->key);
268     }
269
270     memset (&user_data, 0, sizeof (user_data));
271     user_data.data = conf;
272
273     conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
274     if (conf->mosq == NULL)
275     {
276         ERROR ("mqtt plugin: mosquitto_new failed");
277         free (conf);
278         return (-1);
279     }
280
281     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
282             /* keepalive = */ 10, /* clean session = */ 1);
283     if (status != MOSQ_ERR_SUCCESS)
284     {
285         char errbuf[1024];
286         ERROR ("mqtt plugin: mosquitto_connect failed: %s",
287                 (status == MOSQ_ERR_ERRNO)
288                 ? sstrerror (errno, errbuf, sizeof (errbuf))
289                 : mosquitto_strerror (status));
290         free (conf);
291         return (-1);
292     }
293
294     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
295         conf->host, conf->port);
296
297     conf->connected = 1;
298
299     plugin_register_write ("mqtt", mqtt_write, &user_data);
300
301     return (0);
302 } /* mqtt_config */
303
304 static int mqtt_init (void)
305 {
306     mosquitto_lib_init();
307
308     return (0);
309 } /* mqtt_init */
310
311 void module_register (void)
312 {
313     plugin_register_complex_config ("mqtt", mqtt_config);
314     plugin_register_init ("mqtt", mqtt_init);
315 } /* void module_register */
316
317 /* vim: set sw=4 sts=4 et fdm=marker : */