2 * collectd - src/mqtt.c
3 * Copyright (C) 2014 Marc Falzon
4 * Copyright (C) 2014,2015 Florian octo Forster
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
25 * Marc Falzon <marc at baha dot mu>
26 * Florian octo Forster <octo at collectd.org>
29 // Reference: http://mosquitto.org/api/files/mosquitto-h.html
35 #include "utils_cache.h"
36 #include "utils_complain.h"
40 #include <mosquitto.h>
42 #define MQTT_MAX_TOPIC_SIZE 1024
43 #define MQTT_MAX_MESSAGE_SIZE MQTT_MAX_TOPIC_SIZE + 1024
44 #define MQTT_DEFAULT_HOST "localhost"
45 #define MQTT_DEFAULT_PORT 1883
46 #define MQTT_DEFAULT_TOPIC_PREFIX "collectd"
47 #define MQTT_DEFAULT_TOPIC "collectd/#"
48 #ifndef MQTT_KEEPALIVE
49 # define MQTT_KEEPALIVE 60
56 struct mqtt_client_conf
61 struct mosquitto *mosq;
82 c_complain_t complaint_cantpublish;
85 typedef struct mqtt_client_conf mqtt_client_conf_t;
87 static mqtt_client_conf_t **subscribers = NULL;
88 static size_t subscribers_num = 0;
93 #if LIBMOSQUITTO_MAJOR == 0
94 static char const *mosquitto_strerror (int code)
98 case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
99 case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
100 case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
101 case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
102 case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
103 case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
104 case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
105 case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
106 case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
107 case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
108 case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
109 case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
110 case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
111 case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
112 case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
115 return "UNKNOWN ERROR CODE";
118 /* provided by libmosquitto */
121 static void mqtt_free (mqtt_client_conf_t *conf)
127 (void) mosquitto_disconnect (conf->mosq);
129 (void) mosquitto_destroy (conf->mosq);
132 sfree (conf->username);
133 sfree (conf->password);
134 sfree (conf->client_id);
135 sfree (conf->topic_prefix);
139 static char *strip_prefix (char *topic)
145 for (i = 0; topic[i] != 0; i++)
154 char *tmp = strchr (topic, '/');
164 static void on_message (
165 #if LIBMOSQUITTO_MAJOR == 0
167 __attribute__((unused)) struct mosquitto *m,
169 __attribute__((unused)) void *arg,
170 const struct mosquitto_message *msg)
172 value_list_t vl = VALUE_LIST_INIT;
173 data_set_t const *ds;
179 if ((msg->payloadlen <= 0)
180 || (((uint8_t *) msg->payload)[msg->payloadlen - 1] != 0))
183 topic = strdup (msg->topic);
184 name = strip_prefix (topic);
186 status = parse_identifier_vl (name, &vl);
189 ERROR ("mqtt plugin: Unable to parse topic \"%s\".", topic);
195 ds = plugin_get_ds (vl.type);
198 ERROR ("mqtt plugin: Unknown type: \"%s\".", vl.type);
202 vl.values = calloc (ds->ds_num, sizeof (*vl.values));
203 if (vl.values == NULL)
205 ERROR ("mqtt plugin: calloc failed.");
208 vl.values_len = ds->ds_num;
210 payload = strdup ((void *) msg->payload);
211 DEBUG ("mqtt plugin: payload = \"%s\"", payload);
212 status = parse_values (payload, &vl, ds);
215 ERROR ("mqtt plugin: Unable to parse payload \"%s\".", payload);
222 plugin_dispatch_values (&vl);
224 } /* void on_message */
226 /* must hold conf->lock when calling. */
227 static int mqtt_reconnect (mqtt_client_conf_t *conf)
234 status = mosquitto_reconnect (conf->mosq);
235 if (status != MOSQ_ERR_SUCCESS)
238 ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
239 (status == MOSQ_ERR_ERRNO)
240 ? sstrerror(errno, errbuf, sizeof (errbuf))
241 : mosquitto_strerror (status));
248 &conf->complaint_cantpublish,
249 "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
250 conf->host, conf->port);
253 } /* mqtt_reconnect */
255 /* must hold conf->lock when calling. */
256 static int mqtt_connect (mqtt_client_conf_t *conf)
258 char const *client_id;
261 if (conf->mosq != NULL)
262 return mqtt_reconnect (conf);
265 client_id = conf->client_id;
267 client_id = hostname_g;
269 #if LIBMOSQUITTO_MAJOR == 0
270 conf->mosq = mosquitto_new (client_id, /* user data = */ conf);
272 conf->mosq = mosquitto_new (client_id, conf->clean_session, /* user data = */ conf);
274 if (conf->mosq == NULL)
276 ERROR ("mqtt plugin: mosquitto_new failed");
280 if (conf->username && conf->password)
282 status = mosquitto_username_pw_set (conf->mosq, conf->username, conf->password);
283 if (status != MOSQ_ERR_SUCCESS)
286 ERROR ("mqtt plugin: mosquitto_username_pw_set failed: %s",
287 (status == MOSQ_ERR_ERRNO)
288 ? sstrerror (errno, errbuf, sizeof (errbuf))
289 : mosquitto_strerror (status));
291 mosquitto_destroy (conf->mosq);
297 #if LIBMOSQUITTO_MAJOR == 0
298 status = mosquitto_connect (conf->mosq, conf->host, conf->port,
299 /* keepalive = */ MQTT_KEEPALIVE, /* clean session = */ conf->clean_session);
301 status = mosquitto_connect (conf->mosq, conf->host, conf->port, MQTT_KEEPALIVE);
303 if (status != MOSQ_ERR_SUCCESS)
306 ERROR ("mqtt plugin: mosquitto_connect failed: %s",
307 (status == MOSQ_ERR_ERRNO)
308 ? sstrerror (errno, errbuf, sizeof (errbuf))
309 : mosquitto_strerror (status));
311 mosquitto_destroy (conf->mosq);
318 mosquitto_message_callback_set (conf->mosq, on_message);
320 status = mosquitto_subscribe (conf->mosq,
321 /* message_id = */ NULL,
322 conf->topic, conf->qos);
323 if (status != MOSQ_ERR_SUCCESS)
325 ERROR ("mqtt plugin: Subscribing to \"%s\" failed: %s",
326 conf->topic, mosquitto_strerror (status));
328 mosquitto_disconnect (conf->mosq);
329 mosquitto_destroy (conf->mosq);
339 static void *subscribers_thread (void *arg)
341 mqtt_client_conf_t *conf = arg;
348 status = mqtt_connect (conf);
355 /* The documentation says "0" would map to the default (1000ms), but
356 * that does not work on some versions. */
357 #if LIBMOSQUITTO_MAJOR == 0
358 status = mosquitto_loop (conf->mosq, /* timeout = */ 1000 /* ms */);
360 status = mosquitto_loop (conf->mosq,
361 /* timeout[ms] = */ 1000,
362 /* max_packets = */ 100);
364 if (status == MOSQ_ERR_CONN_LOST)
369 else if (status != MOSQ_ERR_SUCCESS)
371 ERROR ("mqtt plugin: mosquitto_loop failed: %s",
372 mosquitto_strerror (status));
373 mosquitto_destroy (conf->mosq);
379 DEBUG ("mqtt plugin: mosquitto_loop succeeded.");
380 } /* while (conf->loop) */
383 } /* void *subscribers_thread */
385 static int publish (mqtt_client_conf_t *conf, char const *topic,
386 void const *payload, size_t payload_len)
390 pthread_mutex_lock (&conf->lock);
392 status = mqtt_connect (conf);
394 pthread_mutex_unlock (&conf->lock);
395 ERROR ("mqtt plugin: unable to reconnect to broker");
399 status = mosquitto_publish(conf->mosq, /* message_id */ NULL, topic,
400 #if LIBMOSQUITTO_MAJOR == 0
401 (uint32_t) payload_len, payload,
403 (int) payload_len, payload,
405 conf->qos, conf->retain);
406 if (status != MOSQ_ERR_SUCCESS)
410 &conf->complaint_cantpublish,
411 "mqtt plugin: mosquitto_publish failed: %s",
412 (status == MOSQ_ERR_ERRNO)
413 ? sstrerror(errno, errbuf, sizeof (errbuf))
414 : mosquitto_strerror(status));
415 /* Mark our connection "down" regardless of the error as a safety
416 * measure; we will try to reconnect the next time we have to publish a
420 pthread_mutex_unlock (&conf->lock);
424 pthread_mutex_unlock (&conf->lock);
428 static int format_topic (char *buf, size_t buf_len,
429 data_set_t const *ds, value_list_t const *vl,
430 mqtt_client_conf_t *conf)
432 char name[MQTT_MAX_TOPIC_SIZE];
435 if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
436 return (FORMAT_VL (buf, buf_len, vl));
438 status = FORMAT_VL (name, sizeof (name), vl);
442 status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
443 if ((status < 0) || (((size_t) status) >= buf_len))
447 } /* int format_topic */
449 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
450 user_data_t *user_data)
452 mqtt_client_conf_t *conf;
453 char topic[MQTT_MAX_TOPIC_SIZE];
454 char payload[MQTT_MAX_MESSAGE_SIZE];
457 if ((user_data == NULL) || (user_data->data == NULL))
459 conf = user_data->data;
461 status = format_topic (topic, sizeof (topic), ds, vl, conf);
464 ERROR ("mqtt plugin: format_topic failed with status %d.", status);
468 status = format_values (payload, sizeof (payload),
469 ds, vl, conf->store_rates);
472 ERROR ("mqtt plugin: format_values failed with status %d.", status);
476 status = publish (conf, topic, payload, strlen (payload) + 1);
479 ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
490 * ClientId "collectd"
499 static int mqtt_config_publisher (oconfig_item_t *ci)
501 mqtt_client_conf_t *conf;
503 user_data_t user_data;
507 conf = calloc (1, sizeof (*conf));
510 ERROR ("mqtt plugin: malloc failed.");
516 status = cf_util_get_string (ci, &conf->name);
523 conf->host = strdup (MQTT_DEFAULT_HOST);
524 conf->port = MQTT_DEFAULT_PORT;
525 conf->client_id = NULL;
527 conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
528 conf->store_rates = 1;
530 status = pthread_mutex_init (&conf->lock, NULL);
537 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
539 for (i = 0; i < ci->children_num; i++)
541 oconfig_item_t *child = ci->children + i;
542 if (strcasecmp ("Host", child->key) == 0)
543 cf_util_get_string (child, &conf->host);
544 else if (strcasecmp ("Port", child->key) == 0)
546 int tmp = cf_util_get_port_number (child);
548 ERROR ("mqtt plugin: Invalid port number.");
552 else if (strcasecmp ("ClientId", child->key) == 0)
553 cf_util_get_string (child, &conf->client_id);
554 else if (strcasecmp ("User", child->key) == 0)
555 cf_util_get_string (child, &conf->username);
556 else if (strcasecmp ("Password", child->key) == 0)
557 cf_util_get_string (child, &conf->password);
558 else if (strcasecmp ("QoS", child->key) == 0)
561 status = cf_util_get_int (child, &tmp);
562 if ((status != 0) || (tmp < 0) || (tmp > 2))
563 ERROR ("mqtt plugin: Not a valid QoS setting.");
567 else if (strcasecmp ("Prefix", child->key) == 0)
568 cf_util_get_string (child, &conf->topic_prefix);
569 else if (strcasecmp ("StoreRates", child->key) == 0)
570 cf_util_get_boolean (child, &conf->store_rates);
571 else if (strcasecmp ("Retain", child->key) == 0)
572 cf_util_get_boolean (child, &conf->retain);
574 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
577 ssnprintf (cb_name, sizeof (cb_name), "mqtt/%s", conf->name);
578 memset (&user_data, 0, sizeof (user_data));
579 user_data.data = conf;
581 plugin_register_write (cb_name, mqtt_write, &user_data);
583 } /* mqtt_config_publisher */
589 * ClientId "collectd"
595 static int mqtt_config_subscriber (oconfig_item_t *ci)
597 mqtt_client_conf_t **tmp;
598 mqtt_client_conf_t *conf;
602 conf = calloc (1, sizeof (*conf));
605 ERROR ("mqtt plugin: malloc failed.");
611 status = cf_util_get_string (ci, &conf->name);
618 conf->host = strdup (MQTT_DEFAULT_HOST);
619 conf->port = MQTT_DEFAULT_PORT;
620 conf->client_id = NULL;
622 conf->topic = strdup (MQTT_DEFAULT_TOPIC);
623 conf->clean_session = 1;
625 status = pthread_mutex_init (&conf->lock, NULL);
632 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
634 for (i = 0; i < ci->children_num; i++)
636 oconfig_item_t *child = ci->children + i;
637 if (strcasecmp ("Host", child->key) == 0)
638 cf_util_get_string (child, &conf->host);
639 else if (strcasecmp ("Port", child->key) == 0)
641 int tmp = cf_util_get_port_number (child);
643 ERROR ("mqtt plugin: Invalid port number.");
647 else if (strcasecmp ("ClientId", child->key) == 0)
648 cf_util_get_string (child, &conf->client_id);
649 else if (strcasecmp ("User", child->key) == 0)
650 cf_util_get_string (child, &conf->username);
651 else if (strcasecmp ("Password", child->key) == 0)
652 cf_util_get_string (child, &conf->password);
653 else if (strcasecmp ("QoS", child->key) == 0)
656 status = cf_util_get_int (child, &tmp);
657 if ((status != 0) || (tmp < 0) || (tmp > 2))
658 ERROR ("mqtt plugin: Not a valid QoS setting.");
662 else if (strcasecmp ("Topic", child->key) == 0)
663 cf_util_get_string (child, &conf->topic);
664 else if (strcasecmp ("CleanSession", child->key) == 0)
665 cf_util_get_boolean (child, &conf->clean_session);
667 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
670 tmp = realloc (subscribers, sizeof (*subscribers) * subscribers_num);
673 ERROR ("mqtt plugin: realloc failed.");
678 subscribers[subscribers_num] = conf;
682 } /* mqtt_config_subscriber */
694 static int mqtt_config (oconfig_item_t *ci)
698 for (i = 0; i < ci->children_num; i++)
700 oconfig_item_t *child = ci->children + i;
702 if (strcasecmp ("Publish", child->key) == 0)
703 mqtt_config_publisher (child);
704 else if (strcasecmp ("Subscribe", child->key) == 0)
705 mqtt_config_subscriber (child);
707 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
711 } /* int mqtt_config */
713 static int mqtt_init (void)
717 mosquitto_lib_init ();
719 for (i = 0; i < subscribers_num; i++)
723 if (subscribers[i]->loop)
726 status = plugin_thread_create (&subscribers[i]->thread,
728 /* func = */ subscribers_thread,
729 /* args = */ subscribers[i]);
733 ERROR ("mqtt plugin: pthread_create failed: %s",
734 sstrerror (errno, errbuf, sizeof (errbuf)));
742 void module_register (void)
744 plugin_register_complex_config ("mqtt", mqtt_config);
745 plugin_register_init ("mqtt", mqtt_init);
746 } /* void module_register */
748 /* vim: set sw=4 sts=4 et fdm=marker : */