Fix graphite serialization of unsigned ints (#4033)

This commit is contained in:
Daniel Nelson 2018-04-18 12:13:25 -07:00 committed by GitHub
parent 1486ae25c0
commit dd2c60e620
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 10 deletions

View File

@ -2,8 +2,10 @@ package graphite
import ( import (
"fmt" "fmt"
"math"
"regexp" "regexp"
"sort" "sort"
"strconv"
"strings" "strings"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
@ -43,20 +45,14 @@ func (s *GraphiteSerializer) Serialize(metric telegraf.Metric) ([]byte, error) {
} }
for fieldName, value := range metric.Fields() { for fieldName, value := range metric.Fields() {
switch v := value.(type) { fieldValue := formatValue(value)
case string: if fieldValue == "" {
continue continue
case bool:
if v {
value = 1
} else {
value = 0
}
} }
metricString := fmt.Sprintf("%s %#v %d\n", metricString := fmt.Sprintf("%s %s %d\n",
// insert "field" section of template // insert "field" section of template
sanitize(InsertField(bucket, fieldName)), sanitize(InsertField(bucket, fieldName)),
value, fieldValue,
timestamp) timestamp)
point := []byte(metricString) point := []byte(metricString)
out = append(out, point...) out = append(out, point...)
@ -64,6 +60,34 @@ func (s *GraphiteSerializer) Serialize(metric telegraf.Metric) ([]byte, error) {
return out, nil return out, nil
} }
func formatValue(value interface{}) string {
switch v := value.(type) {
case string:
return ""
case bool:
if v {
return "1"
} else {
return "0"
}
case uint64:
return strconv.FormatUint(v, 10)
case int64:
return strconv.FormatInt(v, 10)
case float64:
if math.IsNaN(v) {
return ""
}
if math.IsInf(v, 0) {
return ""
}
return strconv.FormatFloat(v, 'f', -1, 64)
}
return ""
}
// SerializeBucketName will take the given measurement name and tags and // SerializeBucketName will take the given measurement name and tags and
// produce a graphite bucket. It will use the GraphiteSerializer.Template // produce a graphite bucket. It will use the GraphiteSerializer.Template
// to generate this, or DEFAULT_TEMPLATE. // to generate this, or DEFAULT_TEMPLATE.

View File

@ -218,6 +218,22 @@ func TestSerializeValueBoolean(t *testing.T) {
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
} }
func TestSerializeValueUnsigned(t *testing.T) {
now := time.Unix(0, 0)
tags := map[string]string{}
fields := map[string]interface{}{
"free": uint64(42),
}
m, err := metric.New("mem", tags, fields, now)
require.NoError(t, err)
s := GraphiteSerializer{}
buf, err := s.Serialize(m)
require.NoError(t, err)
require.Equal(t, buf, []byte(".mem.free 42 0\n"))
}
// test that fields with spaces get fixed. // test that fields with spaces get fixed.
func TestSerializeFieldWithSpaces(t *testing.T) { func TestSerializeFieldWithSpaces(t *testing.T) {
now := time.Now() now := time.Now()