2 * collectd - src/mqtt.c
3 * Copyright (C) 2014 Marc Falzon <marc at baha dot mu>
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 // Reference: http://mosquitto.org/api/files/mosquitto-h.html
30 #include "utils_cache.h"
31 #include "utils_complain.h"
35 #include <mosquitto.h>
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_TOPIC_PREFIX "collectd"
42 #define MQTT_DEFAULT_TOPIC "collectd/#"
47 struct mqtt_client_conf
52 struct mosquitto *mosq;
73 c_complain_t complaint_cantpublish;
76 typedef struct mqtt_client_conf mqtt_client_conf_t;
78 static mqtt_client_conf_t **subscribers = NULL;
79 static size_t subscribers_num = 0;
84 static char const *mosquitto_strerror (int code)
88 case MOSQ_ERR_SUCCESS: return "MOSQ_ERR_SUCCESS";
89 case MOSQ_ERR_NOMEM: return "MOSQ_ERR_NOMEM";
90 case MOSQ_ERR_PROTOCOL: return "MOSQ_ERR_PROTOCOL";
91 case MOSQ_ERR_INVAL: return "MOSQ_ERR_INVAL";
92 case MOSQ_ERR_NO_CONN: return "MOSQ_ERR_NO_CONN";
93 case MOSQ_ERR_CONN_REFUSED: return "MOSQ_ERR_CONN_REFUSED";
94 case MOSQ_ERR_NOT_FOUND: return "MOSQ_ERR_NOT_FOUND";
95 case MOSQ_ERR_CONN_LOST: return "MOSQ_ERR_CONN_LOST";
96 case MOSQ_ERR_SSL: return "MOSQ_ERR_SSL";
97 case MOSQ_ERR_PAYLOAD_SIZE: return "MOSQ_ERR_PAYLOAD_SIZE";
98 case MOSQ_ERR_NOT_SUPPORTED: return "MOSQ_ERR_NOT_SUPPORTED";
99 case MOSQ_ERR_AUTH: return "MOSQ_ERR_AUTH";
100 case MOSQ_ERR_ACL_DENIED: return "MOSQ_ERR_ACL_DENIED";
101 case MOSQ_ERR_UNKNOWN: return "MOSQ_ERR_UNKNOWN";
102 case MOSQ_ERR_ERRNO: return "MOSQ_ERR_ERRNO";
105 return "UNKNOWN ERROR CODE";
108 static void mqtt_free (mqtt_client_conf_t *conf)
114 (void) mosquitto_disconnect (conf->mosq);
116 (void) mosquitto_destroy (conf->mosq);
119 sfree (conf->username);
120 sfree (conf->password);
121 sfree (conf->client_id);
122 sfree (conf->topic_prefix);
126 static char *strip_prefix (char *topic)
132 for (i = 0; topic[i] != 0; i++)
141 char *tmp = strchr (topic, '/');
151 static void on_message (__attribute__((unused)) void *arg,
152 const struct mosquitto_message *msg)
154 value_list_t vl = VALUE_LIST_INIT;
155 data_set_t const *ds;
161 if ((msg->payloadlen <= 0) || (msg->payload[msg->payloadlen - 1] != 0))
164 topic = strdup (msg->topic);
165 name = strip_prefix (topic);
167 status = parse_identifier_vl (name, &vl);
170 ERROR ("mqtt plugin: Unable to parse topic \"%s\".", topic);
176 ds = plugin_get_ds (vl.type);
179 ERROR ("mqtt plugin: Unknown type: \"%s\".", vl.type);
183 vl.values = calloc (ds->ds_num, sizeof (*vl.values));
184 if (vl.values == NULL)
186 ERROR ("mqtt plugin: calloc failed.");
189 vl.values_len = ds->ds_num;
191 payload = strdup ((void *) msg->payload);
192 DEBUG ("mqtt plugin: payload = \"%s\"", payload);
193 status = parse_values (payload, &vl, ds);
196 ERROR ("mqtt plugin: Unable to parse payload \"%s\".", payload);
203 plugin_dispatch_values (&vl);
205 } /* void on_message */
207 /* must hold conf->lock when calling. */
208 static int mqtt_reconnect (mqtt_client_conf_t *conf)
215 status = mosquitto_reconnect (conf->mosq);
216 if (status != MOSQ_ERR_SUCCESS)
219 ERROR ("mqtt_connect_broker: mosquitto_connect failed: %s",
220 (status == MOSQ_ERR_ERRNO)
221 ? sstrerror(errno, errbuf, sizeof (errbuf))
222 : mosquitto_strerror (status));
229 &conf->complaint_cantpublish,
230 "mqtt plugin: successfully reconnected to broker \"%s:%d\"",
231 conf->host, conf->port);
234 } /* mqtt_reconnect */
236 /* must hold conf->lock when calling. */
237 static int mqtt_connect (mqtt_client_conf_t *conf)
239 char const *client_id;
242 if (conf->mosq != NULL)
243 return mqtt_reconnect (conf);
246 client_id = conf->client_id;
248 client_id = hostname_g;
250 conf->mosq = mosquitto_new (client_id, /* user data = */ conf);
251 if (conf->mosq == NULL)
253 ERROR ("mqtt plugin: mosquitto_new failed");
257 if (conf->username && conf->password)
259 status = mosquitto_username_pw_set (conf->mosq, conf->username, conf->password);
260 if (status != MOSQ_ERR_SUCCESS)
263 ERROR ("mqtt plugin: mosquitto_username_pw_set failed: %s",
264 (status == MOSQ_ERR_ERRNO)
265 ? sstrerror (errno, errbuf, sizeof (errbuf))
266 : mosquitto_strerror (status));
268 mosquitto_destroy (conf->mosq);
274 status = mosquitto_connect (conf->mosq, conf->host, conf->port,
275 /* keepalive = */ 10, /* clean session = */ conf->clean_session);
276 if (status != MOSQ_ERR_SUCCESS)
279 ERROR ("mqtt plugin: mosquitto_connect failed: %s",
280 (status == MOSQ_ERR_ERRNO)
281 ? sstrerror (errno, errbuf, sizeof (errbuf))
282 : mosquitto_strerror (status));
284 mosquitto_destroy (conf->mosq);
291 mosquitto_message_callback_set (conf->mosq, on_message);
293 status = mosquitto_subscribe (conf->mosq, /* mid = */ NULL,
294 conf->topic, conf->qos);
295 if (status != MOSQ_ERR_SUCCESS)
297 ERROR ("mqtt plugin: Subscribing to \"%s\" failed: %s",
298 conf->topic, mosquitto_strerror (status));
300 mosquitto_disconnect (conf->mosq);
301 mosquitto_destroy (conf->mosq);
311 static void *subscribers_thread (void *arg)
313 mqtt_client_conf_t *conf = arg;
320 status = mqtt_connect (conf);
327 /* The documentation says "0" would map to the default (1000ms), but
328 * that does not work on some versions. */
329 status = mosquitto_loop (conf->mosq, /* timeout = */ 1000 /* ms */);
330 if (status == MOSQ_ERR_CONN_LOST)
335 else if (status != MOSQ_ERR_SUCCESS)
337 ERROR ("mqtt plugin: mosquitto_loop failed: %s",
338 mosquitto_strerror (status));
339 mosquitto_destroy (conf->mosq);
345 DEBUG ("mqtt plugin: mosquitto_loop succeeded.");
346 } /* while (conf->loop) */
349 } /* void *subscribers_thread */
351 static int publish (mqtt_client_conf_t *conf, char const *topic,
352 void const *payload, size_t payload_len)
356 pthread_mutex_lock (&conf->lock);
358 status = mqtt_connect (conf);
360 pthread_mutex_unlock (&conf->lock);
361 ERROR ("mqtt plugin: unable to reconnect to broker");
365 status = mosquitto_publish(conf->mosq,
366 /* message id */ NULL,
368 (uint32_t) payload_len, payload,
370 /* retain */ conf->retain);
371 if (status != MOSQ_ERR_SUCCESS)
375 &conf->complaint_cantpublish,
376 "plugin mqtt: mosquitto_publish failed: %s",
377 status == MOSQ_ERR_ERRNO ?
378 sstrerror(errno, errbuf, sizeof (errbuf)) :
379 mosquitto_strerror(status));
380 /* Mark our connection "down" regardless of the error as a safety
381 * measure; we will try to reconnect the next time we have to publish a
385 pthread_mutex_unlock (&conf->lock);
389 pthread_mutex_unlock (&conf->lock);
393 static int format_topic (char *buf, size_t buf_len,
394 data_set_t const *ds, value_list_t const *vl,
395 mqtt_client_conf_t *conf)
397 char name[MQTT_MAX_TOPIC_SIZE];
400 if ((conf->topic_prefix == NULL) || (conf->topic_prefix[0] == 0))
401 return (FORMAT_VL (buf, buf_len, vl));
403 status = FORMAT_VL (name, sizeof (name), vl);
407 status = ssnprintf (buf, buf_len, "%s/%s", conf->topic_prefix, name);
408 if ((status < 0) || (((size_t) status) >= buf_len))
412 } /* int format_topic */
414 static int mqtt_write (const data_set_t *ds, const value_list_t *vl,
415 user_data_t *user_data)
417 mqtt_client_conf_t *conf;
418 char topic[MQTT_MAX_TOPIC_SIZE];
419 char payload[MQTT_MAX_MESSAGE_SIZE];
422 if ((user_data == NULL) || (user_data->data == NULL))
424 conf = user_data->data;
426 status = format_topic (topic, sizeof (topic), ds, vl, conf);
429 ERROR ("mqtt plugin: format_topic failed with status %d.", status);
433 status = format_values (payload, sizeof (payload),
434 ds, vl, conf->store_rates);
437 ERROR ("mqtt plugin: format_values failed with status %d.", status);
441 status = publish (conf, topic, payload, strlen (payload) + 1);
444 ERROR ("mqtt plugin: publish failed: %s", mosquitto_strerror (status));
455 * ClientId "collectd"
464 static int mqtt_config_publisher (oconfig_item_t *ci)
466 mqtt_client_conf_t *conf;
467 user_data_t user_data;
471 conf = calloc (1, sizeof (*conf));
474 ERROR ("mqtt plugin: malloc failed.");
480 status = cf_util_get_string (ci, &conf->name);
487 conf->host = strdup (MQTT_DEFAULT_HOST);
488 conf->port = MQTT_DEFAULT_PORT;
489 conf->client_id = NULL;
490 conf->topic_prefix = strdup (MQTT_DEFAULT_TOPIC_PREFIX);
492 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
494 for (i = 0; i < ci->children_num; i++)
496 oconfig_item_t *child = ci->children + i;
497 if (strcasecmp ("Host", child->key) == 0)
498 cf_util_get_string (child, &conf->host);
499 else if (strcasecmp ("Port", child->key) == 0)
501 int tmp = cf_util_get_port_number (child);
503 ERROR ("mqtt plugin: Invalid port number.");
507 else if (strcasecmp ("ClientId", child->key) == 0)
508 cf_util_get_string (child, &conf->client_id);
509 else if (strcasecmp ("User", child->key) == 0)
510 cf_util_get_string (child, &conf->username);
511 else if (strcasecmp ("Password", child->key) == 0)
512 cf_util_get_string (child, &conf->password);
513 else if (strcasecmp ("QoS", child->key) == 0)
516 status = cf_util_get_int (child, &tmp);
517 if ((status != 0) || (tmp < 0) || (tmp > 2))
518 ERROR ("mqtt plugin: Not a valid QoS setting.");
522 else if (strcasecmp ("Prefix", child->key) == 0)
523 cf_util_get_string (child, &conf->topic_prefix);
524 else if (strcasecmp ("StoreRates", child->key) == 0)
525 cf_util_get_boolean (child, &conf->store_rates);
526 else if (strcasecmp ("Retain", child->key) == 0)
527 cf_util_get_boolean (child, &conf->retain);
529 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
532 memset (&user_data, 0, sizeof (user_data));
533 user_data.data = conf;
535 plugin_register_write ("mqtt", mqtt_write, &user_data);
537 } /* mqtt_config_publisher */
543 * ClientId "collectd"
549 static int mqtt_config_subscriber (oconfig_item_t *ci)
551 mqtt_client_conf_t **tmp;
552 mqtt_client_conf_t *conf;
556 conf = calloc (1, sizeof (*conf));
559 ERROR ("mqtt plugin: malloc failed.");
565 status = cf_util_get_string (ci, &conf->name);
572 conf->host = strdup (MQTT_DEFAULT_HOST);
573 conf->port = MQTT_DEFAULT_PORT;
574 conf->client_id = NULL;
575 conf->topic = strdup (MQTT_DEFAULT_TOPIC);
577 C_COMPLAIN_INIT (&conf->complaint_cantpublish);
579 for (i = 0; i < ci->children_num; i++)
581 oconfig_item_t *child = ci->children + i;
582 if (strcasecmp ("Host", child->key) == 0)
583 cf_util_get_string (child, &conf->host);
584 else if (strcasecmp ("Port", child->key) == 0)
586 int tmp = cf_util_get_port_number (child);
588 ERROR ("mqtt plugin: Invalid port number.");
592 else if (strcasecmp ("ClientId", child->key) == 0)
593 cf_util_get_string (child, &conf->client_id);
594 else if (strcasecmp ("User", child->key) == 0)
595 cf_util_get_string (child, &conf->username);
596 else if (strcasecmp ("Password", child->key) == 0)
597 cf_util_get_string (child, &conf->password);
598 else if (strcasecmp ("QoS", child->key) == 0)
601 status = cf_util_get_int (child, &tmp);
602 if ((status != 0) || (tmp < 0) || (tmp > 2))
603 ERROR ("mqtt plugin: Not a valid QoS setting.");
607 else if (strcasecmp ("Topic", child->key) == 0)
608 cf_util_get_string (child, &conf->topic);
609 else if (strcasecmp ("CleanSession", child->key) == 0)
610 cf_util_get_boolean (child, &conf->clean_session);
612 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
615 tmp = realloc (subscribers, sizeof (*subscribers) * subscribers_num);
618 ERROR ("mqtt plugin: realloc failed.");
623 subscribers[subscribers_num] = conf;
627 } /* mqtt_config_subscriber */
639 static int mqtt_config (oconfig_item_t *ci)
643 for (i = 0; i < ci->children_num; i++)
645 oconfig_item_t *child = ci->children + i;
647 if (strcasecmp ("Publish", child->key) == 0)
648 mqtt_config_publisher (child);
649 else if (strcasecmp ("Subscribe", child->key) == 0)
650 mqtt_config_subscriber (child);
652 ERROR ("mqtt plugin: Unknown config option: %s", child->key);
656 } /* int mqtt_config */
658 static int mqtt_init (void)
662 mosquitto_lib_init ();
664 for (i = 0; i < subscribers_num; i++)
668 if (subscribers[i]->loop)
671 status = plugin_thread_create (&subscribers[i]->thread,
673 /* func = */ subscribers_thread,
674 /* args = */ subscribers[i]);
678 ERROR ("mqtt plugin: pthread_create failed: %s",
679 sstrerror (errno, errbuf, sizeof (errbuf)));
687 void module_register (void)
689 plugin_register_complex_config ("mqtt", mqtt_config);
690 plugin_register_init ("mqtt", mqtt_init);
691 } /* void module_register */
693 /* vim: set sw=4 sts=4 et fdm=marker : */