influxdb/gather/handler.go

51 lines
1.1 KiB
Go
Raw Normal View History

2018-09-07 15:45:28 +00:00
package gather
import (
"bytes"
"context"
"encoding/json"
"github.com/influxdata/influxdb/v2"
"github.com/influxdata/influxdb/v2/nats"
2018-09-07 15:45:28 +00:00
"go.uber.org/zap"
)
// handler implents nats Handler interface.
type handler struct {
Scraper Scraper
Publisher nats.Publisher
log *zap.Logger
2018-09-07 15:45:28 +00:00
}
// Process consumes scraper target from scraper target queue,
// call the scraper to gather, and publish to metrics queue.
func (h *handler) Process(s nats.Subscription, m nats.Message) {
defer m.Ack()
2019-01-10 17:39:37 +00:00
req := new(influxdb.ScraperTarget)
2018-09-07 15:45:28 +00:00
err := json.Unmarshal(m.Data(), req)
if err != nil {
h.log.Error("Unable to unmarshal json", zap.Error(err))
2018-09-07 15:45:28 +00:00
return
}
ms, err := h.Scraper.Gather(context.TODO(), *req)
if err != nil {
h.log.Error("Unable to gather", zap.Error(err))
2018-09-07 15:45:28 +00:00
return
}
2019-01-10 17:39:37 +00:00
// send metrics to recorder queue
2018-09-07 15:45:28 +00:00
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(ms); err != nil {
h.log.Error("Unable to marshal json", zap.Error(err))
2018-09-07 15:45:28 +00:00
return
}
if err := h.Publisher.Publish(MetricsSubject, buf); err != nil {
h.log.Error("Unable to publish scraper metrics", zap.Error(err))
2018-09-07 15:45:28 +00:00
return
}
}