2016-02-09 22:03:46 +00:00
|
|
|
package mqtt_consumer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2016-04-14 02:58:45 +00:00
|
|
|
"strings"
|
2016-02-09 22:03:46 +00:00
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
"github.com/influxdata/telegraf/internal"
|
|
|
|
"github.com/influxdata/telegraf/plugins/inputs"
|
|
|
|
"github.com/influxdata/telegraf/plugins/parsers"
|
|
|
|
|
2016-03-30 17:54:01 +00:00
|
|
|
"github.com/eclipse/paho.mqtt.golang"
|
2016-02-09 22:03:46 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type MQTTConsumer struct {
|
2017-09-11 19:24:51 +00:00
|
|
|
Servers []string
|
|
|
|
Topics []string
|
|
|
|
Username string
|
|
|
|
Password string
|
|
|
|
QoS int `toml:"qos"`
|
|
|
|
ConnectionTimeout internal.Duration `toml:"connection_timeout"`
|
2016-02-09 22:03:46 +00:00
|
|
|
|
|
|
|
parser parsers.Parser
|
|
|
|
|
2016-02-16 00:21:38 +00:00
|
|
|
// Legacy metric buffer support
|
|
|
|
MetricBuffer int
|
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
PersistentSession bool
|
|
|
|
ClientID string `toml:"client_id"`
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
// Path to CA file
|
|
|
|
SSLCA string `toml:"ssl_ca"`
|
|
|
|
// Path to host cert file
|
|
|
|
SSLCert string `toml:"ssl_cert"`
|
|
|
|
// Path to cert key file
|
|
|
|
SSLKey string `toml:"ssl_key"`
|
|
|
|
// Use SSL but skip chain & host verification
|
|
|
|
InsecureSkipVerify bool
|
|
|
|
|
|
|
|
sync.Mutex
|
2016-03-30 17:54:01 +00:00
|
|
|
client mqtt.Client
|
2016-02-09 22:03:46 +00:00
|
|
|
// channel of all incoming raw mqtt messages
|
|
|
|
in chan mqtt.Message
|
|
|
|
done chan struct{}
|
2016-02-16 00:21:38 +00:00
|
|
|
|
|
|
|
// keep the accumulator internally:
|
|
|
|
acc telegraf.Accumulator
|
2016-04-14 02:58:45 +00:00
|
|
|
|
2017-09-11 19:24:51 +00:00
|
|
|
connected bool
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var sampleConfig = `
|
|
|
|
servers = ["localhost:1883"]
|
2016-02-18 21:26:51 +00:00
|
|
|
## MQTT QoS, must be 0, 1, or 2
|
2016-02-09 22:03:46 +00:00
|
|
|
qos = 0
|
2017-09-11 19:24:51 +00:00
|
|
|
## Connection timeout for initial connection in seconds
|
|
|
|
connection_timeout = 30
|
2016-02-09 22:03:46 +00:00
|
|
|
|
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"
|
|
|
|
|
2016-02-18 21:26:51 +00:00
|
|
|
## Optional SSL Config
|
2016-02-09 22:03:46 +00:00
|
|
|
# ssl_ca = "/etc/telegraf/ca.pem"
|
|
|
|
# ssl_cert = "/etc/telegraf/cert.pem"
|
|
|
|
# ssl_key = "/etc/telegraf/key.pem"
|
2016-02-18 21:26:51 +00:00
|
|
|
## Use SSL 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 {
|
2016-02-09 22:03:46 +00:00
|
|
|
m.Lock()
|
|
|
|
defer m.Unlock()
|
2017-09-11 19:24:51 +00:00
|
|
|
m.connected = false
|
2016-02-16 00:21:38 +00:00
|
|
|
|
2016-03-07 12:56:10 +00:00
|
|
|
if m.PersistentSession && m.ClientID == "" {
|
|
|
|
return fmt.Errorf("ERROR MQTT Consumer: When using persistent_session" +
|
|
|
|
" = true, you MUST also set client_id")
|
|
|
|
}
|
|
|
|
|
2016-02-16 00:21:38 +00:00
|
|
|
m.acc = acc
|
2016-02-09 22:03:46 +00:00
|
|
|
if m.QoS > 2 || m.QoS < 0 {
|
|
|
|
return fmt.Errorf("MQTT Consumer, invalid QoS value: %d", m.QoS)
|
|
|
|
}
|
|
|
|
|
2017-09-11 19:24:51 +00:00
|
|
|
if int(m.ConnectionTimeout.Duration) <= 0 {
|
|
|
|
return fmt.Errorf("MQTT Consumer, invalid connection_timeout value: %d", m.ConnectionTimeout)
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
opts, err := m.createOpts()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
m.client = mqtt.NewClient(opts)
|
2016-02-16 00:21:38 +00:00
|
|
|
m.in = make(chan mqtt.Message, 1000)
|
2016-02-09 22:03:46 +00:00
|
|
|
m.done = make(chan struct{})
|
|
|
|
|
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()
|
|
|
|
log.Printf("D! MQTT Consumer, connection error - %v", err)
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
go m.receiver()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2017-09-11 19:24:51 +00:00
|
|
|
|
2016-04-14 02:58:45 +00:00
|
|
|
func (m *MQTTConsumer) onConnect(c mqtt.Client) {
|
2016-09-30 21:37:56 +00:00
|
|
|
log.Printf("I! MQTT Client Connected")
|
2017-09-11 19:24:51 +00:00
|
|
|
if !m.PersistentSession || !m.connected {
|
2016-04-13 01:43:25 +00:00
|
|
|
topics := make(map[string]byte)
|
|
|
|
for _, topic := range m.Topics {
|
|
|
|
topics[topic] = byte(m.QoS)
|
|
|
|
}
|
|
|
|
subscribeToken := c.SubscribeMultiple(topics, m.recvMessage)
|
|
|
|
subscribeToken.Wait()
|
|
|
|
if subscribeToken.Error() != nil {
|
2017-03-24 19:03:36 +00:00
|
|
|
m.acc.AddError(fmt.Errorf("E! MQTT Subscribe Error\ntopics: %s\nerror: %s",
|
|
|
|
strings.Join(m.Topics[:], ","), subscribeToken.Error()))
|
2016-04-13 01:43:25 +00:00
|
|
|
}
|
2017-09-11 19:24:51 +00:00
|
|
|
m.connected = true
|
2016-04-14 02:58:45 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) onConnectionLost(c mqtt.Client, err error) {
|
2017-03-24 19:03:36 +00:00
|
|
|
m.acc.AddError(fmt.Errorf("E! MQTT Connection lost\nerror: %s\nMQTT Client will try to reconnect", err.Error()))
|
2016-04-14 02:58:45 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-02-09 22:03:46 +00:00
|
|
|
// receiver() reads all incoming messages from the consumer, and parses them into
|
|
|
|
// influxdb metric points.
|
|
|
|
func (m *MQTTConsumer) receiver() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-m.done:
|
|
|
|
return
|
|
|
|
case msg := <-m.in:
|
|
|
|
topic := msg.Topic()
|
|
|
|
metrics, err := m.parser.Parse(msg.Payload())
|
|
|
|
if err != nil {
|
2017-03-24 19:03:36 +00:00
|
|
|
m.acc.AddError(fmt.Errorf("E! MQTT Parse Error\nmessage: %s\nerror: %s",
|
|
|
|
string(msg.Payload()), err.Error()))
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, metric := range metrics {
|
2016-02-16 00:21:38 +00:00
|
|
|
tags := metric.Tags()
|
|
|
|
tags["topic"] = topic
|
|
|
|
m.acc.AddFields(metric.Name(), metric.Fields(), tags, metric.Time())
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-30 17:54:01 +00:00
|
|
|
func (m *MQTTConsumer) recvMessage(_ mqtt.Client, msg mqtt.Message) {
|
2016-02-09 22:03:46 +00:00
|
|
|
m.in <- msg
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Stop() {
|
|
|
|
m.Lock()
|
|
|
|
defer m.Unlock()
|
2017-09-11 19:24:51 +00:00
|
|
|
|
|
|
|
if m.connected {
|
|
|
|
close(m.done)
|
|
|
|
m.client.Disconnect(200)
|
|
|
|
m.connected = false
|
|
|
|
}
|
2016-02-09 22:03:46 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *MQTTConsumer) Gather(acc telegraf.Accumulator) error {
|
2017-09-11 19:24:51 +00:00
|
|
|
if !m.connected {
|
|
|
|
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
|
|
|
|
|
|
|
tlsCfg, err := internal.GetTLSConfig(
|
|
|
|
m.SSLCert, m.SSLKey, m.SSLCA, m.InsecureSkipVerify)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
scheme := "tcp"
|
|
|
|
if tlsCfg != nil {
|
|
|
|
scheme = "ssl"
|
|
|
|
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")
|
|
|
|
}
|
|
|
|
for _, host := range m.Servers {
|
|
|
|
server := fmt.Sprintf("%s://%s", scheme, host)
|
|
|
|
|
|
|
|
opts.AddBroker(server)
|
|
|
|
}
|
|
|
|
opts.SetAutoReconnect(true)
|
|
|
|
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.SetOnConnectHandler(m.onConnect)
|
|
|
|
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 {
|
|
|
|
return &MQTTConsumer{}
|
|
|
|
})
|
|
|
|
}
|