mqtt plugin: Rename mqtt_publish_message() to publish().
[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 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;
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             (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;
148
149         pthread_mutex_unlock (&conf->lock);
150         return (-1);
151     }
152
153     pthread_mutex_unlock (&conf->lock);
154     return (0);
155 } /* int publish */
156
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;
163
164     if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
165         return (FORMAT_VL (buf, buf_len, vl));
166
167     status = FORMAT_VL (name, sizeof (name), vl);
168     if (status != 0)
169         return (status);
170
171     status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
172     if ((status < 0) || (((size_t) status) >= buf_len))
173         return (ENOMEM);
174
175     return (0);
176 } /* int format_topic */
177
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 */
186
187     if ((user_data == NULL) || (user_data->data == NULL))
188         return (EINVAL);
189     conf = user_data->data;
190
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     }
196
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     }
204
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     }
211
212     return (status);
213 } /* mqtt_write */
214
215 static int mqtt_config (oconfig_item_t *ci)
216 {
217     mqtt_client_conf_t *conf;
218     user_data_t user_data;
219     int status;
220
221     conf = calloc (1, sizeof (*conf));
222     if (conf == NULL)
223     {
224         ERROR ("mqtt plugin: malloc failed.");
225         return (-1);
226     }
227
228     conf->connected = false;
229     conf->host = MQTT_DEFAULT_HOST;
230     conf->port = MQTT_DEFAULT_PORT;
231     conf->client_id = MQTT_DEFAULT_CLIENT_ID;
232     conf->topic_prefix = MQTT_DEFAULT_TOPIC_PREFIX;
233     C_COMPLAIN_INIT (&conf->complaint_cantpublish);
234
235     memset (&user_data, 0, sizeof (user_data));
236     user_data.data = conf;
237
238     conf->mosq = mosquitto_new (conf->client_id, /* user data = */ conf);
239     if (conf->mosq == NULL)
240     {
241         ERROR ("mqtt plugin: mosquitto_new failed");
242         free (conf);
243         return (-1);
244     }
245
246     status = mosquitto_connect (conf->mosq, conf->host, conf->port,
247             /* keepalive = */ 10, /* clean session = */ 1);
248     if (status != MOSQ_ERR_SUCCESS)
249     {
250         char errbuf[1024];
251         ERROR ("mqtt plugin: mosquitto_connect failed: %s",
252                 (status == MOSQ_ERR_ERRNO)
253                 ? sstrerror (errno, errbuf, sizeof (errbuf))
254                 : mosquitto_strerror (status));
255         free (conf);
256         return (-1);
257     }
258
259     DEBUG ("mqtt plugin: successfully connected to broker \"%s:%d\"",
260         conf->host, conf->port);
261
262     conf->connected = true;
263
264     plugin_register_write ("mqtt", mqtt_write, &user_data);
265
266     return (0);
267 } /* mqtt_config */
268
269 static int mqtt_init (void)
270 {
271     mosquitto_lib_init();
272
273     return (0);
274 } /* mqtt_init */
275
276 void module_register (void)
277 {
278     plugin_register_complex_config ("mqtt", mqtt_config);
279     plugin_register_init ("mqtt", mqtt_init);
280 } /* void module_register */
281
282 /* vim: set sw=4 sts=4 et fdm=marker : */