Hand over full config to Sink and Receiver

This commit is contained in:
Thomas Roehl
2021-05-18 15:16:10 +02:00
parent b1e6b8e379
commit 1b9cb8955c
5 changed files with 137 additions and 70 deletions

View File

@@ -2,6 +2,7 @@ package sinks
import (
"bytes"
"errors"
"fmt"
protocol "github.com/influxdata/line-protocol"
nats "github.com/nats-io/nats.go"
@@ -16,21 +17,11 @@ type NatsSink struct {
buffer *bytes.Buffer
}
func (s *NatsSink) Init(host string, port string, user string, password string, database string) error {
s.host = host
s.port = port
s.user = user
s.password = password
s.database = database
// Setup Influx line protocol
s.buffer = &bytes.Buffer{}
s.buffer.Grow(1025)
s.encoder = protocol.NewEncoder(s.buffer)
s.encoder.SetPrecision(time.Second)
s.encoder.SetMaxLineBytes(1024)
// Setup infos for connection
func (s *NatsSink) connect() error {
uinfo := nats.UserInfo(s.user, s.password)
uri := fmt.Sprintf("nats://%s:%s", s.host, s.port)
log.Print("Using URI ", uri)
s.client = nil
nc, err := nats.Connect(uri, uinfo)
if err != nil {
log.Fatal(err)
@@ -40,21 +31,49 @@ func (s *NatsSink) Init(host string, port string, user string, password string,
return nil
}
func (s *NatsSink) Init(config SinkConfig) error {
if len(config.Host) == 0 ||
len(config.Port) == 0 ||
len(config.Database) == 0 {
return errors.New("Not all configuration variables set required by NatsSink")
}
s.host = config.Host
s.port = config.Port
s.database = config.Database
s.organization = config.Organization
s.user = config.User
s.password = config.Password
// Setup Influx line protocol
s.buffer = &bytes.Buffer{}
s.buffer.Grow(1025)
s.encoder = protocol.NewEncoder(s.buffer)
s.encoder.SetPrecision(time.Second)
s.encoder.SetMaxLineBytes(1024)
// Setup infos for connection
return s.connect()
}
func (s *NatsSink) Write(measurement string, tags map[string]string, fields map[string]interface{}, t time.Time) error {
m, err := protocol.New(measurement, tags, fields, t)
if err != nil {
log.Print(err)
return err
if s.client != nil {
m, err := protocol.New(measurement, tags, fields, t)
if err != nil {
log.Print(err)
return err
}
_, err = s.encoder.Encode(m)
if err != nil {
log.Print(err)
return err
}
s.client.Publish(s.database, s.buffer.Bytes())
}
_, err = s.encoder.Encode(m)
if err != nil {
log.Print(err)
return err
}
s.client.Publish(s.database, s.buffer.Bytes())
return nil
}
func (s *NatsSink) Close() {
s.client.Close()
log.Print("Closing Nats connection")
if s.client != nil {
s.client.Close()
}
}