2016-03-18 00:01:01 +00:00
|
|
|
package value
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
2016-05-02 18:17:20 +00:00
|
|
|
"strings"
|
2016-03-18 00:01:01 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/influxdata/telegraf"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ValueParser struct {
|
|
|
|
MetricName string
|
|
|
|
DataType string
|
|
|
|
DefaultTags map[string]string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
|
2016-11-16 13:13:31 +00:00
|
|
|
vStr := string(bytes.TrimSpace(bytes.Trim(buf, "\x00")))
|
|
|
|
|
2016-05-02 18:17:20 +00:00
|
|
|
// unless it's a string, separate out any fields in the buffer,
|
|
|
|
// ignore anything but the last.
|
2016-11-16 13:13:31 +00:00
|
|
|
if v.DataType != "string" {
|
|
|
|
values := strings.Fields(vStr)
|
2016-05-02 18:17:20 +00:00
|
|
|
if len(values) < 1 {
|
|
|
|
return []telegraf.Metric{}, nil
|
|
|
|
}
|
|
|
|
vStr = string(values[len(values)-1])
|
2016-03-18 00:01:01 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var value interface{}
|
|
|
|
var err error
|
|
|
|
switch v.DataType {
|
|
|
|
case "", "int", "integer":
|
2016-05-02 18:17:20 +00:00
|
|
|
value, err = strconv.Atoi(vStr)
|
2016-03-18 00:01:01 +00:00
|
|
|
case "float", "long":
|
2016-05-02 18:17:20 +00:00
|
|
|
value, err = strconv.ParseFloat(vStr, 64)
|
2016-03-18 00:01:01 +00:00
|
|
|
case "str", "string":
|
2016-05-02 18:17:20 +00:00
|
|
|
value = vStr
|
2016-03-18 00:01:01 +00:00
|
|
|
case "bool", "boolean":
|
2016-05-02 18:17:20 +00:00
|
|
|
value, err = strconv.ParseBool(vStr)
|
2016-03-18 00:01:01 +00:00
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
fields := map[string]interface{}{"value": value}
|
|
|
|
metric, err := telegraf.NewMetric(v.MetricName, v.DefaultTags,
|
|
|
|
fields, time.Now().UTC())
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return []telegraf.Metric{metric}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) {
|
|
|
|
metrics, err := v.Parse([]byte(line))
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(metrics) < 1 {
|
|
|
|
return nil, fmt.Errorf("Can not parse the line: %s, for data format: value", line)
|
|
|
|
}
|
|
|
|
|
|
|
|
return metrics[0], nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (v *ValueParser) SetDefaultTags(tags map[string]string) {
|
|
|
|
v.DefaultTags = tags
|
|
|
|
}
|