forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
92 lines (75 loc) · 1.93 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package prometheusremotewrite
import (
"fmt"
"math"
"time"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/plugins/parsers"
)
type Parser struct {
DefaultTags map[string]string
}
func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) {
var err error
var metrics []telegraf.Metric
var req prompb.WriteRequest
if err := req.Unmarshal(buf); err != nil {
return nil, fmt.Errorf("unable to unmarshal request body: %w", err)
}
now := time.Now()
for _, ts := range req.Timeseries {
tags := map[string]string{}
for key, value := range p.DefaultTags {
tags[key] = value
}
for _, l := range ts.Labels {
tags[l.Name] = l.Value
}
metricName := tags[model.MetricNameLabel]
if metricName == "" {
return nil, fmt.Errorf("metric name %q not found in tag-set or empty", model.MetricNameLabel)
}
delete(tags, model.MetricNameLabel)
for _, s := range ts.Samples {
fields := make(map[string]interface{})
if !math.IsNaN(s.Value) {
fields[metricName] = s.Value
}
// converting to telegraf metric
if len(fields) > 0 {
t := now
if s.Timestamp > 0 {
t = time.Unix(0, s.Timestamp*1000000)
}
m := metric.New("prometheus_remote_write", tags, fields, t)
metrics = append(metrics, m)
}
}
}
return metrics, err
}
func (p *Parser) ParseLine(line string) (telegraf.Metric, error) {
metrics, err := p.Parse([]byte(line))
if err != nil {
return nil, err
}
if len(metrics) < 1 {
return nil, fmt.Errorf("no metrics in line")
}
if len(metrics) > 1 {
return nil, fmt.Errorf("more than one metric in line")
}
return metrics[0], nil
}
func (p *Parser) SetDefaultTags(tags map[string]string) {
p.DefaultTags = tags
}
func init() {
parsers.Add("prometheusremotewrite",
func(defaultMetricName string) telegraf.Parser {
return &Parser{}
})
}