2016-02-06 00:36:35 +00:00
|
|
|
package influx
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
2016-10-18 11:22:23 +00:00
|
|
|
"time"
|
2016-02-06 00:36:35 +00:00
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
2016-11-22 12:51:57 +00:00
|
|
|
"github.com/influxdata/telegraf/metric"
|
2016-02-06 00:36:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// InfluxParser is an object for Parsing incoming metrics.
|
|
|
|
type InfluxParser struct {
|
|
|
|
// DefaultTags will be added to every parsed metric
|
|
|
|
DefaultTags map[string]string
|
|
|
|
}
|
|
|
|
|
2017-04-10 23:39:40 +00:00
|
|
|
func (p *InfluxParser) ParseWithDefaultTimePrecision(buf []byte, t time.Time, precision string) ([]telegraf.Metric, error) {
|
2017-01-23 21:50:52 +00:00
|
|
|
if !bytes.HasSuffix(buf, []byte("\n")) {
|
|
|
|
buf = append(buf, '\n')
|
|
|
|
}
|
2016-02-06 00:36:35 +00:00
|
|
|
// parse even if the buffer begins with a newline
|
|
|
|
buf = bytes.TrimPrefix(buf, []byte("\n"))
|
2017-04-10 23:39:40 +00:00
|
|
|
metrics, err := metric.ParseWithDefaultTimePrecision(buf, t, precision)
|
2016-11-22 12:51:57 +00:00
|
|
|
if len(p.DefaultTags) > 0 {
|
|
|
|
for _, m := range metrics {
|
|
|
|
for k, v := range p.DefaultTags {
|
|
|
|
// only set the default tag if it doesn't already exist:
|
|
|
|
if !m.HasTag(k) {
|
|
|
|
m.AddTag(k, v)
|
|
|
|
}
|
2016-02-06 00:36:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return metrics, err
|
|
|
|
}
|
|
|
|
|
2016-10-18 11:22:23 +00:00
|
|
|
// Parse returns a slice of Metrics from a text representation of a
|
|
|
|
// metric (in line-protocol format)
|
|
|
|
// with each metric separated by newlines. If any metrics fail to parse,
|
|
|
|
// a non-nil error will be returned in addition to the metrics that parsed
|
|
|
|
// successfully.
|
|
|
|
func (p *InfluxParser) Parse(buf []byte) ([]telegraf.Metric, error) {
|
2017-04-10 23:39:40 +00:00
|
|
|
return p.ParseWithDefaultTimePrecision(buf, time.Now(), "")
|
2016-10-18 11:22:23 +00:00
|
|
|
}
|
|
|
|
|
2016-02-06 00:36:35 +00:00
|
|
|
func (p *InfluxParser) 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, fmt.Errorf(
|
|
|
|
"Can not parse the line: %s, for data format: influx ", line)
|
|
|
|
}
|
|
|
|
|
|
|
|
return metrics[0], nil
|
|
|
|
}
|
2016-02-09 22:03:46 +00:00
|
|
|
|
|
|
|
func (p *InfluxParser) SetDefaultTags(tags map[string]string) {
|
|
|
|
p.DefaultTags = tags
|
|
|
|
}
|