forked from influxdata/telegraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
115 lines (95 loc) · 2.04 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package influx
import (
"errors"
"fmt"
"sync"
"github.com/influxdata/telegraf"
)
const (
maxErrorBufferSize = 1024
)
var (
ErrNoMetric = errors.New("no metric in line")
)
type ParseError struct {
Offset int
msg string
buf string
}
func (e *ParseError) Error() string {
buffer := e.buf
if len(buffer) > maxErrorBufferSize {
buffer = buffer[:maxErrorBufferSize] + "..."
}
return fmt.Sprintf("metric parse error: %s at offset %d: %q", e.msg, e.Offset, buffer)
}
type Parser struct {
DefaultTags map[string]string
sync.Mutex
*machine
handler *MetricHandler
}
// NewParser returns a Parser than accepts line protocol
func NewParser(handler *MetricHandler) *Parser {
return &Parser{
machine: NewMachine(handler),
handler: handler,
}
}
// NewSeriesParser returns a Parser than accepts a measurement and tagset
func NewSeriesParser(handler *MetricHandler) *Parser {
return &Parser{
machine: NewSeriesMachine(handler),
handler: handler,
}
}
func (p *Parser) Parse(input []byte) ([]telegraf.Metric, error) {
p.Lock()
defer p.Unlock()
metrics := make([]telegraf.Metric, 0)
p.machine.SetData(input)
for p.machine.ParseLine() {
err := p.machine.Err()
if err != nil {
p.handler.Reset()
return nil, &ParseError{
Offset: p.machine.Position(),
msg: err.Error(),
buf: string(input),
}
}
metric, err := p.handler.Metric()
if err != nil {
return nil, err
}
p.handler.Reset()
metrics = append(metrics, metric)
}
p.applyDefaultTags(metrics)
return metrics, nil
}
func (p *Parser) ParseLine(line string) (telegraf.Metric, error) {
metrics, err := p.Parse([]byte(line + "\n"))
if err != nil {
return nil, err
}
if len(metrics) < 1 {
return nil, ErrNoMetric
}
return metrics[0], nil
}
func (p *Parser) SetDefaultTags(tags map[string]string) {
p.DefaultTags = tags
}
func (p *Parser) applyDefaultTags(metrics []telegraf.Metric) {
if len(p.DefaultTags) == 0 {
return
}
for _, m := range metrics {
for k, v := range p.DefaultTags {
if !m.HasTag(k) {
m.AddTag(k, v)
}
}
}
}