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/#"
52 struct mqtt_client_conf
57 struct mosquitto *mosq;
78 c_complain_t complaint_cantpublish;
81 typedef struct mqtt_client_conf mqtt_client_conf_t;
83 static mqtt_client_conf_t **subscribers = NULL;
84 static size_t subscribers_num = 0;
89 static char const *mosquitto_strerror (int code)
93 case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
94 case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
95 case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
96 case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
97 case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
98 case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
99 case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
100 case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
101 case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
102 case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
103 case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
104 case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
105 case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
106 case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
107 case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
110 return "UNKNOWN ERROR CODE";
113 static void mqtt_free (mqtt_client_conf_t *conf)
119 (void) mosquitto_disconnect (conf->mosq);
121 (void) mosquitto_destroy (conf->mosq);
124 sfree (conf->username);
125 sfree (conf->password);
126 sfree (conf->client_id);
127 sfree (conf->topic_prefix);
131 static char *strip_prefix (char *topic)
137 for (i = 0; topic[i] != 0; i++)
146 char *tmp = strchr (topic, '/');
156 static void on_message (__attribute__((unused)) void *arg,
157 const struct mosquitto_message *msg)
159 value_list_t vl = VALUE_LIST_INIT;
160 data_set_t const *ds;
166 if ((msg->payloadlen <= 0) || (msg->payload[msg->payloadlen - 1] != 0))
169 topic = strdup (msg->topic);
170 name = strip_prefix (topic);
172 status = parse_identifier_vl (name, &vl);
175 ERROR ("mqtt plugin: Unable to parse topic \"%s\".", topic);
181 ds = plugin_get_ds (vl.type);
184 ERROR ("mqtt plugin: Unknown type: \"%s\".", vl.type);
188 vl.values = calloc (ds->ds_num, sizeof (*vl.values));
189 if (vl.values == NULL)
191 ERROR ("mqtt plugin: calloc failed.");
194 vl.values_len = ds->ds_num;
196 payload = strdup ((void *) msg->payload);
197 DEBUG ("mqtt plugin: payload = \"%s\"", payload);
198 status = parse_values (payload, &vl, ds);
201 ERROR ("mqtt plugin: Unable to parse payload \"%s\".", payload);
208 plugin_dispatch_values (&vl);
210 } /* void on_message */
212 /* must hold conf->lock when calling. */
213 static int mqtt_reconnect (mqtt_client_conf_t *conf)
220 status = mosquitto_reconnect (conf->mosq);
221 if (status != MOSQ_ERR_SUCCESS)
224 ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
225 (status == MOSQ_ERR_ERRNO)
226 ? sstrerror(errno, errbuf, sizeof (errbuf))
227 : mosquitto_strerror (status));
234 &conf->complaint_cantpublish,
235 "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
236 conf->host, conf->port);
239 } /* mqtt_reconnect */
241 /* must hold conf->lock when calling. */
242 static int mqtt_connect (mqtt_client_conf_t *conf)
244 char const *client_id;
247 if (conf->mosq != NULL)
248 return mqtt_reconnect (conf);
251 client_id = conf->client_id;
253 client_id = hostname_g;
255 conf->mosq = mosquitto_new (client_id, /* user data = */ conf);
256 if (conf->mosq == NULL)
258 ERROR ("mqtt plugin: mosquitto_new failed");
262 if (conf->username && conf->password)
264 status = mosquitto_username_pw_set (conf->mosq, conf->username, conf->password);
265 if (status != MOSQ_ERR_SUCCESS)
268 ERROR ("mqtt plugin: mosquitto_username_pw_set failed: %s",
269 (status == MOSQ_ERR_ERRNO)
270 ? sstrerror (errno, errbuf, sizeof (errbuf))
271 : mosquitto_strerror (status));
273 mosquitto_destroy (conf->mosq);
279 status = mosquitto_connect (conf->mosq, conf->host, conf->port,
280 /* keepalive = */ 10, /* clean session = */ conf->clean_session);
281 if (status != MOSQ_ERR_SUCCESS)
284 ERROR ("mqtt plugin: mosquitto_connect failed: %s",
285 (status == MOSQ_ERR_ERRNO)
286 ? sstrerror (errno, errbuf, sizeof (errbuf))
287 : mosquitto_strerror (status));
289 mosquitto_destroy (conf->mosq);
296 mosquitto_message_callback_set (conf->mosq, on_message);
298 status = mosquitto_subscribe (conf->mosq, /* mid = */ NULL,
299 conf->topic, conf->qos);
300 if (status != MOSQ_ERR_SUCCESS)
302 ERROR ("mqtt plugin: Subscribing to \"%s\" failed: %s",
303 conf->topic, mosquitto_strerror (status));
305 mosquitto_disconnect (conf->mosq);
306 mosquitto_destroy (conf->mosq);
316 static void *subscribers_thread (void *arg)
318 mqtt_client_conf_t *conf = arg;
325 status = mqtt_connect (conf);
332 /* The documentation says "0" would map to the default (1000ms), but
333 * that does not work on some versions. */
334 status = mosquitto_loop (conf->mosq, /* timeout = */ 1000 /* ms */);
335 if (status == MOSQ_ERR_CONN_LOST)
340 else if (status != MOSQ_ERR_SUCCESS)
342 ERROR ("mqtt plugin: mosquitto_loop failed: %s",
343 mosquitto_strerror (status));
344 mosquitto_destroy (conf->mosq);
350 DEBUG ("mqtt plugin: mosquitto_loop succeeded.");
351 } /* while (conf->loop) */
354 } /* void *subscribers_thread */
356 static int publish (mqtt_client_conf_t *conf, char const *topic,
357 void const *payload, size_t payload_len)
361 pthread_mutex_lock (&conf->lock);
363 status = mqtt_connect (conf);
365 pthread_mutex_unlock (&conf->lock);
366 ERROR ("mqtt plugin: unable to reconnect to broker");
370 status = mosquitto_publish(conf->mosq,
371 /* message id */ NULL,
373 (uint32_t) payload_len, payload,
375 /* retain */ conf->retain);
376 if (status != MOSQ_ERR_SUCCESS)
380 &conf->complaint_cantpublish,
381 "plugin mqtt: mosquitto_publish failed: %s",
382 status == MOSQ_ERR_ERRNO ?
383 sstrerror(errno, errbuf, sizeof (errbuf)) :
384 mosquitto_strerror(status));
385 /* Mark our connection "down" regardless of the error as a safety
386 * measure; we will try to reconnect the next time we have to publish a
390 pthread_mutex_unlock (&conf->lock);
394 pthread_mutex_unlock (&conf->lock);
398 static int format_topic (char *buf, size_t buf_len,
399 data_set_t const *ds, value_list_t const *vl,
400 mqtt_client_conf_t *conf)
402 char name[MQTT_MAX_TOPIC_SIZE];
405 if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
406 return (FORMAT_VL (buf, buf_len, vl));
408 status = FORMAT_VL (name, sizeof (name), vl);
412 status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
413 if ((status < 0) || (((size_t) status) >= buf_len))
417 } /* int format_topic */
419 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
420 user_data_t *user_data)
422 mqtt_client_conf_t *conf;
423 char topic[MQTT_MAX_TOPIC_SIZE];
424 char payload[MQTT_MAX_MESSAGE_SIZE];
427 if ((user_data == NULL) || (user_data->data == NULL))
429 conf = user_data->data;
431 status = format_topic (topic, sizeof (topic), ds, vl, conf);
434 ERROR ("mqtt plugin: format_topic failed with status %d.", status);
438 status = format_values (payload, sizeof (payload),
439 ds, vl, conf->store_rates);
442 ERROR ("mqtt plugin: format_values failed with status %d.", status);
446 status = publish (conf, topic, payload, strlen (payload) + 1);
449 ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
460 * ClientId "collectd"
469 static int mqtt_config_publisher (oconfig_item_t *ci)
471 mqtt_client_conf_t *conf;
472 user_data_t user_data;
476 conf = calloc (1, sizeof (*conf));
479 ERROR ("mqtt plugin: malloc failed.");
485 status = cf_util_get_string (ci, &conf->name);
492 conf->host = strdup (MQTT_DEFAULT_HOST);
493 conf->port = MQTT_DEFAULT_PORT;
494 conf->client_id = NULL;
495 conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
497 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
499 for (i = 0; i < ci->children_num; i++)
501 oconfig_item_t *child = ci->children + i;
502 if (strcasecmp ("Host", child->key) == 0)
503 cf_util_get_string (child, &conf->host);
504 else if (strcasecmp ("Port", child->key) == 0)
506 int tmp = cf_util_get_port_number (child);
508 ERROR ("mqtt plugin: Invalid port number.");
512 else if (strcasecmp ("ClientId", child->key) == 0)
513 cf_util_get_string (child, &conf->client_id);
514 else if (strcasecmp ("User", child->key) == 0)
515 cf_util_get_string (child, &conf->username);
516 else if (strcasecmp ("Password", child->key) == 0)
517 cf_util_get_string (child, &conf->password);
518 else if (strcasecmp ("QoS", child->key) == 0)
521 status = cf_util_get_int (child, &tmp);
522 if ((status != 0) || (tmp < 0) || (tmp > 2))
523 ERROR ("mqtt plugin: Not a valid QoS setting.");
527 else if (strcasecmp ("Prefix", child->key) == 0)
528 cf_util_get_string (child, &conf->topic_prefix);
529 else if (strcasecmp ("StoreRates", child->key) == 0)
530 cf_util_get_boolean (child, &conf->store_rates);
531 else if (strcasecmp ("Retain", child->key) == 0)
532 cf_util_get_boolean (child, &conf->retain);
534 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
537 memset (&user_data, 0, sizeof (user_data));
538 user_data.data = conf;
540 plugin_register_write ("mqtt", mqtt_write, &user_data);
542 } /* mqtt_config_publisher */
548 * ClientId "collectd"
554 static int mqtt_config_subscriber (oconfig_item_t *ci)
556 mqtt_client_conf_t **tmp;
557 mqtt_client_conf_t *conf;
561 conf = calloc (1, sizeof (*conf));
564 ERROR ("mqtt plugin: malloc failed.");
570 status = cf_util_get_string (ci, &conf->name);
577 conf->host = strdup (MQTT_DEFAULT_HOST);
578 conf->port = MQTT_DEFAULT_PORT;
579 conf->client_id = NULL;
580 conf->topic = strdup (MQTT_DEFAULT_TOPIC);
582 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
584 for (i = 0; i < ci->children_num; i++)
586 oconfig_item_t *child = ci->children + i;
587 if (strcasecmp ("Host", child->key) == 0)
588 cf_util_get_string (child, &conf->host);
589 else if (strcasecmp ("Port", child->key) == 0)
591 int tmp = cf_util_get_port_number (child);
593 ERROR ("mqtt plugin: Invalid port number.");
597 else if (strcasecmp ("ClientId", child->key) == 0)
598 cf_util_get_string (child, &conf->client_id);
599 else if (strcasecmp ("User", child->key) == 0)
600 cf_util_get_string (child, &conf->username);
601 else if (strcasecmp ("Password", child->key) == 0)
602 cf_util_get_string (child, &conf->password);
603 else if (strcasecmp ("QoS", child->key) == 0)
606 status = cf_util_get_int (child, &tmp);
607 if ((status != 0) || (tmp < 0) || (tmp > 2))
608 ERROR ("mqtt plugin: Not a valid QoS setting.");
612 else if (strcasecmp ("Topic", child->key) == 0)
613 cf_util_get_string (child, &conf->topic);
614 else if (strcasecmp ("CleanSession", child->key) == 0)
615 cf_util_get_boolean (child, &conf->clean_session);
617 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
620 tmp = realloc (subscribers, sizeof (*subscribers) * subscribers_num);
623 ERROR ("mqtt plugin: realloc failed.");
628 subscribers[subscribers_num] = conf;
632 } /* mqtt_config_subscriber */
644 static int mqtt_config (oconfig_item_t *ci)
648 for (i = 0; i < ci->children_num; i++)
650 oconfig_item_t *child = ci->children + i;
652 if (strcasecmp ("Publish", child->key) == 0)
653 mqtt_config_publisher (child);
654 else if (strcasecmp ("Subscribe", child->key) == 0)
655 mqtt_config_subscriber (child);
657 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
661 } /* int mqtt_config */
663 static int mqtt_init (void)
667 mosquitto_lib_init ();
669 for (i = 0; i < subscribers_num; i++)
673 if (subscribers[i]->loop)
676 status = plugin_thread_create (&subscribers[i]->thread,
678 /* func = */ subscribers_thread,
679 /* args = */ subscribers[i]);
683 ERROR ("mqtt plugin: pthread_create failed: %s",
684 sstrerror (errno, errbuf, sizeof (errbuf)));
692 void module_register (void)
694 plugin_register_complex_config ("mqtt", mqtt_config);
695 plugin_register_init ("mqtt", mqtt_init);
696 } /* void module_register */
698 /* vim: set sw=4 sts=4 et fdm=marker : */