2021-03-26 16:48:09 +01:00
|
|
|
package sinks
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-06-30 16:56:47 +02:00
|
|
|
"crypto/tls"
|
2021-05-18 15:16:10 +02:00
|
|
|
"errors"
|
2021-03-26 16:48:09 +01:00
|
|
|
"fmt"
|
|
|
|
influxdb2 "github.com/influxdata/influxdb-client-go/v2"
|
|
|
|
influxdb2Api "github.com/influxdata/influxdb-client-go/v2/api"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type InfluxSink struct {
|
|
|
|
Sink
|
2021-05-18 15:16:10 +02:00
|
|
|
client influxdb2.Client
|
|
|
|
writeApi influxdb2Api.WriteAPIBlocking
|
|
|
|
retPolicy string
|
2021-03-26 16:48:09 +01:00
|
|
|
}
|
|
|
|
|
2021-05-18 15:16:10 +02:00
|
|
|
func (s *InfluxSink) connect() error {
|
|
|
|
var auth string
|
2021-06-30 16:56:47 +02:00
|
|
|
var uri string
|
|
|
|
if s.ssl {
|
|
|
|
uri = fmt.Sprintf("https://%s:%s", s.host, s.port)
|
|
|
|
} else {
|
|
|
|
uri = fmt.Sprintf("http://%s:%s", s.host, s.port)
|
|
|
|
}
|
2021-05-18 15:16:10 +02:00
|
|
|
if len(s.user) == 0 {
|
|
|
|
auth = s.password
|
|
|
|
} else {
|
|
|
|
auth = fmt.Sprintf("%s:%s", s.user, s.password)
|
|
|
|
}
|
|
|
|
log.Print("Using URI ", uri, " Org ", s.organization, " Bucket ", s.database)
|
2021-06-30 16:56:47 +02:00
|
|
|
s.client = influxdb2.NewClientWithOptions(uri, auth,
|
|
|
|
influxdb2.DefaultOptions().SetTLSConfig(&tls.Config{InsecureSkipVerify: true}))
|
2021-03-26 16:48:09 +01:00
|
|
|
s.writeApi = s.client.WriteAPIBlocking(s.organization, s.database)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-05-18 15:16:10 +02:00
|
|
|
func (s *InfluxSink) Init(config SinkConfig) error {
|
|
|
|
if len(config.Host) == 0 ||
|
|
|
|
len(config.Port) == 0 ||
|
|
|
|
len(config.Database) == 0 ||
|
|
|
|
len(config.Organization) == 0 ||
|
|
|
|
len(config.Password) == 0 {
|
|
|
|
return errors.New("Not all configuration variables set required by InfluxSink")
|
|
|
|
}
|
|
|
|
s.host = config.Host
|
|
|
|
s.port = config.Port
|
|
|
|
s.database = config.Database
|
|
|
|
s.organization = config.Organization
|
|
|
|
s.user = config.User
|
|
|
|
s.password = config.Password
|
2021-06-30 16:56:47 +02:00
|
|
|
s.ssl = config.SSL
|
2021-05-18 15:16:10 +02:00
|
|
|
return s.connect()
|
|
|
|
}
|
|
|
|
|
2021-03-26 16:48:09 +01:00
|
|
|
func (s *InfluxSink) Write(measurement string, tags map[string]string, fields map[string]interface{}, t time.Time) error {
|
|
|
|
p := influxdb2.NewPoint(measurement, tags, fields, t)
|
|
|
|
err := s.writeApi.WritePoint(context.Background(), p)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *InfluxSink) Close() {
|
|
|
|
log.Print("Closing InfluxDB connection")
|
|
|
|
s.client.Close()
|
|
|
|
}
|