d1d22054880648c6d3ce2f5872c254c803acbc8f
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 **/
24 // Reference: http://mosquitto.org/api/files/mosquitto-h.html
27 #include "collectd.h"
28 #include "common.h"
29 #include "plugin.h"
30 #include "utils_cache.h"
31 #include "utils_complain.h"
33 #include <pthread.h>
35 #include <mosquitto.h>
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"
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;
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 }
81 return "UNKNOWN ERROR CODE";
82 }
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;
92 if (conf->connected)
93 return (0);
95 status = mosquitto_reconnect (conf->mosq);
96 if (status != MOSQ_ERR_SUCCESS)
97 {
98 ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
99 (status == MOSQ_ERR_ERRNO ?
100 strerror(errno) : mosquitto_strerror (status)));
101 return (-1);
102 }
104 conf->connected = true;
106 c_release (LOG_INFO,
107 &conf->complaint_cantpublish,
108 "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
109 conf->host, conf->port);
111 return (0);
112 } /* mqtt_reconnect_broker */
114 static int publish (mqtt_client_conf_t *conf, char const *topic,
115 void const *payload, size_t payload_len)
116 {
117 int const qos = 0; /* TODO: Config option */
118 int status;
120 pthread_mutex_lock (&conf->lock);
122 status = mqtt_reconnect_broker (conf);
123 if (status != 0) {
124 pthread_mutex_unlock (&conf->lock);
125 ERROR ("mqtt plugin: unable to reconnect to broker");
126 return (status);
127 }
129 status = mosquitto_publish(conf->mosq,
130 /* message id */ NULL,
131 topic,
132 (uint32_t) payload_len, payload,
133 /* qos */ qos,
134 /* retain */ false);
135 if (status != MOSQ_ERR_SUCCESS)
136 {
137 char errbuf[1024];
138 c_complain (LOG_ERR,
139 &conf->complaint_cantpublish,
140 "plugin mqtt: mosquitto_publish failed: %s",
141 status == MOSQ_ERR_ERRNO ?
142 sstrerror(errno, errbuf, sizeof (errbuf)) :
143 mosquitto_strerror(status));
144 /* Mark our connection "down" regardless of the error as a safety
145 * measure; we will try to reconnect the next time we have to publish a
146 * message */
147 conf->connected = false;
149 pthread_mutex_unlock (&conf->lock);
150 return (-1);
151 }
153 pthread_mutex_unlock (&conf->lock);
154 return (0);
155 } /* int publish */
157 static int format_topic (char *buf, size_t buf_len,
158 data_set_t const *ds, value_list_t const *vl,
159 mqtt_client_conf_t *conf)
160 {
161 char name[MQTT_MAX_TOPIC_SIZE];
162 int status;
164 if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
165 return (FORMAT_VL (buf, buf_len, vl));
167 status = FORMAT_VL (name, sizeof (name), vl);
168 if (status != 0)
169 return (status);
171 status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
172 if ((status < 0) || (((size_t) status) >= buf_len))
173 return (ENOMEM);
175 return (0);
176 } /* int format_topic */
178 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
179 user_data_t *user_data)
180 {
181 mqtt_client_conf_t *conf;
182 char topic[MQTT_MAX_TOPIC_SIZE];
183 char payload[MQTT_MAX_MESSAGE_SIZE];
184 int status = 0;
185 _Bool const store_rates = 0; /* TODO: Config option */
187 if ((user_data == NULL) || (user_data->data == NULL))
188 return (EINVAL);
189 conf = user_data->data;
191 status = format_topic (topic, sizeof (topic), ds, vl, conf);
192 {
193 ERROR ("mqtt plugin: format_topic failed with status %d.", status);
194 return (status);
195 }
197 status = format_values (payload, sizeof (payload),
198 ds, vl, store_rates);
199 if (status != 0)
200 {
201 ERROR ("mqtt plugin: format_values failed with status %d.", status);
202 return (status);
203 }
205 status = publish (conf, topic, payload, sizeof (payload));
206 if (status != 0)
207 {
208 ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
209 return (status);
210 }
212 return (status);
213 } /* mqtt_write */
215 /*
216 * <Plugin mqtt>
217 * Host "example.com"
218 * Port 1883
219 * Prefix "collectd"
220 * ClientId "collectd"
221 * </Plugin>
222 */
223 static int mqtt_config (oconfig_item_t *ci)
224 {
225 mqtt_client_conf_t *conf;
226 user_data_t user_data;
227 int status;
228 int i;
230 conf = calloc (1, sizeof (*conf));
231 if (conf == NULL)
232 {
233 ERROR ("mqtt plugin: malloc failed.");
234 return (-1);
235 }
237 conf->connected = false;
238 conf->host = strdup (MQTT_DEFAULT_HOST);
239 conf->port = MQTT_DEFAULT_PORT;
240 conf->client_id = strdup (MQTT_DEFAULT_CLIENT_ID);
241 conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
242 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
244 for (i = 0; i < ci->children_num; i++)
245 {
246 oconfig_item_t *child = ci->children + i;
247 if (strcasecmp ("Host", child->key) == 0)
248 cf_util_get_string (child, &conf->host);
249 else if (strcasecmp ("Port", child->key) == 0)
250 {
251 int tmp = cf_util_get_port_number (child);
252 if (tmp < 0)
253 {
254 ERROR ("mqtt plugin: Invalid port number.");
255 continue;
256 }
257 conf->port = tmp;
258 }
259 else if (strcasecmp ("Prefix", child->key) == 0)
260 cf_util_get_string (child, &conf->topic_prefix);
261 else if (strcasecmp ("ClientId", child->key) == 0)
262 cf_util_get_string (child, &conf->client_id);
263 else
264 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
265 }
267 memset (&user_data, 0, sizeof (user_data));
268 user_data.data = conf;
270 conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
271 if (conf->mosq == NULL)
272 {
273 ERROR ("mqtt plugin: mosquitto_new failed");
274 free (conf);
275 return (-1);
276 }
278 status = mosquitto_connect (conf->mosq, conf->host, conf->port,
279 /* keepalive = */ 10, /* clean session = */ 1);
280 if (status != MOSQ_ERR_SUCCESS)
281 {
282 char errbuf[1024];
283 ERROR ("mqtt plugin: mosquitto_connect failed: %s",
284 (status == MOSQ_ERR_ERRNO)
285 ? sstrerror (errno, errbuf, sizeof (errbuf))
286 : mosquitto_strerror (status));
287 free (conf);
288 return (-1);
289 }
291 DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
292 conf->host, conf->port);
294 conf->connected = true;
296 plugin_register_write ("mqtt", mqtt_write, &user_data);
298 return (0);
299 } /* mqtt_config */
301 static int mqtt_init (void)
302 {
303 mosquitto_lib_init();
305 return (0);
306 } /* mqtt_init */
308 void module_register (void)
309 {
310 plugin_register_complex_config ("mqtt", mqtt_config);
311 plugin_register_init ("mqtt", mqtt_init);
312 } /* void module_register */
314 /* vim: set sw=4 sts=4 et fdm=marker : */