2021-05-18 15:15:26 +02:00
|
|
|
package receivers
|
|
|
|
|
|
|
|
import (
|
2021-05-18 15:44:42 +02:00
|
|
|
"errors"
|
2021-05-18 15:15:26 +02:00
|
|
|
s "github.com/ClusterCockpit/cc-metric-collector/sinks"
|
2021-10-04 15:23:43 +02:00
|
|
|
lp "github.com/influxdata/line-protocol"
|
2021-05-18 15:15:26 +02:00
|
|
|
nats "github.com/nats-io/nats.go"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NatsReceiver struct {
|
|
|
|
Receiver
|
2021-10-08 13:28:44 +02:00
|
|
|
nc *nats.Conn
|
|
|
|
handler *lp.MetricHandler
|
|
|
|
parser *lp.Parser
|
2021-05-18 15:15:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
var DefaultTime = func() time.Time {
|
|
|
|
return time.Unix(42, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *NatsReceiver) Init(config ReceiverConfig, sink s.SinkFuncs) error {
|
2021-05-18 15:44:42 +02:00
|
|
|
if len(config.Addr) == 0 ||
|
2021-05-18 15:15:26 +02:00
|
|
|
len(config.Port) == 0 ||
|
|
|
|
len(config.Database) == 0 {
|
|
|
|
return errors.New("Not all configuration variables set required by NatsReceiver")
|
|
|
|
}
|
|
|
|
r.addr = config.Addr
|
|
|
|
if len(r.addr) == 0 {
|
|
|
|
r.addr = nats.DefaultURL
|
|
|
|
}
|
|
|
|
r.port = config.Port
|
|
|
|
if len(r.port) == 0 {
|
|
|
|
r.port = "4222"
|
|
|
|
}
|
|
|
|
log.Print("Init NATS Receiver")
|
|
|
|
nc, err := nats.Connect(r.addr)
|
|
|
|
if err == nil {
|
|
|
|
r.database = config.Database
|
|
|
|
r.sink = sink
|
|
|
|
r.nc = nc
|
|
|
|
} else {
|
|
|
|
log.Print(err)
|
|
|
|
r.nc = nil
|
|
|
|
}
|
2021-10-08 13:28:44 +02:00
|
|
|
r.handler = lp.NewMetricHandler()
|
|
|
|
r.parser = lp.NewParser(r.handler)
|
|
|
|
r.parser.SetTimeFunc(DefaultTime)
|
2021-05-18 15:15:26 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *NatsReceiver) Start() {
|
|
|
|
log.Print("Start NATS Receiver")
|
|
|
|
r.nc.Subscribe(r.database, r._NatsReceive)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *NatsReceiver) _NatsReceive(m *nats.Msg) {
|
2021-10-08 13:28:44 +02:00
|
|
|
metrics, err := r.parser.Parse(m.Data)
|
2021-05-18 15:15:26 +02:00
|
|
|
if err == nil {
|
|
|
|
for _, m := range metrics {
|
2021-10-04 15:23:43 +02:00
|
|
|
y, err := lp.New(m.Name(), Tags2Map(m), Fields2Map(m), m.Time())
|
|
|
|
if err == nil {
|
|
|
|
r.sink.Write(y)
|
|
|
|
}
|
2021-05-18 15:15:26 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *NatsReceiver) Close() {
|
|
|
|
if r.nc != nil {
|
|
|
|
log.Print("Close NATS Receiver")
|
|
|
|
r.nc.Close()
|
|
|
|
}
|
|
|
|
}
|