Code

mqtt plugin: Use the thread-safe sstrerror().
[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  **/
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         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     }
106     conf->connected = 1;
108     c_release (LOG_INFO,
109             &conf->complaint_cantpublish,
110             "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
111             conf->host, conf->port);
113     return (0);
114 } /* mqtt_reconnect_broker */
116 static int publish (mqtt_client_conf_t *conf, char const *topic,
117     void const *payload, size_t payload_len)
119     int const qos = 0; /* TODO: Config option */
120     int status;
122     pthread_mutex_lock (&conf->lock);
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     }
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;
151         pthread_mutex_unlock (&conf->lock);
152         return (-1);
153     }
155     pthread_mutex_unlock (&conf->lock);
156     return (0);
157 } /* int publish */
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)
163     char name[MQTT_MAX_TOPIC_SIZE];
164     int status;
166     if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
167         return (FORMAT_VL (buf, buf_len, vl));
169     status = FORMAT_VL (name, sizeof (name), vl);
170     if (status != 0)
171         return (status);
173     status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
174     if ((status < 0) || (((size_t) status) >= buf_len))
175         return (ENOMEM);
177     return (0);
178 } /* int format_topic */
180 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
181     user_data_t *user_data)
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 */
189     if ((user_data == NULL) || (user_data->data == NULL))
190         return (EINVAL);
191     conf = user_data->data;
193     status = format_topic (topic, sizeof (topic), ds, vl, conf);
194     {
195         ERROR ("mqtt plugin: format_topic failed with status %d.", status);
196         return (status);
197     }
199     status = format_values (payload, sizeof (payload),
200             ds, vl, store_rates);
201     if (status != 0)
202     {
203         ERROR ("mqtt plugin: format_values failed with status %d.", status);
204         return (status);
205     }
207     status = publish (conf, topic, payload, sizeof (payload));
208     if (status != 0)
209     {
210         ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
211         return (status);
212     }
214     return (status);
215 } /* mqtt_write */
217 /*
218  * <Plugin mqtt>
219  *   Host "example.com"
220  *   Port 1883
221  *   Prefix "collectd"
222  *   ClientId "collectd"
223  * </Plugin>
224  */
225 static int mqtt_config (oconfig_item_t *ci)
227     mqtt_client_conf_t *conf;
228     user_data_t user_data;
229     int status;
230     int i;
232     conf = calloc (1, sizeof (*conf));
233     if (conf == NULL)
234     {
235         ERROR ("mqtt plugin: malloc failed.");
236         return (-1);
237     }
239     conf->connected = 0;
240     conf->host = strdup (MQTT_DEFAULT_HOST);
241     conf->port = MQTT_DEFAULT_PORT;
242     conf->client_id = strdup (MQTT_DEFAULT_CLIENT_ID);
243     conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
244     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
246     for (i = 0; i < ci->children_num; i++)
247     {
248         oconfig_item_t *child = ci->children + i;
249         if (strcasecmp ("Host", child->key) == 0)
250             cf_util_get_string (child, &conf->host);
251         else if (strcasecmp ("Port", child->key) == 0)
252         {
253             int tmp = cf_util_get_port_number (child);
254             if (tmp < 0)
255             {
256                 ERROR ("mqtt plugin: Invalid port number.");
257                 continue;
258             }
259             conf->port = tmp;
260         }
261         else if (strcasecmp ("Prefix", child->key) == 0)
262             cf_util_get_string (child, &conf->topic_prefix);
263         else if (strcasecmp ("ClientId", child->key) == 0)
264             cf_util_get_string (child, &conf->client_id);
265         else
266             ERROR ("mqtt plugin: Unknown config option: %s", child->key);
267     }
269     memset (&user_data, 0, sizeof (user_data));
270     user_data.data = conf;
272     conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
273     if (conf->mosq == NULL)
274     {
275         ERROR ("mqtt plugin: mosquitto_new failed");
276         free (conf);
277         return (-1);
278     }
280     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
281             /* keepalive = */ 10, /* clean session = */ 1);
282     if (status != MOSQ_ERR_SUCCESS)
283     {
284         char errbuf[1024];
285         ERROR ("mqtt plugin: mosquitto_connect failed: %s",
286                 (status == MOSQ_ERR_ERRNO)
287                 ? sstrerror (errno, errbuf, sizeof (errbuf))
288                 : mosquitto_strerror (status));
289         free (conf);
290         return (-1);
291     }
293     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
294         conf->host, conf->port);
296     conf->connected = 1;
298     plugin_register_write ("mqtt", mqtt_write, &user_data);
300     return (0);
301 } /* mqtt_config */
303 static int mqtt_init (void)
305     mosquitto_lib_init();
307     return (0);
308 } /* mqtt_init */
310 void module_register (void)
312     plugin_register_complex_config ("mqtt", mqtt_config);
313     plugin_register_init ("mqtt", mqtt_init);
314 } /* void module_register */
316 /* vim: set sw=4 sts=4 et fdm=marker : */