ef46e529375c9d3171562f5c1332c9541aa19dbb
[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         ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
99             (status == MOSQ_ERR_ERRNO ?
100                 strerror(errno) : mosquitto_strerror (status)));
101         return (-1);
102     }
103
104     conf->connected = true;
105
106     c_release (LOG_INFO,
107         &conf->complaint_cantpublish,
108         "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
109         conf->host, conf->port);
110
111     return (0);
112 } /* mqtt_reconnect_broker */
113
114 static int mqtt_publish_message (mqtt_client_conf_t *conf, char *topic,
115     void const *payload, size_t payload_len)
116 {
117     char errbuf[1024];
118     int status;
119
120     pthread_mutex_lock (&conf->lock);
121
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     }
128
129     status = mosquitto_publish(conf->mosq,
130         /* message id */ NULL,
131         topic,
132         (int) payload_len,
133         payload,
134         /* qos */ 0,
135         /* retain */ false);
136     if (status != MOSQ_ERR_SUCCESS)
137     {
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         /*
145         Mark our connection "down" regardless of the error as a safety measure;
146         we will try to reconnect the next time we have to publish a message
147         */
148         conf->connected = false;
149
150         pthread_mutex_unlock (&conf->lock);
151         return (-1);
152     }
153
154     pthread_mutex_unlock (&conf->lock);
155     return (0);
156 } /* mqtt_publish_message */
157
158 static int format_topic (char *buf, size_t buf_len,
159     data_set_t const *ds, value_list_t const *vl,
160     mqtt_client_conf_t *conf)
161 {
162     char name[MQTT_MAX_TOPIC_SIZE];
163     int status;
164
165     if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
166         return (FORMAT_VL (buf, buf_len, vl));
167
168     status = FORMAT_VL (name, sizeof (name), vl);
169     if (status != 0)
170         return (status);
171
172     status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
173     if ((status < 0) || (((size_t) status) >= buf_len))
174         return (ENOMEM);
175
176     return (0);
177 } /* int format_topic */
178
179 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
180     user_data_t *user_data)
181 {
182     mqtt_client_conf_t *conf;
183     char topic[MQTT_MAX_TOPIC_SIZE];
184     char payload[MQTT_MAX_MESSAGE_SIZE];
185     int status = 0;
186     _Bool const store_rates = 0; /* TODO: Config option */
187
188     if ((user_data == NULL) || (user_data->data == NULL))
189         return (EINVAL);
190     conf = user_data->data;
191
192     status = format_topic (topic, sizeof (topic), ds, vl, conf);
193     {
194         ERROR ("mqtt plugin: format_topic failed with status %d.", status);
195         return (status);
196     }
197
198     status = format_values (payload, sizeof (payload),
199             ds, vl, store_rates);
200     if (status != 0)
201     {
202         ERROR ("mqtt plugin: format_values failed with status %d.", status);
203         return (status);
204     }
205
206     status = publish (conf, topic, payload, sizeof (payload));
207     if (status != 0)
208     {
209         ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
210         return (status);
211     }
212
213     return (status);
214 } /* mqtt_write */
215
216 static int mqtt_config (oconfig_item_t *ci)
217 {
218     mqtt_client_conf_t *conf;
219     user_data_t user_data;
220     int status;
221
222     conf = calloc (1, sizeof (*conf));
223     if (conf == NULL)
224     {
225         ERROR ("mqtt plugin: malloc failed.");
226         return (-1);
227     }
228
229     conf->connected = false;
230     conf->host = MQTT_DEFAULT_HOST;
231     conf->port = MQTT_DEFAULT_PORT;
232     conf->client_id = MQTT_DEFAULT_CLIENT_ID;
233     conf->topic_prefix = MQTT_DEFAULT_TOPIC_PREFIX;
234     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
235
236     memset (&user_data, 0, sizeof (user_data));
237     user_data.data = conf;
238
239     conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
240     if (conf->mosq == NULL)
241     {
242         ERROR ("mqtt plugin: mosquitto_new failed");
243         free (conf);
244         return (-1);
245     }
246
247     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
248             /* keepalive = */ 10, /* clean session = */ 1);
249     if (status != MOSQ_ERR_SUCCESS)
250     {
251         char errbuf[1024];
252         ERROR ("mqtt plugin: mosquitto_connect failed: %s",
253                 (status == MOSQ_ERR_ERRNO)
254                 ? sstrerror (errno, errbuf, sizeof (errbuf))
255                 : mosquitto_strerror (status));
256         free (conf);
257         return (-1);
258     }
259
260     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
261         conf->host, conf->port);
262
263     conf->connected = true;
264
265     plugin_register_write ("mqtt", mqtt_write, &user_data);
266
267     return (0);
268 } /* mqtt_config */
269
270 static int mqtt_init (void)
271 {
272     mosquitto_lib_init();
273
274     return (0);
275 } /* mqtt_init */
276
277 void module_register (void)
278 {
279     plugin_register_complex_config ("mqtt", mqtt_config);
280     plugin_register_init ("mqtt", mqtt_init);
281 } /* void module_register */
282
283 /* vim: set sw=4 sts=4 et fdm=marker : */