Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix graphite serialization of unsigned ints #4033

Merged
merged 1 commit into from
Apr 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 34 additions & 10 deletions plugins/serializers/graphite/graphite.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package graphite

import (
"fmt"
"math"
"regexp"
"sort"
"strconv"
"strings"

"github.com/influxdata/telegraf"
Expand Down Expand Up @@ -43,27 +45,49 @@ func (s *GraphiteSerializer) Serialize(metric telegraf.Metric) ([]byte, error) {
}

for fieldName, value := range metric.Fields() {
switch v := value.(type) {
case string:
fieldValue := formatValue(value)
if fieldValue == "" {
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
sanitize(InsertField(bucket, fieldName)),
value,
fieldValue,
timestamp)
point := []byte(metricString)
out = append(out, point...)
}
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
// produce a graphite bucket. It will use the GraphiteSerializer.Template
// to generate this, or DEFAULT_TEMPLATE.
Expand Down
16 changes: 16 additions & 0 deletions plugins/serializers/graphite/graphite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,22 @@ func TestSerializeValueBoolean(t *testing.T) {
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.
func TestSerializeFieldWithSpaces(t *testing.T) {
now := time.Now()
Expand Down