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"
|
|
|
|
"log"
|
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
|
|
|
|
)
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
type MQTTConsumer struct {
|
2018-11-05 21:34:28 +00:00
|
|
|
Servers []string
|
|
|
|
Topics []string
|
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
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
|
|
|
|
2018-10-15 20:03:52 +00:00
|
|
|
client mqtt.Client
|
2018-11-05 21:34:28 +00:00
|
|
|
acc telegraf.TrackingAccumulator
|
2018-10-15 20:03:52 +00:00
|
|
|
state ConnectionState
|
|
|
|
subscribed bool
|
2018-11-05 21:34:28 +00:00
|
|
|
sem semaphore
|
|
|
|
messages map[telegraf.TrackingID]bool
|
|
|
|
|
|
|
|
ctx context.Context
|
|
|
|
cancel context.CancelFunc
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var sampleConfig = `
|
2017-10-30 22:33:20 +00:00
|
|
|
## MQTT broker URLs to be used. The format should be scheme://host:port,
|
|
|
|
## schema can be tcp, ssl, or ws.
|
|
|
|
servers = ["tcp://localhost:1883"]
|
|
|
|
|
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.
|
2016-02-09 22:03:46 +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
|
2017-09-29 22:58:38 +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
|
|
|
|
|
2016-02-18 21:26:51 +00:00
|
|
|
## Topics to subscribe to
|
2016-02-09 22:03:46 +00:00
|
|
|
topics = [
|
|
|
|
"telegraf/host01/cpu",
|
|
|
|
"telegraf/+/mem",
|
|
|
|
"sensors/#",
|
|
|
|
]
|
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
# if true, messages that can't be delivered while the subscriber is offline
|
|
|
|
# will be delivered when it comes back (such as on service restart).
|
|
|
|
# NOTE: if true, client_id MUST be set
|
|
|
|
persistent_session = false
|
|
|
|
# If empty, a random client ID will be generated.
|
|
|
|
client_id = ""
|
|
|
|
|
2016-02-18 21:26:51 +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
|
|
|
|
}
|
|
|
|
|
2016-02-16 00:21:38 +00:00
|
|
|
func (m *MQTTConsumer) Start(acc telegraf.Accumulator) 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
|
|
|
}
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
m.acc = acc.WithTracking(m.MaxUndeliveredMessages)
|
|
|
|
m.ctx, m.cancel = context.WithCancel(context.Background())
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
opts, err := m.createOpts()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
m.client = mqtt.NewClient(opts)
|
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 {
|
|
|
|
if token := m.client.Connect(); token.Wait() && token.Error() != nil {
|
|
|
|
err := token.Error()
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Disconnected
|
2017-09-11 19:24:51 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("I! [inputs.mqtt_consumer] Connected %v", m.Servers)
|
2018-10-15 20:03:52 +00:00
|
|
|
m.state = Connected
|
2018-11-05 21:34:28 +00:00
|
|
|
m.sem = make(semaphore, m.MaxUndeliveredMessages)
|
|
|
|
m.messages = make(map[telegraf.TrackingID]bool)
|
2016-02-09 22:03:46 +00:00
|
|
|
|
2018-10-15 20:03:52 +00:00
|
|
|
// Only subscribe on first connection when using persistent sessions. On
|
|
|
|
// subsequent connections the subscriptions should be stored in the
|
|
|
|
// session, but the proper way to do this is to check the connection
|
|
|
|
// response to ensure a session was found.
|
|
|
|
if !m.PersistentSession || !m.subscribed {
|
2016-04-13 01:43:25 +00:00
|
|
|
topics := make(map[string]byte)
|
|
|
|
for _, topic := range m.Topics {
|
|
|
|
topics[topic] = byte(m.QoS)
|
|
|
|
}
|
2018-10-15 20:03:52 +00:00
|
|
|
subscribeToken := m.client.SubscribeMultiple(topics, m.recvMessage)
|
2016-04-13 01:43:25 +00:00
|
|
|
subscribeToken.Wait()
|
|
|
|
if subscribeToken.Error() != nil {
|
2018-10-15 20:03:52 +00:00
|
|
|
m.acc.AddError(fmt.Errorf("subscription error: topics: %s: %v",
|
2017-03-24 19:03:36 +00:00
|
|
|
strings.Join(m.Topics[:], ","), subscribeToken.Error()))
|
2016-04-13 01:43:25 +00:00
|
|
|
}
|
2018-10-15 20:03:52 +00:00
|
|
|
m.subscribed = true
|
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))
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("D! [inputs.mqtt_consumer] 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():
|
|
|
|
_, ok := m.messages[track.ID()]
|
|
|
|
if !ok {
|
|
|
|
// Added by a previous connection
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
<-m.sem
|
|
|
|
// 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
|
|
|
}
|
|
|
|
|
2018-11-05 21:34:28 +00:00
|
|
|
topic := msg.Topic()
|
2018-10-15 20:03:52 +00:00
|
|
|
for _, metric := range metrics {
|
2018-11-05 21:34:28 +00:00
|
|
|
metric.AddTag("topic", 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 {
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("D! [inputs.mqtt_consumer] Disconnecting %v", m.Servers)
|
2017-09-11 19:24:51 +00:00
|
|
|
m.client.Disconnect(200)
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("D! [inputs.mqtt_consumer] 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
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("D! [inputs.mqtt_consumer] 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 {
|
|
|
|
return opts, fmt.Errorf("could not get host infomations")
|
|
|
|
}
|
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, "://") {
|
2018-11-05 21:34:28 +00:00
|
|
|
log.Printf("W! [inputs.mqtt_consumer] 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
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
inputs.Add("mqtt_consumer", func() telegraf.Input {
|
2017-09-29 22:58:38 +00:00
|
|
|
return &MQTTConsumer{
|
2018-11-05 21:34:28 +00:00
|
|
|
ConnectionTimeout: defaultConnectionTimeout,
|
|
|
|
MaxUndeliveredMessages: defaultMaxUndeliveredMessages,
|
2019-01-08 01:14:07 +00:00
|
|
|
state: Disconnected,
|
2017-09-29 22:58:38 +00:00
|
|
|
}
|
2016-02-09 22:03:46 +00:00
|
|
|
})
|
|
|
|
}
|