2016-02-09 22:03:46 +00:00
|
|
|
package mqtt_consumer
|
|
|
|
|
|
|
|
import (
|
2018-11-05 21:34:28 +00:00
|
|
|
"context"
|
2018-10-15 20:03:52 +00:00
|
|
|
"errors"
|
2016-02-09 22:03:46 +00:00
|
|
|
"fmt"
|
2016-04-14 02:58:45 +00:00
|
|
|
"strings"
|
2016-02-09 22:03:46 +00:00
|
|
|
"time"
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
"github.com/eclipse/paho.mqtt.golang"
|
2016-02-09 22:03:46 +00:00
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
"github.com/influxdata/telegraf/internal"
|
2018-05-04 23:33:23 +00:00
|
|
|
"github.com/influxdata/telegraf/internal/tls"
|
2016-02-09 22:03:46 +00:00
|
|
|
"github.com/influxdata/telegraf/plugins/inputs"
|
|
|
|
"github.com/influxdata/telegraf/plugins/parsers"
|
|
|
|
)
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
var (
|
|
|
|
// 30 Seconds is the default used by paho.mqtt.golang
|
|
|
|
defaultConnectionTimeout = internal.Duration{Duration: 30 * time.Second}
|
|
|
|
|
|
|
|
defaultMaxUndeliveredMessages = 1000
|
|
|
|
)
|
2017-09-29 22:58:38 +00:00
|
|
|
|
2018-10-15 20:03:52 +00:00
|
|
|
type ConnectionState int
|
2018-11-05 21:34:28 +00:00
|
|
|
type empty struct{}
|
|
|
|
type semaphore chan empty
|
2018-10-15 20:03:52 +00:00
|
|
|
|
|
|
|
const (
|
|
|
|
Disconnected ConnectionState = iota
|
|
|
|
Connecting
|
|
|
|
Connected
|
|
|
|
)
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
type Client interface {
|
|
|
|
Connect() mqtt.Token
|
|
|
|
SubscribeMultiple(filters map[string]byte, callback mqtt.MessageHandler) mqtt.Token
|
|
|
|
AddRoute(topic string, callback mqtt.MessageHandler)
|
|
|
|
Disconnect(quiesce uint)
|
|
|
|
}
|
|
|
|
|
|
|
|
type ClientFactory func(o *mqtt.ClientOptions) Client
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
type MQTTConsumer struct {
|
2019-08-20 02:05:22 +00:00
|
|
|
Servers []string `toml:"servers"`
|
|
|
|
Topics []string `toml:"topics"`
|
|
|
|
TopicTag *string `toml:"topic_tag"`
|
|
|
|
Username string `toml:"username"`
|
|
|
|
Password string `toml:"password"`
|
2018-11-05 21:34:28 +00:00
|
|
|
QoS int `toml:"qos"`
|
|
|
|
ConnectionTimeout internal.Duration `toml:"connection_timeout"`
|
|
|
|
MaxUndeliveredMessages int `toml:"max_undelivered_messages"`
|
2016-02-09 22:03:46 +00:00
|
|
|
|
|
|
|
parser parsers.Parser
|
|
|
|
|
2018-10-19 22:46:20 +00:00
|
|
|
// Legacy metric buffer support; deprecated in v0.10.3
|
2016-02-16 00:21:38 +00:00
|
|
|
MetricBuffer int
|
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
PersistentSession bool
|
|
|
|
ClientID string `toml:"client_id"`
|
2018-05-04 23:33:23 +00:00
|
|
|
tls.ClientConfig
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2019-09-23 22:39:50 +00:00
|
|
|
Log telegraf.Logger
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
clientFactory ClientFactory
|
|
|
|
client Client
|
|
|
|
opts *mqtt.ClientOptions
|
|
|
|
acc telegraf.TrackingAccumulator
|
|
|
|
state ConnectionState
|
|
|
|
sem semaphore
|
|
|
|
messages map[telegraf.TrackingID]bool
|
2019-08-20 02:05:22 +00:00
|
|
|
topicTag string
|
2018-11-05 21:34:28 +00:00
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var sampleConfig = `
|
2020-06-04 21:43:05 +00:00
|
|
|
## Broker URLs for the MQTT server or cluster. To connect to multiple
|
|
|
|
## clusters or standalone servers, use a seperate plugin instance.
|
|
|
|
## example: servers = ["tcp://localhost:1883"]
|
|
|
|
## servers = ["ssl://localhost:1883"]
|
|
|
|
## servers = ["ws://localhost:1883"]
|
2019-08-15 00:05:34 +00:00
|
|
|
servers = ["tcp://127.0.0.1:1883"]
|
|
|
|
|
|
|
|
## Topics that will be subscribed to.
|
|
|
|
topics = [
|
|
|
|
"telegraf/host01/cpu",
|
|
|
|
"telegraf/+/mem",
|
|
|
|
"sensors/#",
|
|
|
|
]
|
2017-10-30 22:33:20 +00:00
|
|
|
|
2019-08-20 02:05:22 +00:00
|
|
|
## The message topic will be stored in a tag specified by this value. If set
|
|
|
|
## to the empty string no topic tag will be created.
|
|
|
|
# topic_tag = "topic"
|
|
|
|
|
2018-10-04 00:21:30 +00:00
|
|
|
## QoS policy for messages
|
|
|
|
## 0 = at most once
|
|
|
|
## 1 = at least once
|
|
|
|
## 2 = exactly once
|
|
|
|
##
|
|
|
|
## When using a QoS of 1 or 2, you should enable persistent_session to allow
|
|
|
|
## resuming unacknowledged messages.
|
2019-08-15 00:05:34 +00:00
|
|
|
# qos = 0
|
2018-10-04 00:21:30 +00:00
|
|
|
|
2017-09-11 19:24:51 +00:00
|
|
|
## Connection timeout for initial connection in seconds
|
2019-08-15 00:05:34 +00:00
|
|
|
# connection_timeout = "30s"
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
## Maximum messages to read from the broker that have not been written by an
|
|
|
|
## output. For best throughput set based on the number of metrics within
|
|
|
|
## each message and the size of the output's metric_batch_size.
|
|
|
|
##
|
|
|
|
## For example, if each message from the queue contains 10 metrics and the
|
|
|
|
## output metric_batch_size is 1000, setting this to 100 will ensure that a
|
|
|
|
## full batch is collected and the write is triggered immediately without
|
|
|
|
## waiting until the next flush_interval.
|
|
|
|
# max_undelivered_messages = 1000
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
## Persistent session disables clearing of the client session on connection.
|
2019-11-12 22:11:42 +00:00
|
|
|
## In order for this option to work you must also set client_id to identify
|
2019-08-15 00:05:34 +00:00
|
|
|
## the client. To receive messages that arrived while the client is offline,
|
|
|
|
## also set the qos option to 1 or 2 and don't forget to also set the QoS when
|
|
|
|
## publishing.
|
|
|
|
# persistent_session = false
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
## If unset, a random client ID will be generated.
|
|
|
|
# client_id = ""
|
2016-03-07 12:56:10 +00:00
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
## Username and password to connect MQTT server.
|
2016-02-09 22:03:46 +00:00
|
|
|
# username = "telegraf"
|
|
|
|
# password = "metricsmetricsmetricsmetrics"
|
|
|
|
|
2018-05-04 23:33:23 +00:00
|
|
|
## Optional TLS Config
|
|
|
|
# tls_ca = "/etc/telegraf/ca.pem"
|
|
|
|
# tls_cert = "/etc/telegraf/cert.pem"
|
|
|
|
# tls_key = "/etc/telegraf/key.pem"
|
|
|
|
## Use TLS but skip chain & host verification
|
2016-02-09 22:03:46 +00:00
|
|
|
# insecure_skip_verify = false
|
|
|
|
|
2016-03-31 23:50:24 +00:00
|
|
|
## Data format to consume.
|
2017-04-27 21:59:18 +00:00
|
|
|
## Each data format has its own unique set of configuration options, read
|
2016-02-18 21:26:51 +00:00
|
|
|
## more about them here:
|
|
|
|
## https://github.com/influxdata/telegraf/blob/master/docs/DATA_FORMATS_INPUT.md
|
2016-02-09 22:03:46 +00:00
|
|
|
data_format = "influx"
|
|
|
|
`
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) SampleConfig() string {
|
|
|
|
return sampleConfig
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Description() string {
|
|
|
|
return "Read metrics from MQTT topic(s)"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) SetParser(parser parsers.Parser) {
|
|
|
|
m.parser = parser
|
|
|
|
}
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
func (m *MQTTConsumer) Init() error {
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Disconnected
|
2016-02-16 00:21:38 +00:00
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
if m.PersistentSession && m.ClientID == "" {
|
2018-10-15 20:03:52 +00:00
|
|
|
return errors.New("persistent_session requires client_id")
|
2016-03-07 12:56:10 +00:00
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
if m.QoS > 2 || m.QoS < 0 {
|
2018-10-15 20:03:52 +00:00
|
|
|
return fmt.Errorf("qos value must be 0, 1, or 2: %d", m.QoS)
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
2017-10-02 19:28:31 +00:00
|
|
|
if m.ConnectionTimeout.Duration < 1*time.Second {
|
2018-10-15 20:03:52 +00:00
|
|
|
return fmt.Errorf("connection_timeout must be greater than 1s: %s", m.ConnectionTimeout.Duration)
|
2017-09-11 19:24:51 +00:00
|
|
|
}
|
|
|
|
|
2019-08-20 02:05:22 +00:00
|
|
|
m.topicTag = "topic"
|
|
|
|
if m.TopicTag != nil {
|
|
|
|
m.topicTag = *m.TopicTag
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
opts, err := m.createOpts()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
m.opts = opts
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Start(acc telegraf.Accumulator) error {
|
|
|
|
m.state = Disconnected
|
|
|
|
|
|
|
|
m.acc = acc.WithTracking(m.MaxUndeliveredMessages)
|
2019-12-27 23:48:45 +00:00
|
|
|
m.sem = make(semaphore, m.MaxUndeliveredMessages)
|
2019-08-15 00:05:34 +00:00
|
|
|
m.ctx, m.cancel = context.WithCancel(context.Background())
|
|
|
|
|
|
|
|
m.client = m.clientFactory(m.opts)
|
|
|
|
|
|
|
|
// AddRoute sets up the function for handling messages. These need to be
|
|
|
|
// added in case we find a persistent session containing subscriptions so we
|
2020-05-14 07:41:58 +00:00
|
|
|
// know where to dispatch persisted and new messages to. In the alternate
|
2019-08-15 00:05:34 +00:00
|
|
|
// case that we need to create the subscriptions these will be replaced.
|
|
|
|
for _, topic := range m.Topics {
|
|
|
|
m.client.AddRoute(topic, m.recvMessage)
|
|
|
|
}
|
|
|
|
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Connecting
|
2017-09-11 19:24:51 +00:00
|
|
|
m.connect()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) connect() error {
|
2019-08-15 00:05:34 +00:00
|
|
|
token := m.client.Connect()
|
|
|
|
if token.Wait() && token.Error() != nil {
|
2017-09-11 19:24:51 +00:00
|
|
|
err := token.Error()
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Disconnected
|
2017-09-11 19:24:51 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Infof("Connected %v", m.Servers)
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Connected
|
2018-11-05 21:34:28 +00:00
|
|
|
m.messages = make(map[telegraf.TrackingID]bool)
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2020-05-14 07:41:58 +00:00
|
|
|
// Persistent sessions should skip subscription if a session is present, as
|
2019-08-15 00:05:34 +00:00
|
|
|
// the subscriptions are stored by the server.
|
|
|
|
type sessionPresent interface {
|
|
|
|
SessionPresent() bool
|
|
|
|
}
|
|
|
|
if t, ok := token.(sessionPresent); ok && t.SessionPresent() {
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Debugf("Session found %v", m.Servers)
|
2019-08-15 00:05:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
topics := make(map[string]byte)
|
|
|
|
for _, topic := range m.Topics {
|
|
|
|
topics[topic] = byte(m.QoS)
|
|
|
|
}
|
|
|
|
|
|
|
|
subscribeToken := m.client.SubscribeMultiple(topics, m.recvMessage)
|
|
|
|
subscribeToken.Wait()
|
|
|
|
if subscribeToken.Error() != nil {
|
|
|
|
m.acc.AddError(fmt.Errorf("subscription error: topics: %s: %v",
|
|
|
|
strings.Join(m.Topics[:], ","), subscribeToken.Error()))
|
2016-04-14 02:58:45 +00:00
|
|
|
}
|
2018-10-15 20:03:52 +00:00
|
|
|
|
|
|
|
return nil
|
2016-04-14 02:58:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) onConnectionLost(c mqtt.Client, err error) {
|
2018-10-15 20:03:52 +00:00
|
|
|
m.acc.AddError(fmt.Errorf("connection lost: %v", err))
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Debugf("Disconnected %v", m.Servers)
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Disconnected
|
2016-04-14 02:58:45 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2018-10-15 20:03:52 +00:00
|
|
|
func (m *MQTTConsumer) recvMessage(c mqtt.Client, msg mqtt.Message) {
|
2018-11-05 21:34:28 +00:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case track := <-m.acc.Delivered():
|
2019-12-27 23:48:45 +00:00
|
|
|
<-m.sem
|
2018-11-05 21:34:28 +00:00
|
|
|
_, ok := m.messages[track.ID()]
|
|
|
|
if !ok {
|
|
|
|
// Added by a previous connection
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// No ack, MQTT does not support durable handling
|
|
|
|
delete(m.messages, track.ID())
|
|
|
|
case m.sem <- empty{}:
|
|
|
|
err := m.onMessage(m.acc, msg)
|
|
|
|
if err != nil {
|
|
|
|
m.acc.AddError(err)
|
|
|
|
<-m.sem
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) onMessage(acc telegraf.TrackingAccumulator, msg mqtt.Message) error {
|
2018-10-15 20:03:52 +00:00
|
|
|
metrics, err := m.parser.Parse(msg.Payload())
|
|
|
|
if err != nil {
|
2018-11-05 21:34:28 +00:00
|
|
|
return err
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
2019-08-20 02:05:22 +00:00
|
|
|
if m.topicTag != "" {
|
|
|
|
topic := msg.Topic()
|
|
|
|
for _, metric := range metrics {
|
|
|
|
metric.AddTag(m.topicTag, topic)
|
|
|
|
}
|
2018-10-15 20:03:52 +00:00
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
|
|
|
|
id := acc.AddTrackingMetricGroup(metrics)
|
|
|
|
m.messages[id] = true
|
|
|
|
return nil
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Stop() {
|
2018-10-15 20:03:52 +00:00
|
|
|
if m.state == Connected {
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Debugf("Disconnecting %v", m.Servers)
|
2017-09-11 19:24:51 +00:00
|
|
|
m.client.Disconnect(200)
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Debugf("Disconnected %v", m.Servers)
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Disconnected
|
2017-09-11 19:24:51 +00:00
|
|
|
}
|
2018-11-05 21:34:28 +00:00
|
|
|
m.cancel()
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Gather(acc telegraf.Accumulator) error {
|
2018-10-15 20:03:52 +00:00
|
|
|
if m.state == Disconnected {
|
|
|
|
m.state = Connecting
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Debugf("Connecting %v", m.Servers)
|
2017-09-11 19:24:51 +00:00
|
|
|
m.connect()
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) createOpts() (*mqtt.ClientOptions, error) {
|
|
|
|
opts := mqtt.NewClientOptions()
|
|
|
|
|
2017-09-11 19:24:51 +00:00
|
|
|
opts.ConnectTimeout = m.ConnectionTimeout.Duration
|
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
if m.ClientID == "" {
|
|
|
|
opts.SetClientID("Telegraf-Consumer-" + internal.RandomString(5))
|
|
|
|
} else {
|
|
|
|
opts.SetClientID(m.ClientID)
|
|
|
|
}
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2018-05-04 23:33:23 +00:00
|
|
|
tlsCfg, err := m.ClientConfig.TLSConfig()
|
2016-02-09 22:03:46 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if tlsCfg != nil {
|
|
|
|
opts.SetTLSConfig(tlsCfg)
|
|
|
|
}
|
|
|
|
|
|
|
|
user := m.Username
|
2016-03-02 17:36:23 +00:00
|
|
|
if user != "" {
|
2016-02-09 22:03:46 +00:00
|
|
|
opts.SetUsername(user)
|
|
|
|
}
|
|
|
|
password := m.Password
|
|
|
|
if password != "" {
|
|
|
|
opts.SetPassword(password)
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(m.Servers) == 0 {
|
2020-05-15 22:43:32 +00:00
|
|
|
return opts, fmt.Errorf("could not get host informations")
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
2017-10-30 22:33:20 +00:00
|
|
|
|
|
|
|
for _, server := range m.Servers {
|
|
|
|
// Preserve support for host:port style servers; deprecated in Telegraf 1.4.4
|
|
|
|
if !strings.Contains(server, "://") {
|
2019-09-23 22:39:50 +00:00
|
|
|
m.Log.Warnf("Server %q should be updated to use `scheme://host:port` format", server)
|
2017-10-30 22:33:20 +00:00
|
|
|
if tlsCfg == nil {
|
|
|
|
server = "tcp://" + server
|
|
|
|
} else {
|
|
|
|
server = "ssl://" + server
|
|
|
|
}
|
|
|
|
}
|
2016-02-09 22:03:46 +00:00
|
|
|
|
|
|
|
opts.AddBroker(server)
|
|
|
|
}
|
2018-10-15 20:03:52 +00:00
|
|
|
opts.SetAutoReconnect(false)
|
2016-02-09 22:03:46 +00:00
|
|
|
opts.SetKeepAlive(time.Second * 60)
|
2016-03-07 12:56:10 +00:00
|
|
|
opts.SetCleanSession(!m.PersistentSession)
|
2016-04-14 02:58:45 +00:00
|
|
|
opts.SetConnectionLostHandler(m.onConnectionLost)
|
2017-09-11 19:24:51 +00:00
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
return opts, nil
|
|
|
|
}
|
|
|
|
|
2019-08-15 00:05:34 +00:00
|
|
|
func New(factory ClientFactory) *MQTTConsumer {
|
|
|
|
return &MQTTConsumer{
|
|
|
|
Servers: []string{"tcp://127.0.0.1:1883"},
|
|
|
|
ConnectionTimeout: defaultConnectionTimeout,
|
|
|
|
MaxUndeliveredMessages: defaultMaxUndeliveredMessages,
|
|
|
|
clientFactory: factory,
|
|
|
|
state: Disconnected,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
func init() {
|
|
|
|
inputs.Add("mqtt_consumer", func() telegraf.Input {
|
2019-08-15 00:05:34 +00:00
|
|
|
return New(func(o *mqtt.ClientOptions) Client {
|
|
|
|
return mqtt.NewClient(o)
|
|
|
|
})
|
2016-02-09 22:03:46 +00:00
|
|
|
})
|
|
|
|
}
|