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 static char const *mosquitto_strerror (int code)
97 case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
98 case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
99 case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
100 case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
101 case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
102 case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
103 case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
104 case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
105 case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
106 case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
107 case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
108 case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
109 case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
110 case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
111 case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
114 return "UNKNOWN ERROR CODE";
117 static void mqtt_free (mqtt_client_conf_t *conf)
123 (void) mosquitto_disconnect (conf->mosq);
125 (void) mosquitto_destroy (conf->mosq);
128 sfree (conf->username);
129 sfree (conf->password);
130 sfree (conf->client_id);
131 sfree (conf->topic_prefix);
135 static char *strip_prefix (char *topic)
141 for (i = 0; topic[i] != 0; i++)
150 char *tmp = strchr (topic, '/');
160 static void on_message (__attribute__((unused)) void *arg,
161 const struct mosquitto_message *msg)
163 value_list_t vl = VALUE_LIST_INIT;
164 data_set_t const *ds;
170 if ((msg->payloadlen <= 0) || (msg->payload[msg->payloadlen - 1] != 0))
173 topic = strdup (msg->topic);
174 name = strip_prefix (topic);
176 status = parse_identifier_vl (name, &vl);
179 ERROR ("mqtt plugin: Unable to parse topic \"%s\".", topic);
185 ds = plugin_get_ds (vl.type);
188 ERROR ("mqtt plugin: Unknown type: \"%s\".", vl.type);
192 vl.values = calloc (ds->ds_num, sizeof (*vl.values));
193 if (vl.values == NULL)
195 ERROR ("mqtt plugin: calloc failed.");
198 vl.values_len = ds->ds_num;
200 payload = strdup ((void *) msg->payload);
201 DEBUG ("mqtt plugin: payload = \"%s\"", payload);
202 status = parse_values (payload, &vl, ds);
205 ERROR ("mqtt plugin: Unable to parse payload \"%s\".", payload);
212 plugin_dispatch_values (&vl);
214 } /* void on_message */
216 /* must hold conf->lock when calling. */
217 static int mqtt_reconnect (mqtt_client_conf_t *conf)
224 status = mosquitto_reconnect (conf->mosq);
225 if (status != MOSQ_ERR_SUCCESS)
228 ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
229 (status == MOSQ_ERR_ERRNO)
230 ? sstrerror(errno, errbuf, sizeof (errbuf))
231 : mosquitto_strerror (status));
238 &conf->complaint_cantpublish,
239 "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
240 conf->host, conf->port);
243 } /* mqtt_reconnect */
245 /* must hold conf->lock when calling. */
246 static int mqtt_connect (mqtt_client_conf_t *conf)
248 char const *client_id;
251 if (conf->mosq != NULL)
252 return mqtt_reconnect (conf);
255 client_id = conf->client_id;
257 client_id = hostname_g;
259 conf->mosq = mosquitto_new (client_id, /* user data = */ conf);
260 if (conf->mosq == NULL)
262 ERROR ("mqtt plugin: mosquitto_new failed");
266 if (conf->username && conf->password)
268 status = mosquitto_username_pw_set (conf->mosq, conf->username, conf->password);
269 if (status != MOSQ_ERR_SUCCESS)
272 ERROR ("mqtt plugin: mosquitto_username_pw_set failed: %s",
273 (status == MOSQ_ERR_ERRNO)
274 ? sstrerror (errno, errbuf, sizeof (errbuf))
275 : mosquitto_strerror (status));
277 mosquitto_destroy (conf->mosq);
283 status = mosquitto_connect (conf->mosq, conf->host, conf->port,
284 /* keepalive = */ MQTT_KEEPALIVE, /* clean session = */ conf->clean_session);
285 if (status != MOSQ_ERR_SUCCESS)
288 ERROR ("mqtt plugin: mosquitto_connect failed: %s",
289 (status == MOSQ_ERR_ERRNO)
290 ? sstrerror (errno, errbuf, sizeof (errbuf))
291 : mosquitto_strerror (status));
293 mosquitto_destroy (conf->mosq);
300 mosquitto_message_callback_set (conf->mosq, on_message);
302 status = mosquitto_subscribe (conf->mosq, /* mid = */ NULL,
303 conf->topic, conf->qos);
304 if (status != MOSQ_ERR_SUCCESS)
306 ERROR ("mqtt plugin: Subscribing to \"%s\" failed: %s",
307 conf->topic, mosquitto_strerror (status));
309 mosquitto_disconnect (conf->mosq);
310 mosquitto_destroy (conf->mosq);
320 static void *subscribers_thread (void *arg)
322 mqtt_client_conf_t *conf = arg;
329 status = mqtt_connect (conf);
336 /* The documentation says "0" would map to the default (1000ms), but
337 * that does not work on some versions. */
338 status = mosquitto_loop (conf->mosq, /* timeout = */ 1000 /* ms */);
339 if (status == MOSQ_ERR_CONN_LOST)
344 else if (status != MOSQ_ERR_SUCCESS)
346 ERROR ("mqtt plugin: mosquitto_loop failed: %s",
347 mosquitto_strerror (status));
348 mosquitto_destroy (conf->mosq);
354 DEBUG ("mqtt plugin: mosquitto_loop succeeded.");
355 } /* while (conf->loop) */
358 } /* void *subscribers_thread */
360 static int publish (mqtt_client_conf_t *conf, char const *topic,
361 void const *payload, size_t payload_len)
365 pthread_mutex_lock (&conf->lock);
367 status = mqtt_connect (conf);
369 pthread_mutex_unlock (&conf->lock);
370 ERROR ("mqtt plugin: unable to reconnect to broker");
374 status = mosquitto_publish(conf->mosq,
375 /* message id */ NULL,
377 (uint32_t) payload_len, payload,
379 /* retain */ conf->retain);
380 if (status != MOSQ_ERR_SUCCESS)
384 &conf->complaint_cantpublish,
385 "plugin mqtt: mosquitto_publish failed: %s",
386 status == MOSQ_ERR_ERRNO ?
387 sstrerror(errno, errbuf, sizeof (errbuf)) :
388 mosquitto_strerror(status));
389 /* Mark our connection "down" regardless of the error as a safety
390 * measure; we will try to reconnect the next time we have to publish a
394 pthread_mutex_unlock (&conf->lock);
398 pthread_mutex_unlock (&conf->lock);
402 static int format_topic (char *buf, size_t buf_len,
403 data_set_t const *ds, value_list_t const *vl,
404 mqtt_client_conf_t *conf)
406 char name[MQTT_MAX_TOPIC_SIZE];
409 if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
410 return (FORMAT_VL (buf, buf_len, vl));
412 status = FORMAT_VL (name, sizeof (name), vl);
416 status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
417 if ((status < 0) || (((size_t) status) >= buf_len))
421 } /* int format_topic */
423 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
424 user_data_t *user_data)
426 mqtt_client_conf_t *conf;
427 char topic[MQTT_MAX_TOPIC_SIZE];
428 char payload[MQTT_MAX_MESSAGE_SIZE];
431 if ((user_data == NULL) || (user_data->data == NULL))
433 conf = user_data->data;
435 status = format_topic (topic, sizeof (topic), ds, vl, conf);
438 ERROR ("mqtt plugin: format_topic failed with status %d.", status);
442 status = format_values (payload, sizeof (payload),
443 ds, vl, conf->store_rates);
446 ERROR ("mqtt plugin: format_values failed with status %d.", status);
450 status = publish (conf, topic, payload, strlen (payload) + 1);
453 ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
464 * ClientId "collectd"
473 static int mqtt_config_publisher (oconfig_item_t *ci)
475 mqtt_client_conf_t *conf;
477 user_data_t user_data;
481 conf = calloc (1, sizeof (*conf));
484 ERROR ("mqtt plugin: malloc failed.");
490 status = cf_util_get_string (ci, &conf->name);
497 conf->host = strdup (MQTT_DEFAULT_HOST);
498 conf->port = MQTT_DEFAULT_PORT;
499 conf->client_id = NULL;
500 conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
502 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
504 for (i = 0; i < ci->children_num; i++)
506 oconfig_item_t *child = ci->children + i;
507 if (strcasecmp ("Host", child->key) == 0)
508 cf_util_get_string (child, &conf->host);
509 else if (strcasecmp ("Port", child->key) == 0)
511 int tmp = cf_util_get_port_number (child);
513 ERROR ("mqtt plugin: Invalid port number.");
517 else if (strcasecmp ("ClientId", child->key) == 0)
518 cf_util_get_string (child, &conf->client_id);
519 else if (strcasecmp ("User", child->key) == 0)
520 cf_util_get_string (child, &conf->username);
521 else if (strcasecmp ("Password", child->key) == 0)
522 cf_util_get_string (child, &conf->password);
523 else if (strcasecmp ("QoS", child->key) == 0)
526 status = cf_util_get_int (child, &tmp);
527 if ((status != 0) || (tmp < 0) || (tmp > 2))
528 ERROR ("mqtt plugin: Not a valid QoS setting.");
532 else if (strcasecmp ("Prefix", child->key) == 0)
533 cf_util_get_string (child, &conf->topic_prefix);
534 else if (strcasecmp ("StoreRates", child->key) == 0)
535 cf_util_get_boolean (child, &conf->store_rates);
536 else if (strcasecmp ("Retain", child->key) == 0)
537 cf_util_get_boolean (child, &conf->retain);
539 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
542 ssnprintf (cb_name, sizeof (cb_name), "mqtt/%s", conf->name);
543 memset (&user_data, 0, sizeof (user_data));
544 user_data.data = conf;
546 plugin_register_write (cb_name, mqtt_write, &user_data);
548 } /* mqtt_config_publisher */
554 * ClientId "collectd"
560 static int mqtt_config_subscriber (oconfig_item_t *ci)
562 mqtt_client_conf_t **tmp;
563 mqtt_client_conf_t *conf;
567 conf = calloc (1, sizeof (*conf));
570 ERROR ("mqtt plugin: malloc failed.");
576 status = cf_util_get_string (ci, &conf->name);
583 conf->host = strdup (MQTT_DEFAULT_HOST);
584 conf->port = MQTT_DEFAULT_PORT;
585 conf->client_id = NULL;
586 conf->topic = strdup (MQTT_DEFAULT_TOPIC);
588 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
590 for (i = 0; i < ci->children_num; i++)
592 oconfig_item_t *child = ci->children + i;
593 if (strcasecmp ("Host", child->key) == 0)
594 cf_util_get_string (child, &conf->host);
595 else if (strcasecmp ("Port", child->key) == 0)
597 int tmp = cf_util_get_port_number (child);
599 ERROR ("mqtt plugin: Invalid port number.");
603 else if (strcasecmp ("ClientId", child->key) == 0)
604 cf_util_get_string (child, &conf->client_id);
605 else if (strcasecmp ("User", child->key) == 0)
606 cf_util_get_string (child, &conf->username);
607 else if (strcasecmp ("Password", child->key) == 0)
608 cf_util_get_string (child, &conf->password);
609 else if (strcasecmp ("QoS", child->key) == 0)
612 status = cf_util_get_int (child, &tmp);
613 if ((status != 0) || (tmp < 0) || (tmp > 2))
614 ERROR ("mqtt plugin: Not a valid QoS setting.");
618 else if (strcasecmp ("Topic", child->key) == 0)
619 cf_util_get_string (child, &conf->topic);
620 else if (strcasecmp ("CleanSession", child->key) == 0)
621 cf_util_get_boolean (child, &conf->clean_session);
623 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
626 tmp = realloc (subscribers, sizeof (*subscribers) * subscribers_num);
629 ERROR ("mqtt plugin: realloc failed.");
634 subscribers[subscribers_num] = conf;
638 } /* mqtt_config_subscriber */
650 static int mqtt_config (oconfig_item_t *ci)
654 for (i = 0; i < ci->children_num; i++)
656 oconfig_item_t *child = ci->children + i;
658 if (strcasecmp ("Publish", child->key) == 0)
659 mqtt_config_publisher (child);
660 else if (strcasecmp ("Subscribe", child->key) == 0)
661 mqtt_config_subscriber (child);
663 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
667 } /* int mqtt_config */
669 static int mqtt_init (void)
673 mosquitto_lib_init ();
675 for (i = 0; i < subscribers_num; i++)
679 if (subscribers[i]->loop)
682 status = plugin_thread_create (&subscribers[i]->thread,
684 /* func = */ subscribers_thread,
685 /* args = */ subscribers[i]);
689 ERROR ("mqtt plugin: pthread_create failed: %s",
690 sstrerror (errno, errbuf, sizeof (errbuf)));
698 void module_register (void)
700 plugin_register_complex_config ("mqtt", mqtt_config);
701 plugin_register_init ("mqtt", mqtt_init);
702 } /* void module_register */
704 /* vim: set sw=4 sts=4 et fdm=marker : */