Remove error return type from metric.New method (#9116)

* Remove error return type from metric.New method.

* Formatting changes for linter + gofmt

* Additional linter fixes.

* More linter fixes.

* Linter fix.

* address comments
This commit is contained in:
David Bennett 2021-04-13 14:40:03 -04:00 committed by GitHub
parent 411df7d763
commit 842a788022
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
94 changed files with 1433 additions and 1937 deletions

View File

@ -90,10 +90,7 @@ func (ac *accumulator) addFields(
tp telegraf.ValueType, tp telegraf.ValueType,
t ...time.Time, t ...time.Time,
) { ) {
m, err := metric.New(measurement, tags, fields, ac.getTime(t), tp) m := metric.New(measurement, tags, fields, ac.getTime(t), tp)
if err != nil {
return
}
if m := ac.maker.MakeMetric(m); m != nil { if m := ac.maker.MakeMetric(m); m != nil {
ac.metrics <- m ac.metrics <- m
} }

View File

@ -24,7 +24,7 @@ func New(
fields map[string]interface{}, fields map[string]interface{},
tm time.Time, tm time.Time,
tp ...telegraf.ValueType, tp ...telegraf.ValueType,
) (telegraf.Metric, error) { ) telegraf.Metric {
var vtype telegraf.ValueType var vtype telegraf.ValueType
if len(tp) > 0 { if len(tp) > 0 {
vtype = tp[0] vtype = tp[0]
@ -60,7 +60,7 @@ func New(
} }
} }
return m, nil return m
} }
// FromMetric returns a deep copy of the metric with any tracking information // FromMetric returns a deep copy of the metric with any tracking information

View File

@ -20,8 +20,7 @@ func TestNewMetric(t *testing.T) {
"usage_idle": float64(99), "usage_idle": float64(99),
"usage_busy": float64(1), "usage_busy": float64(1),
} }
m, err := New("cpu", tags, fields, now) m := New("cpu", tags, fields, now)
require.NoError(t, err)
require.Equal(t, "cpu", m.Name()) require.Equal(t, "cpu", m.Name())
require.Equal(t, tags, m.Tags()) require.Equal(t, tags, m.Tags())
@ -38,10 +37,7 @@ func baseMetric() telegraf.Metric {
} }
now := time.Now() now := time.Now()
m, err := New("cpu", tags, fields, now) m := New("cpu", tags, fields, now)
if err != nil {
panic(err)
}
return m return m
} }
@ -176,7 +172,7 @@ func TestTagList_Sorted(t *testing.T) {
func TestEquals(t *testing.T) { func TestEquals(t *testing.T) {
now := time.Now() now := time.Now()
m1, err := New("cpu", m1 := New("cpu",
map[string]string{ map[string]string{
"host": "localhost", "host": "localhost",
}, },
@ -185,9 +181,8 @@ func TestEquals(t *testing.T) {
}, },
now, now,
) )
require.NoError(t, err)
m2, err := New("cpu", m2 := New("cpu",
map[string]string{ map[string]string{
"host": "localhost", "host": "localhost",
}, },
@ -196,7 +191,6 @@ func TestEquals(t *testing.T) {
}, },
now, now,
) )
require.NoError(t, err)
lhs := m1.(*metric) lhs := m1.(*metric)
require.Equal(t, lhs, m2) require.Equal(t, lhs, m2)
@ -208,7 +202,7 @@ func TestEquals(t *testing.T) {
} }
func TestHashID(t *testing.T) { func TestHashID(t *testing.T) {
m, _ := New( m := New(
"cpu", "cpu",
map[string]string{ map[string]string{
"datacenter": "us-east-1", "datacenter": "us-east-1",
@ -241,7 +235,7 @@ func TestHashID(t *testing.T) {
} }
func TestHashID_Consistency(t *testing.T) { func TestHashID_Consistency(t *testing.T) {
m, _ := New( m := New(
"cpu", "cpu",
map[string]string{ map[string]string{
"datacenter": "us-east-1", "datacenter": "us-east-1",
@ -255,7 +249,7 @@ func TestHashID_Consistency(t *testing.T) {
) )
hash := m.HashID() hash := m.HashID()
m2, _ := New( m2 := New(
"cpu", "cpu",
map[string]string{ map[string]string{
"datacenter": "us-east-1", "datacenter": "us-east-1",
@ -274,7 +268,7 @@ func TestHashID_Consistency(t *testing.T) {
} }
func TestHashID_Delimiting(t *testing.T) { func TestHashID_Delimiting(t *testing.T) {
m1, _ := New( m1 := New(
"cpu", "cpu",
map[string]string{ map[string]string{
"a": "x", "a": "x",
@ -286,7 +280,7 @@ func TestHashID_Delimiting(t *testing.T) {
}, },
time.Now(), time.Now(),
) )
m2, _ := New( m2 := New(
"cpu", "cpu",
map[string]string{ map[string]string{
"a": "xbycz", "a": "xbycz",
@ -328,8 +322,7 @@ func TestValueType(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(42), "value": float64(42),
} }
m, err := New("cpu", tags, fields, now, telegraf.Gauge) m := New("cpu", tags, fields, now, telegraf.Gauge)
assert.NoError(t, err)
assert.Equal(t, telegraf.Gauge, m.Type()) assert.Equal(t, telegraf.Gauge, m.Type())
} }

View File

@ -50,18 +50,14 @@ func (g *SeriesGrouper) Add(
} }
sort.Slice(taglist, func(i, j int) bool { return taglist[i].Key < taglist[j].Key }) sort.Slice(taglist, func(i, j int) bool { return taglist[i].Key < taglist[j].Key })
var err error
id := groupID(g.hashSeed, measurement, taglist, tm) id := groupID(g.hashSeed, measurement, taglist, tm)
metric := g.metrics[id] m := g.metrics[id]
if metric == nil { if m == nil {
metric, err = New(measurement, tags, map[string]interface{}{field: fieldValue}, tm) m = New(measurement, tags, map[string]interface{}{field: fieldValue}, tm)
if err != nil { g.metrics[id] = m
return err g.ordered = append(g.ordered, m)
}
g.metrics[id] = metric
g.ordered = append(g.ordered, metric)
} else { } else {
metric.AddField(field, fieldValue) m.AddField(field, fieldValue)
} }
return nil return nil
} }

View File

@ -6,7 +6,7 @@ import (
"time" "time"
) )
var m, _ = New( var m = New(
"mymetric", "mymetric",
map[string]string{ map[string]string{
"host": "host.example.com", "host": "host.example.com",

View File

@ -16,10 +16,7 @@ func mustMetric(
tm time.Time, tm time.Time,
tp ...telegraf.ValueType, tp ...telegraf.ValueType,
) telegraf.Metric { ) telegraf.Metric {
m, err := New(name, tags, fields, tm, tp...) m := New(name, tags, fields, tm, tp...)
if err != nil {
panic("mustMetric")
}
return m return m
} }

View File

@ -34,7 +34,7 @@ func Metric() telegraf.Metric {
} }
func MetricTime(sec int64) telegraf.Metric { func MetricTime(sec int64) telegraf.Metric {
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -42,9 +42,6 @@ func MetricTime(sec int64) telegraf.Metric {
}, },
time.Unix(sec, 0), time.Unix(sec, 0),
) )
if err != nil {
panic(err)
}
return m return m
} }

View File

@ -15,11 +15,10 @@ func TestFilter_ApplyEmpty(t *testing.T) {
require.NoError(t, f.Compile()) require.NoError(t, f.Compile())
require.False(t, f.IsActive()) require.False(t, f.IsActive())
m, err := metric.New("m", m := metric.New("m",
map[string]string{}, map[string]string{},
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now()) time.Now())
require.NoError(t, err)
require.True(t, f.Select(m)) require.True(t, f.Select(m))
} }
@ -37,11 +36,10 @@ func TestFilter_ApplyTagsDontPass(t *testing.T) {
require.NoError(t, f.Compile()) require.NoError(t, f.Compile())
require.True(t, f.IsActive()) require.True(t, f.IsActive())
m, err := metric.New("m", m := metric.New("m",
map[string]string{"cpu": "cpu-total"}, map[string]string{"cpu": "cpu-total"},
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now()) time.Now())
require.NoError(t, err)
require.False(t, f.Select(m)) require.False(t, f.Select(m))
} }
@ -53,14 +51,13 @@ func TestFilter_ApplyDeleteFields(t *testing.T) {
require.NoError(t, f.Compile()) require.NoError(t, f.Compile())
require.True(t, f.IsActive()) require.True(t, f.IsActive())
m, err := metric.New("m", m := metric.New("m",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(1), "value": int64(1),
"value2": int64(2), "value2": int64(2),
}, },
time.Now()) time.Now())
require.NoError(t, err)
require.True(t, f.Select(m)) require.True(t, f.Select(m))
f.Modify(m) f.Modify(m)
require.Equal(t, map[string]interface{}{"value2": int64(2)}, m.Fields()) require.Equal(t, map[string]interface{}{"value2": int64(2)}, m.Fields())
@ -74,14 +71,13 @@ func TestFilter_ApplyDeleteAllFields(t *testing.T) {
require.NoError(t, f.Compile()) require.NoError(t, f.Compile())
require.True(t, f.IsActive()) require.True(t, f.IsActive())
m, err := metric.New("m", m := metric.New("m",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(1), "value": int64(1),
"value2": int64(2), "value2": int64(2),
}, },
time.Now()) time.Now())
require.NoError(t, err)
require.True(t, f.Select(m)) require.True(t, f.Select(m))
f.Modify(m) f.Modify(m)
require.Len(t, m.FieldList(), 0) require.Len(t, m.FieldList(), 0)
@ -332,14 +328,13 @@ func TestFilter_TagDrop(t *testing.T) {
} }
func TestFilter_FilterTagsNoMatches(t *testing.T) { func TestFilter_FilterTagsNoMatches(t *testing.T) {
m, err := metric.New("m", m := metric.New("m",
map[string]string{ map[string]string{
"host": "localhost", "host": "localhost",
"mytag": "foobar", "mytag": "foobar",
}, },
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now()) time.Now())
require.NoError(t, err)
f := Filter{ f := Filter{
TagExclude: []string{"nomatch"}, TagExclude: []string{"nomatch"},
} }
@ -361,14 +356,13 @@ func TestFilter_FilterTagsNoMatches(t *testing.T) {
} }
func TestFilter_FilterTagsMatches(t *testing.T) { func TestFilter_FilterTagsMatches(t *testing.T) {
m, err := metric.New("m", m := metric.New("m",
map[string]string{ map[string]string{
"host": "localhost", "host": "localhost",
"mytag": "foobar", "mytag": "foobar",
}, },
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now()) time.Now())
require.NoError(t, err)
f := Filter{ f := Filter{
TagExclude: []string{"ho*"}, TagExclude: []string{"ho*"},
} }
@ -379,14 +373,13 @@ func TestFilter_FilterTagsMatches(t *testing.T) {
"mytag": "foobar", "mytag": "foobar",
}, m.Tags()) }, m.Tags())
m, err = metric.New("m", m = metric.New("m",
map[string]string{ map[string]string{
"host": "localhost", "host": "localhost",
"mytag": "foobar", "mytag": "foobar",
}, },
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now()) time.Now())
require.NoError(t, err)
f = Filter{ f = Filter{
TagInclude: []string{"my*"}, TagInclude: []string{"my*"},
} }

View File

@ -23,17 +23,16 @@ func TestMakeMetricFilterAfterApplyingGlobalTags(t *testing.T) {
require.NoError(t, ri.Config.Filter.Compile()) require.NoError(t, ri.Config.Filter.Compile())
ri.SetDefaultTags(map[string]string{"a": "x", "b": "y"}) ri.SetDefaultTags(map[string]string{"a": "x", "b": "y"})
m, err := metric.New("cpu", m := metric.New("cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": 42, "value": 42,
}, },
now) now)
require.NoError(t, err)
actual := ri.MakeMetric(m) actual := ri.MakeMetric(m)
expected, err := metric.New("cpu", expected := metric.New("cpu",
map[string]string{ map[string]string{
"b": "y", "b": "y",
}, },
@ -41,7 +40,6 @@ func TestMakeMetricFilterAfterApplyingGlobalTags(t *testing.T) {
"value": 42, "value": 42,
}, },
now) now)
require.NoError(t, err)
testutil.RequireMetricEqual(t, expected, actual) testutil.RequireMetricEqual(t, expected, actual)
} }
@ -52,13 +50,12 @@ func TestMakeMetricNoFields(t *testing.T) {
Name: "TestRunningInput", Name: "TestRunningInput",
}) })
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{}, map[string]interface{}{},
now, now,
telegraf.Untyped) telegraf.Untyped)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
require.NoError(t, err)
assert.Nil(t, m) assert.Nil(t, m)
} }
@ -69,7 +66,7 @@ func TestMakeMetricNilFields(t *testing.T) {
Name: "TestRunningInput", Name: "TestRunningInput",
}) })
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(101), "value": int64(101),
@ -77,17 +74,15 @@ func TestMakeMetricNilFields(t *testing.T) {
}, },
now, now,
telegraf.Untyped) telegraf.Untyped)
require.NoError(t, err)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("RITest", expected := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int(101), "value": int(101),
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }
@ -110,7 +105,7 @@ func TestMakeMetricWithPluginTags(t *testing.T) {
telegraf.Untyped) telegraf.Untyped)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("RITest", expected := metric.New("RITest",
map[string]string{ map[string]string{
"foo": "bar", "foo": "bar",
}, },
@ -119,7 +114,6 @@ func TestMakeMetricWithPluginTags(t *testing.T) {
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }
@ -135,7 +129,7 @@ func TestMakeMetricFilteredOut(t *testing.T) {
assert.NoError(t, ri.Config.Filter.Compile()) assert.NoError(t, ri.Config.Filter.Compile())
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(101), "value": int64(101),
@ -143,7 +137,6 @@ func TestMakeMetricFilteredOut(t *testing.T) {
now, now,
telegraf.Untyped) telegraf.Untyped)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
require.NoError(t, err)
assert.Nil(t, m) assert.Nil(t, m)
} }
@ -164,7 +157,7 @@ func TestMakeMetricWithDaemonTags(t *testing.T) {
now, now,
telegraf.Untyped) telegraf.Untyped)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("RITest", expected := metric.New("RITest",
map[string]string{ map[string]string{
"foo": "bar", "foo": "bar",
}, },
@ -173,7 +166,6 @@ func TestMakeMetricWithDaemonTags(t *testing.T) {
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }
@ -184,23 +176,21 @@ func TestMakeMetricNameOverride(t *testing.T) {
NameOverride: "foobar", NameOverride: "foobar",
}) })
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(101), "value": int64(101),
}, },
now, now,
telegraf.Untyped) telegraf.Untyped)
require.NoError(t, err)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("foobar", expected := metric.New("foobar",
nil, nil,
map[string]interface{}{ map[string]interface{}{
"value": 101, "value": 101,
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }
@ -211,23 +201,21 @@ func TestMakeMetricNamePrefix(t *testing.T) {
MeasurementPrefix: "foobar_", MeasurementPrefix: "foobar_",
}) })
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(101), "value": int64(101),
}, },
now, now,
telegraf.Untyped) telegraf.Untyped)
require.NoError(t, err)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("foobar_RITest", expected := metric.New("foobar_RITest",
nil, nil,
map[string]interface{}{ map[string]interface{}{
"value": 101, "value": 101,
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }
@ -238,23 +226,21 @@ func TestMakeMetricNameSuffix(t *testing.T) {
MeasurementSuffix: "_foobar", MeasurementSuffix: "_foobar",
}) })
m, err := metric.New("RITest", m := metric.New("RITest",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(101), "value": int64(101),
}, },
now, now,
telegraf.Untyped) telegraf.Untyped)
require.NoError(t, err)
m = ri.MakeMetric(m) m = ri.MakeMetric(m)
expected, err := metric.New("RITest_foobar", expected := metric.New("RITest_foobar",
nil, nil,
map[string]interface{}{ map[string]interface{}{
"value": 101, "value": 101,
}, },
now, now,
) )
require.NoError(t, err)
require.Equal(t, expected, m) require.Equal(t, expected, m)
} }

View File

@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
var m1, _ = metric.New("m1", var m1 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),
@ -21,7 +21,7 @@ var m1, _ = metric.New("m1",
}, },
time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC), time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
) )
var m2, _ = metric.New("m1", var m2 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),
@ -326,28 +326,28 @@ func TestBasicStatsWithOnlySum(t *testing.T) {
// implementations of sum were calculated from mean and count, which // implementations of sum were calculated from mean and count, which
// e.g. summed "1, 1, 5, 1" as "7.999999..." instead of 8. // e.g. summed "1, 1, 5, 1" as "7.999999..." instead of 8.
func TestBasicStatsWithOnlySumFloatingPointErrata(t *testing.T) { func TestBasicStatsWithOnlySumFloatingPointErrata(t *testing.T) {
var sum1, _ = metric.New("m1", var sum1 = metric.New("m1",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),
}, },
time.Now(), time.Now(),
) )
var sum2, _ = metric.New("m1", var sum2 = metric.New("m1",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),
}, },
time.Now(), time.Now(),
) )
var sum3, _ = metric.New("m1", var sum3 = metric.New("m1",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"a": int64(5), "a": int64(5),
}, },
time.Now(), time.Now(),
) )
var sum4, _ = metric.New("m1", var sum4 = metric.New("m1",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),

View File

@ -8,7 +8,7 @@ import (
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
) )
var start, _ = metric.New("TestMetric", var start = metric.New("TestMetric",
map[string]string{"state": "full"}, map[string]string{"state": "full"},
map[string]interface{}{ map[string]interface{}{
"increasing": int64(0), "increasing": int64(0),
@ -20,7 +20,7 @@ var start, _ = metric.New("TestMetric",
time.Now(), time.Now(),
) )
var finish, _ = metric.New("TestMetric", var finish = metric.New("TestMetric",
map[string]string{"state": "full"}, map[string]string{"state": "full"},
map[string]interface{}{ map[string]interface{}{
"increasing": int64(1000), "increasing": int64(1000),
@ -94,14 +94,14 @@ func TestTwoFullEventsWithoutParameter(t *testing.T) {
duration, _ := time.ParseDuration("2s") duration, _ := time.ParseDuration("2s")
endTime := startTime.Add(duration) endTime := startTime.Add(duration)
first, _ := metric.New("One Field", first := metric.New("One Field",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(10), "value": int64(10),
}, },
startTime, startTime,
) )
last, _ := metric.New("One Field", last := metric.New("One Field",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(20), "value": int64(20),
@ -222,7 +222,7 @@ func TestIgnoresMissingVariable(t *testing.T) {
derivative.Log = testutil.Logger{} derivative.Log = testutil.Logger{}
derivative.Init() derivative.Init()
noParameter, _ := metric.New("TestMetric", noParameter := metric.New("TestMetric",
map[string]string{"state": "no_parameter"}, map[string]string{"state": "no_parameter"},
map[string]interface{}{ map[string]interface{}{
"increasing": int64(100), "increasing": int64(100),
@ -265,17 +265,17 @@ func TestMergesDifferenMetricsWithSameHash(t *testing.T) {
startTime := time.Now() startTime := time.Now()
duration, _ := time.ParseDuration("2s") duration, _ := time.ParseDuration("2s")
endTime := startTime.Add(duration) endTime := startTime.Add(duration)
part1, _ := metric.New("TestMetric", part1 := metric.New("TestMetric",
map[string]string{"state": "full"}, map[string]string{"state": "full"},
map[string]interface{}{"field1": int64(10)}, map[string]interface{}{"field1": int64(10)},
startTime, startTime,
) )
part2, _ := metric.New("TestMetric", part2 := metric.New("TestMetric",
map[string]string{"state": "full"}, map[string]string{"state": "full"},
map[string]interface{}{"field2": int64(20)}, map[string]interface{}{"field2": int64(20)},
startTime, startTime,
) )
final, _ := metric.New("TestMetric", final := metric.New("TestMetric",
map[string]string{"state": "full"}, map[string]string{"state": "full"},
map[string]interface{}{ map[string]interface{}{
"field1": int64(30), "field1": int64(30),
@ -359,7 +359,7 @@ func TestCalculatesCorrectDerivativeOnTwoConsecutivePeriods(t *testing.T) {
derivative.Init() derivative.Init()
startTime := time.Now() startTime := time.Now()
first, _ := metric.New("One Field", first := metric.New("One Field",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(10), "value": int64(10),
@ -370,7 +370,7 @@ func TestCalculatesCorrectDerivativeOnTwoConsecutivePeriods(t *testing.T) {
derivative.Push(&acc) derivative.Push(&acc)
derivative.Reset() derivative.Reset()
second, _ := metric.New("One Field", second := metric.New("One Field",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(20), "value": int64(20),
@ -386,7 +386,7 @@ func TestCalculatesCorrectDerivativeOnTwoConsecutivePeriods(t *testing.T) {
}) })
acc.ClearMetrics() acc.ClearMetrics()
third, _ := metric.New("One Field", third := metric.New("One Field",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": int64(40), "value": int64(40),

View File

@ -15,15 +15,15 @@ func TestSimple(t *testing.T) {
final := NewFinal() final := NewFinal()
tags := map[string]string{"foo": "bar"} tags := map[string]string{"foo": "bar"}
m1, _ := metric.New("m1", m1 := metric.New("m1",
tags, tags,
map[string]interface{}{"a": int64(1)}, map[string]interface{}{"a": int64(1)},
time.Unix(1530939936, 0)) time.Unix(1530939936, 0))
m2, _ := metric.New("m1", m2 := metric.New("m1",
tags, tags,
map[string]interface{}{"a": int64(2)}, map[string]interface{}{"a": int64(2)},
time.Unix(1530939937, 0)) time.Unix(1530939937, 0))
m3, _ := metric.New("m1", m3 := metric.New("m1",
tags, tags,
map[string]interface{}{"a": int64(3)}, map[string]interface{}{"a": int64(3)},
time.Unix(1530939938, 0)) time.Unix(1530939938, 0))
@ -52,15 +52,15 @@ func TestTwoTags(t *testing.T) {
tags1 := map[string]string{"foo": "bar"} tags1 := map[string]string{"foo": "bar"}
tags2 := map[string]string{"foo": "baz"} tags2 := map[string]string{"foo": "baz"}
m1, _ := metric.New("m1", m1 := metric.New("m1",
tags1, tags1,
map[string]interface{}{"a": int64(1)}, map[string]interface{}{"a": int64(1)},
time.Unix(1530939936, 0)) time.Unix(1530939936, 0))
m2, _ := metric.New("m1", m2 := metric.New("m1",
tags2, tags2,
map[string]interface{}{"a": int64(2)}, map[string]interface{}{"a": int64(2)},
time.Unix(1530939937, 0)) time.Unix(1530939937, 0))
m3, _ := metric.New("m1", m3 := metric.New("m1",
tags1, tags1,
map[string]interface{}{"a": int64(3)}, map[string]interface{}{"a": int64(3)},
time.Unix(1530939938, 0)) time.Unix(1530939938, 0))
@ -98,19 +98,19 @@ func TestLongDifference(t *testing.T) {
now := time.Now() now := time.Now()
m1, _ := metric.New("m", m1 := metric.New("m",
tags, tags,
map[string]interface{}{"a": int64(1)}, map[string]interface{}{"a": int64(1)},
now.Add(time.Second*-290)) now.Add(time.Second*-290))
m2, _ := metric.New("m", m2 := metric.New("m",
tags, tags,
map[string]interface{}{"a": int64(2)}, map[string]interface{}{"a": int64(2)},
now.Add(time.Second*-275)) now.Add(time.Second*-275))
m3, _ := metric.New("m", m3 := metric.New("m",
tags, tags,
map[string]interface{}{"a": int64(3)}, map[string]interface{}{"a": int64(3)},
now.Add(time.Second*-100)) now.Add(time.Second*-100))
m4, _ := metric.New("m", m4 := metric.New("m",
tags, tags,
map[string]interface{}{"a": int64(4)}, map[string]interface{}{"a": int64(4)},
now.Add(time.Second*-20)) now.Add(time.Second*-20))

View File

@ -25,7 +25,7 @@ func NewTestHistogram(cfg []config, reset bool, cumulative bool) telegraf.Aggreg
} }
// firstMetric1 is the first test metric // firstMetric1 is the first test metric
var firstMetric1, _ = metric.New( var firstMetric1 = metric.New(
"first_metric_name", "first_metric_name",
tags{}, tags{},
fields{ fields{
@ -36,7 +36,7 @@ var firstMetric1, _ = metric.New(
) )
// firstMetric1 is the first test metric with other value // firstMetric1 is the first test metric with other value
var firstMetric2, _ = metric.New( var firstMetric2 = metric.New(
"first_metric_name", "first_metric_name",
tags{}, tags{},
fields{ fields{
@ -47,7 +47,7 @@ var firstMetric2, _ = metric.New(
) )
// secondMetric is the second metric // secondMetric is the second metric
var secondMetric, _ = metric.New( var secondMetric = metric.New(
"second_metric_name", "second_metric_name",
tags{}, tags{},
fields{ fields{

View File

@ -187,7 +187,7 @@ func TestReset(t *testing.T) {
testutil.RequireMetricsEqual(t, expected, acc.GetTelegrafMetrics()) testutil.RequireMetricsEqual(t, expected, acc.GetTelegrafMetrics())
} }
var m1, _ = metric.New( var m1 = metric.New(
"mymetric", "mymetric",
map[string]string{ map[string]string{
"host": "host.example.com", "host": "host.example.com",
@ -206,7 +206,7 @@ var m1, _ = metric.New(
}, },
time.Now(), time.Now(),
) )
var m2, _ = metric.New( var m2 = metric.New(
"mymetric", "mymetric",
map[string]string{ map[string]string{
"host": "host.example.com", "host": "host.example.com",

View File

@ -8,7 +8,7 @@ import (
"github.com/influxdata/telegraf/testutil" "github.com/influxdata/telegraf/testutil"
) )
var m1, _ = metric.New("m1", var m1 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),
@ -24,7 +24,7 @@ var m1, _ = metric.New("m1",
}, },
time.Now(), time.Now(),
) )
var m2, _ = metric.New("m1", var m2 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"a": int64(1), "a": int64(1),

View File

@ -19,7 +19,7 @@ func NewTestValueCounter(fields []string) telegraf.Aggregator {
return vc return vc
} }
var m1, _ = metric.New("m1", var m1 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"status": 200, "status": 200,
@ -28,7 +28,7 @@ var m1, _ = metric.New("m1",
time.Now(), time.Now(),
) )
var m2, _ = metric.New("m1", var m2 = metric.New("m1",
map[string]string{"foo": "bar"}, map[string]string{"foo": "bar"},
map[string]interface{}{ map[string]interface{}{
"status": "OK", "status": "OK",

View File

@ -18,14 +18,13 @@ func TestOrderedJobsStayOrdered(t *testing.T) {
p := parallel.NewOrdered(acc, jobFunc, 10000, 10) p := parallel.NewOrdered(acc, jobFunc, 10000, 10)
now := time.Now() now := time.Now()
for i := 0; i < 20000; i++ { for i := 0; i < 20000; i++ {
m, err := metric.New("test", m := metric.New("test",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"val": i, "val": i,
}, },
now, now,
) )
require.NoError(t, err)
now = now.Add(1) now = now.Add(1)
p.Enqueue(m) p.Enqueue(m)
} }
@ -51,14 +50,13 @@ func TestUnorderedJobsDontDropAnyJobs(t *testing.T) {
expectedTotal := 0 expectedTotal := 0
for i := 0; i < 20000; i++ { for i := 0; i < 20000; i++ {
expectedTotal += i expectedTotal += i
m, err := metric.New("test", m := metric.New("test",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"val": i, "val": i,
}, },
now, now,
) )
require.NoError(t, err)
now = now.Add(1) now = now.Add(1)
p.Enqueue(m) p.Enqueue(m)
} }
@ -79,7 +77,7 @@ func BenchmarkOrdered(b *testing.B) {
p := parallel.NewOrdered(acc, jobFunc, 10000, 10) p := parallel.NewOrdered(acc, jobFunc, 10000, 10)
m, _ := metric.New("test", m := metric.New("test",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"val": 1, "val": 1,
@ -99,7 +97,7 @@ func BenchmarkUnordered(b *testing.B) {
p := parallel.NewUnordered(acc, jobFunc, 10) p := parallel.NewUnordered(acc, jobFunc, 10)
m, _ := metric.New("test", m := metric.New("test",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"val": 1, "val": 1,

View File

@ -34,7 +34,7 @@ func TestOutputShim(t *testing.T) {
serializer, _ := serializers.NewInfluxSerializer() serializer, _ := serializers.NewInfluxSerializer()
m, _ := metric.New("thing", m := metric.New("thing",
map[string]string{ map[string]string{
"a": "b", "a": "b",
}, },

View File

@ -40,7 +40,7 @@ func TestProcessorShim(t *testing.T) {
serializer, _ := serializers.NewInfluxSerializer() serializer, _ := serializers.NewInfluxSerializer()
parser, _ := parsers.NewInfluxParser() parser, _ := parsers.NewInfluxParser()
m, _ := metric.New("thing", m := metric.New("thing",
map[string]string{ map[string]string{
"a": "b", "a": "b",
}, },

View File

@ -170,7 +170,7 @@ func runCounterProgram() {
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() { for scanner.Scan() {
metric, _ := metric.New("counter", m := metric.New("counter",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"count": i, "count": i,
@ -179,7 +179,7 @@ func runCounterProgram() {
) )
i++ i++
b, err := serializer.Serialize(metric) b, err := serializer.Serialize(m)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "ERR %v\n", err) fmt.Fprintf(os.Stderr, "ERR %v\n", err)
os.Exit(1) os.Exit(1)

View File

@ -81,10 +81,8 @@ func Parse(buf []byte, header http.Header) ([]telegraf.Metric, error) {
} else { } else {
t = now t = now
} }
metric, err := metric.New(metricName, tags, fields, t, common.ValueType(mf.GetType())) m := metric.New(metricName, tags, fields, t, common.ValueType(mf.GetType()))
if err == nil { metrics = append(metrics, m)
metrics = append(metrics, metric)
}
} }
} }
} }

View File

@ -221,13 +221,7 @@ func (rsl *riemannListener) read(conn net.Conn) {
tags["State"] = m.State tags["State"] = m.State
fieldValues["Metric"] = m.Metric fieldValues["Metric"] = m.Metric
fieldValues["TTL"] = m.TTL.Seconds() fieldValues["TTL"] = m.TTL.Seconds()
singleMetric, err := metric.New(m.Service, tags, fieldValues, m.Time, telegraf.Untyped) singleMetric := metric.New(m.Service, tags, fieldValues, m.Time, telegraf.Untyped)
if err != nil {
rsl.Log.Debugf("Could not create metric for service %s at %s", m.Service, m.Time.String())
riemannReturnErrorResponse(conn, "Could not create metric")
return
}
rsl.AddMetric(singleMetric) rsl.AddMetric(singleMetric)
} }
riemannReturnResponse(conn) riemannReturnResponse(conn)

View File

@ -34,10 +34,7 @@ func makeMetrics(p *V5Format) ([]telegraf.Metric, error) {
for k, v := range fields { for k, v := range fields {
fields2[k] = v fields2[k] = v
} }
m, err := metric.New("sflow", tags2, fields2, now) m := metric.New("sflow", tags2, fields2, now)
if err != nil {
return nil, err
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }
} }

View File

@ -106,7 +106,7 @@ func (s CommitCommentEvent) NewMetric() telegraf.Metric {
"commit": s.Comment.Commit, "commit": s.Comment.Commit,
"comment": s.Comment.Body, "comment": s.Comment.Body,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -133,7 +133,7 @@ func (s CreateEvent) NewMetric() telegraf.Metric {
"ref": s.Ref, "ref": s.Ref,
"refType": s.RefType, "refType": s.RefType,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -160,7 +160,7 @@ func (s DeleteEvent) NewMetric() telegraf.Metric {
"ref": s.Ref, "ref": s.Ref,
"refType": s.RefType, "refType": s.RefType,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -188,7 +188,7 @@ func (s DeploymentEvent) NewMetric() telegraf.Metric {
"environment": s.Deployment.Environment, "environment": s.Deployment.Environment,
"description": s.Deployment.Description, "description": s.Deployment.Description,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -219,7 +219,7 @@ func (s DeploymentStatusEvent) NewMetric() telegraf.Metric {
"depState": s.DeploymentStatus.State, "depState": s.DeploymentStatus.State,
"depDescription": s.DeploymentStatus.Description, "depDescription": s.DeploymentStatus.Description,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -244,7 +244,7 @@ func (s ForkEvent) NewMetric() telegraf.Metric {
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
"fork": s.Forkee.Repository, "fork": s.Forkee.Repository,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -269,7 +269,7 @@ func (s GollumEvent) NewMetric() telegraf.Metric {
"forks": s.Repository.Forks, "forks": s.Repository.Forks,
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -298,7 +298,7 @@ func (s IssueCommentEvent) NewMetric() telegraf.Metric {
"comments": s.Issue.Comments, "comments": s.Issue.Comments,
"body": s.Comment.Body, "body": s.Comment.Body,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -327,7 +327,7 @@ func (s IssuesEvent) NewMetric() telegraf.Metric {
"title": s.Issue.Title, "title": s.Issue.Title,
"comments": s.Issue.Comments, "comments": s.Issue.Comments,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -353,7 +353,7 @@ func (s MemberEvent) NewMetric() telegraf.Metric {
"newMember": s.Member.User, "newMember": s.Member.User,
"newMemberStatus": s.Member.Admin, "newMemberStatus": s.Member.Admin,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -376,7 +376,7 @@ func (s MembershipEvent) NewMetric() telegraf.Metric {
"newMember": s.Member.User, "newMember": s.Member.User,
"newMemberStatus": s.Member.Admin, "newMemberStatus": s.Member.Admin,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -399,7 +399,7 @@ func (s PageBuildEvent) NewMetric() telegraf.Metric {
"forks": s.Repository.Forks, "forks": s.Repository.Forks,
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -422,7 +422,7 @@ func (s PublicEvent) NewMetric() telegraf.Metric {
"forks": s.Repository.Forks, "forks": s.Repository.Forks,
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -456,7 +456,7 @@ func (s PullRequestEvent) NewMetric() telegraf.Metric {
"deletions": s.PullRequest.Deletions, "deletions": s.PullRequest.Deletions,
"changedFiles": s.PullRequest.ChangedFiles, "changedFiles": s.PullRequest.ChangedFiles,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -491,7 +491,7 @@ func (s PullRequestReviewCommentEvent) NewMetric() telegraf.Metric {
"commentFile": s.Comment.File, "commentFile": s.Comment.File,
"comment": s.Comment.Comment, "comment": s.Comment.Comment,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -520,7 +520,7 @@ func (s PushEvent) NewMetric() telegraf.Metric {
"before": s.Before, "before": s.Before,
"after": s.After, "after": s.After,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -545,7 +545,7 @@ func (s ReleaseEvent) NewMetric() telegraf.Metric {
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
"tagName": s.Release.TagName, "tagName": s.Release.TagName,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -568,7 +568,7 @@ func (s RepositoryEvent) NewMetric() telegraf.Metric {
"forks": s.Repository.Forks, "forks": s.Repository.Forks,
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -595,7 +595,7 @@ func (s StatusEvent) NewMetric() telegraf.Metric {
"commit": s.Commit, "commit": s.Commit,
"state": s.State, "state": s.State,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -620,7 +620,7 @@ func (s TeamAddEvent) NewMetric() telegraf.Metric {
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
"teamName": s.Team.Name, "teamName": s.Team.Name,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }
@ -643,6 +643,6 @@ func (s WatchEvent) NewMetric() telegraf.Metric {
"forks": s.Repository.Forks, "forks": s.Repository.Forks,
"issues": s.Repository.Issues, "issues": s.Repository.Issues,
} }
m, _ := metric.New(meas, t, f, time.Now()) m := metric.New(meas, t, f, time.Now())
return m return m
} }

View File

@ -1,11 +1,12 @@
package application_insights package application_insights
import ( import (
"github.com/influxdata/telegraf/testutil"
"math" "math"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf/testutil"
"github.com/Microsoft/ApplicationInsights-Go/appinsights" "github.com/Microsoft/ApplicationInsights-Go/appinsights"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
@ -143,13 +144,12 @@ func TestAggregateMetricCreated(t *testing.T) {
transmitter.On("Track", mock.Anything) transmitter.On("Track", mock.Anything)
metricName := "ShouldBeAggregateMetric" metricName := "ShouldBeAggregateMetric"
m, err := metric.New( m := metric.New(
metricName, metricName,
nil, // tags nil, // tags
tt.fields, tt.fields,
now, now,
) )
assert.NoError(err)
ai := ApplicationInsights{ ai := ApplicationInsights{
transmitter: transmitter, transmitter: transmitter,
@ -157,7 +157,7 @@ func TestAggregateMetricCreated(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
err = ai.Connect() err := ai.Connect()
assert.NoError(err) assert.NoError(err)
mSet := []telegraf.Metric{m} mSet := []telegraf.Metric{m}
@ -202,13 +202,12 @@ func TestSimpleMetricCreated(t *testing.T) {
transmitter.On("Track", mock.Anything) transmitter.On("Track", mock.Anything)
metricName := "ShouldBeSimpleMetric" metricName := "ShouldBeSimpleMetric"
m, err := metric.New( m := metric.New(
metricName, metricName,
nil, // tags nil, // tags
tt.fields, tt.fields,
now, now,
) )
assert.NoError(err)
ai := ApplicationInsights{ ai := ApplicationInsights{
transmitter: transmitter, transmitter: transmitter,
@ -216,7 +215,7 @@ func TestSimpleMetricCreated(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
err = ai.Connect() err := ai.Connect()
assert.NoError(err) assert.NoError(err)
mSet := []telegraf.Metric{m} mSet := []telegraf.Metric{m}
@ -273,13 +272,12 @@ func TestTagsAppliedToTelemetry(t *testing.T) {
transmitter.On("Track", mock.Anything) transmitter.On("Track", mock.Anything)
metricName := "ShouldBeSimpleMetric" metricName := "ShouldBeSimpleMetric"
m, err := metric.New( m := metric.New(
metricName, metricName,
tt.tags, tt.tags,
tt.fields, tt.fields,
now, now,
) )
assert.NoError(err)
ai := ApplicationInsights{ ai := ApplicationInsights{
transmitter: transmitter, transmitter: transmitter,
@ -287,7 +285,7 @@ func TestTagsAppliedToTelemetry(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
err = ai.Connect() err := ai.Connect()
assert.NoError(err) assert.NoError(err)
mSet := []telegraf.Metric{m} mSet := []telegraf.Metric{m}
@ -310,13 +308,12 @@ func TestContextTagsSetOnSimpleTelemetry(t *testing.T) {
transmitter := new(mocks.Transmitter) transmitter := new(mocks.Transmitter)
transmitter.On("Track", mock.Anything) transmitter.On("Track", mock.Anything)
m, err := metric.New( m := metric.New(
"SimpleMetric", "SimpleMetric",
map[string]string{"kubernetes_container_name": "atcsvc", "kubernetes_pod_name": "bunkie17554"}, map[string]string{"kubernetes_container_name": "atcsvc", "kubernetes_pod_name": "bunkie17554"},
map[string]interface{}{"value": 23.0}, map[string]interface{}{"value": 23.0},
now, now,
) )
assert.NoError(err)
ai := ApplicationInsights{ ai := ApplicationInsights{
transmitter: transmitter, transmitter: transmitter,
@ -329,7 +326,7 @@ func TestContextTagsSetOnSimpleTelemetry(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
err = ai.Connect() err := ai.Connect()
assert.NoError(err) assert.NoError(err)
mSet := []telegraf.Metric{m} mSet := []telegraf.Metric{m}
@ -348,13 +345,12 @@ func TestContextTagsSetOnAggregateTelemetry(t *testing.T) {
transmitter := new(mocks.Transmitter) transmitter := new(mocks.Transmitter)
transmitter.On("Track", mock.Anything) transmitter.On("Track", mock.Anything)
m, err := metric.New( m := metric.New(
"AggregateMetric", "AggregateMetric",
map[string]string{"kubernetes_container_name": "atcsvc", "kubernetes_pod_name": "bunkie17554"}, map[string]string{"kubernetes_container_name": "atcsvc", "kubernetes_pod_name": "bunkie17554"},
map[string]interface{}{"value": 23.0, "count": 5}, map[string]interface{}{"value": 23.0, "count": 5},
now, now,
) )
assert.NoError(err)
ai := ApplicationInsights{ ai := ApplicationInsights{
transmitter: transmitter, transmitter: transmitter,
@ -367,7 +363,7 @@ func TestContextTagsSetOnAggregateTelemetry(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
err = ai.Connect() err := ai.Connect()
assert.NoError(err) assert.NoError(err)
mSet := []telegraf.Metric{m} mSet := []telegraf.Metric{m}

View File

@ -599,7 +599,7 @@ func (a *AzureMonitor) Push() []telegraf.Metric {
tags[tag.name] = tag.value tags[tag.name] = tag.value
} }
m, err := metric.New(agg.name, m := metric.New(agg.name,
tags, tags,
map[string]interface{}{ map[string]interface{}{
"min": agg.min, "min": agg.min,
@ -610,10 +610,6 @@ func (a *AzureMonitor) Push() []telegraf.Metric {
tbucket, tbucket,
) )
if err != nil {
a.Log.Errorf("Could not create metric for aggregation %q; discarding point", agg.name)
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }
} }

View File

@ -83,7 +83,7 @@ func TestBuildMetricDatums(t *testing.T) {
assert.Equal(0, len(datums), fmt.Sprintf("Valid point should not create a Datum {value: %v}", point)) assert.Equal(0, len(datums), fmt.Sprintf("Valid point should not create a Datum {value: %v}", point))
} }
statisticMetric, _ := metric.New( statisticMetric := metric.New(
"test1", "test1",
map[string]string{"tag1": "value1"}, map[string]string{"tag1": "value1"},
map[string]interface{}{"value_max": float64(10), "value_min": float64(0), "value_sum": float64(100), "value_count": float64(20)}, map[string]interface{}{"value_max": float64(10), "value_min": float64(0), "value_sum": float64(100), "value_count": float64(20)},
@ -92,7 +92,7 @@ func TestBuildMetricDatums(t *testing.T) {
datums := BuildMetricDatum(true, false, statisticMetric) datums := BuildMetricDatum(true, false, statisticMetric)
assert.Equal(1, len(datums), fmt.Sprintf("Valid point should create a Datum {value: %v}", statisticMetric)) assert.Equal(1, len(datums), fmt.Sprintf("Valid point should create a Datum {value: %v}", statisticMetric))
multiFieldsMetric, _ := metric.New( multiFieldsMetric := metric.New(
"test1", "test1",
map[string]string{"tag1": "value1"}, map[string]string{"tag1": "value1"},
map[string]interface{}{"valueA": float64(10), "valueB": float64(0), "valueC": float64(100), "valueD": float64(20)}, map[string]interface{}{"valueA": float64(10), "valueB": float64(0), "valueC": float64(100), "valueD": float64(20)},
@ -101,7 +101,7 @@ func TestBuildMetricDatums(t *testing.T) {
datums = BuildMetricDatum(true, false, multiFieldsMetric) datums = BuildMetricDatum(true, false, multiFieldsMetric)
assert.Equal(4, len(datums), fmt.Sprintf("Each field should create a Datum {value: %v}", multiFieldsMetric)) assert.Equal(4, len(datums), fmt.Sprintf("Each field should create a Datum {value: %v}", multiFieldsMetric))
multiStatisticMetric, _ := metric.New( multiStatisticMetric := metric.New(
"test1", "test1",
map[string]string{"tag1": "value1"}, map[string]string{"tag1": "value1"},
map[string]interface{}{ map[string]interface{}{

View File

@ -203,13 +203,12 @@ func Test_hashID(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
m, err := metric.New( m := metric.New(
test.Name, test.Name,
test.Tags, test.Tags,
test.Fields, test.Fields,
time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
require.NoError(t, err)
if got := hashID(m); got != test.Want { if got := hashID(m); got != test.Want {
t.Errorf("test #%d: got=%d want=%d", i, got, test.Want) t.Errorf("test #%d: got=%d want=%d", i, got, test.Want)
} }

View File

@ -2,16 +2,17 @@ package dynatrace
import ( import (
"encoding/json" "encoding/json"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/config"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
func TestNilMetrics(t *testing.T) { func TestNilMetrics(t *testing.T) {
@ -142,14 +143,14 @@ func TestSendMetric(t *testing.T) {
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1", "nix": "nix"}, map[string]string{"host": "192.168.0.1", "nix": "nix"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -191,7 +192,7 @@ func TestSendSingleMetricWithUnorderedTags(t *testing.T) {
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"a": "test", "c": "test", "b": "test"}, map[string]string{"a": "test", "c": "test", "b": "test"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
@ -233,7 +234,7 @@ func TestSendMetricWithoutTags(t *testing.T) {
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{}, map[string]string{},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
@ -275,7 +276,7 @@ func TestSendMetricWithUpperCaseTagKeys(t *testing.T) {
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"AAA": "test", "CcC": "test", "B B": "test"}, map[string]string{"AAA": "test", "CcC": "test", "B B": "test"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
@ -317,7 +318,7 @@ func TestSendBooleanMetricWithoutTags(t *testing.T) {
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{}, map[string]string{},
map[string]interface{}{"myfield": bool(true)}, map[string]interface{}{"myfield": bool(true)},

View File

@ -55,13 +55,12 @@ func TestExternalOutputWorks(t *testing.T) {
wg.Done() wg.Done()
} }
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{"name": "cpu1"}, map[string]string{"name": "cpu1"},
map[string]interface{}{"idle": 50, "sys": 30}, map[string]interface{}{"idle": 50, "sys": 30},
now, now,
) )
require.NoError(t, err)
require.NoError(t, e.Connect()) require.NoError(t, e.Connect())
require.NoError(t, e.Write([]telegraf.Metric{m})) require.NoError(t, e.Write([]telegraf.Metric{m}))

View File

@ -2,13 +2,14 @@ package graphite
import ( import (
"bufio" "bufio"
"github.com/influxdata/telegraf/testutil"
"net" "net"
"net/textproto" "net/textproto"
"sync" "sync"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf/testutil"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
@ -24,7 +25,7 @@ func TestGraphiteError(t *testing.T) {
Log: testutil.Logger{}, Log: testutil.Logger{},
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"mymeasurement": float64(3.14)}, map[string]interface{}{"mymeasurement": float64(3.14)},
@ -56,19 +57,19 @@ func TestGraphiteOK(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -118,19 +119,19 @@ func TestGraphiteOkWithSeparatorDot(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -180,19 +181,19 @@ func TestGraphiteOkWithSeparatorUnderscore(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -246,19 +247,19 @@ func TestGraphiteOKWithMultipleTemplates(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1", "mytag": "valuetag"}, map[string]string{"host": "192.168.0.1", "mytag": "valuetag"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1", "mytag": "valuetag"}, map[string]string{"host": "192.168.0.1", "mytag": "valuetag"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1", "mytag": "valuetag"}, map[string]string{"host": "192.168.0.1", "mytag": "valuetag"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -308,19 +309,19 @@ func TestGraphiteOkWithTags(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -371,19 +372,19 @@ func TestGraphiteOkWithTagsAndSeparatorDot(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -434,19 +435,19 @@ func TestGraphiteOkWithTagsAndSeparatorUnderscore(t *testing.T) {
} }
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"my_measurement", "my_measurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},

View File

@ -18,7 +18,7 @@ import (
) )
func getMetric() telegraf.Metric { func getMetric() telegraf.Metric {
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -26,9 +26,7 @@ func getMetric() telegraf.Metric {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
if err != nil {
panic(err)
}
return m return m
} }

View File

@ -490,7 +490,7 @@ func TestHTTP_Write(t *testing.T) {
ctx := context.Background() ctx := context.Background()
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -498,7 +498,6 @@ func TestHTTP_Write(t *testing.T) {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
require.NoError(t, err)
metrics := []telegraf.Metric{m} metrics := []telegraf.Metric{m}
client, err := influxdb.NewHTTPClient(tt.config) client, err := influxdb.NewHTTPClient(tt.config)
@ -541,7 +540,7 @@ func TestHTTP_WritePathPrefix(t *testing.T) {
ctx := context.Background() ctx := context.Background()
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -549,7 +548,6 @@ func TestHTTP_WritePathPrefix(t *testing.T) {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
require.NoError(t, err)
metrics := []telegraf.Metric{m} metrics := []telegraf.Metric{m}
config := influxdb.HTTPConfig{ config := influxdb.HTTPConfig{
@ -595,7 +593,7 @@ func TestHTTP_WriteContentEncodingGzip(t *testing.T) {
ctx := context.Background() ctx := context.Background()
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{

View File

@ -200,7 +200,7 @@ func TestWriteRecreateDatabaseIfDatabaseNotFound(t *testing.T) {
err := output.Connect() err := output.Connect()
require.NoError(t, err) require.NoError(t, err)
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -208,7 +208,6 @@ func TestWriteRecreateDatabaseIfDatabaseNotFound(t *testing.T) {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
require.NoError(t, err)
metrics := []telegraf.Metric{m} metrics := []telegraf.Metric{m}
err = output.Write(metrics) err = output.Write(metrics)

View File

@ -23,7 +23,7 @@ var (
) )
func getMetric() telegraf.Metric { func getMetric() telegraf.Metric {
metric, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -31,10 +31,8 @@ func getMetric() telegraf.Metric {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
if err != nil {
panic(err) return m
}
return metric
} }
func getURL() *url.URL { func getURL() *url.URL {
@ -202,7 +200,7 @@ func TestUDP_ErrorLogging(t *testing.T) {
}, },
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
func() telegraf.Metric { func() telegraf.Metric {
metric, _ := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{ map[string]string{
"host": "example.org", "host": "example.org",
@ -210,7 +208,7 @@ func TestUDP_ErrorLogging(t *testing.T) {
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0), time.Unix(0, 0),
) )
return metric return m
}(), }(),
}, },
logContains: `could not serialize metric: "cpu,host=example.org": no serializable fields`, logContains: `could not serialize metric: "cpu,host=example.org": no serializable fields`,

View File

@ -25,13 +25,13 @@ func TestWrite(t *testing.T) {
} }
// Default to gauge // Default to gauge
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"myfield": float64(3.14)}, map[string]interface{}{"myfield": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1", "metric_type": "set"}, map[string]string{"host": "192.168.0.1", "metric_type": "set"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -42,27 +42,27 @@ func TestWrite(t *testing.T) {
i.Write(metrics) i.Write(metrics)
// Counter and Histogram are increments // Counter and Histogram are increments
m3, _ := metric.New( m3 := metric.New(
"my_histogram", "my_histogram",
map[string]string{"host": "192.168.0.1", "metric_type": "histogram"}, map[string]string{"host": "192.168.0.1", "metric_type": "histogram"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
// We will modify metric names that won't be accepted by Instrumental // We will modify metric names that won't be accepted by Instrumental
m4, _ := metric.New( m4 := metric.New(
"bad_metric_name", "bad_metric_name",
map[string]string{"host": "192.168.0.1:8888::123", "metric_type": "counter"}, map[string]string{"host": "192.168.0.1:8888::123", "metric_type": "counter"},
map[string]interface{}{"value": 1}, map[string]interface{}{"value": 1},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
// We will drop metric values that won't be accepted by Instrumental // We will drop metric values that won't be accepted by Instrumental
m5, _ := metric.New( m5 := metric.New(
"bad_values", "bad_values",
map[string]string{"host": "192.168.0.1", "metric_type": "counter"}, map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
map[string]interface{}{"value": "\" 3:30\""}, map[string]interface{}{"value": "\" 3:30\""},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m6, _ := metric.New( m6 := metric.New(
"my_counter", "my_counter",
map[string]string{"host": "192.168.0.1", "metric_type": "counter"}, map[string]string{"host": "192.168.0.1", "metric_type": "counter"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},

View File

@ -117,7 +117,7 @@ func TestRoutingKey(t *testing.T) {
RoutingKey: "static", RoutingKey: "static",
}, },
metric: func() telegraf.Metric { metric: func() telegraf.Metric {
m, _ := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -137,7 +137,7 @@ func TestRoutingKey(t *testing.T) {
RoutingKey: "random", RoutingKey: "random",
}, },
metric: func() telegraf.Metric { metric: func() telegraf.Metric {
m, _ := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{

View File

@ -161,7 +161,7 @@ func TestBuildGauge(t *testing.T) {
} }
func newHostMetric(value interface{}, name, host string) telegraf.Metric { func newHostMetric(value interface{}, name, host string) telegraf.Metric {
m, _ := metric.New( m := metric.New(
name, name,
map[string]string{"host": host}, map[string]string{"host": host},
map[string]interface{}{"value": value}, map[string]interface{}{"value": value},
@ -172,19 +172,19 @@ func newHostMetric(value interface{}, name, host string) telegraf.Metric {
func TestBuildGaugeWithSource(t *testing.T) { func TestBuildGaugeWithSource(t *testing.T) {
mtime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC) mtime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
pt1, _ := metric.New( pt1 := metric.New(
"test1", "test1",
map[string]string{"hostname": "192.168.0.1", "tag1": "value1"}, map[string]string{"hostname": "192.168.0.1", "tag1": "value1"},
map[string]interface{}{"value": 0.0}, map[string]interface{}{"value": 0.0},
mtime, mtime,
) )
pt2, _ := metric.New( pt2 := metric.New(
"test2", "test2",
map[string]string{"hostnam": "192.168.0.1", "tag1": "value1"}, map[string]string{"hostnam": "192.168.0.1", "tag1": "value1"},
map[string]interface{}{"value": 1.0}, map[string]interface{}{"value": 1.0},
mtime, mtime,
) )
pt3, _ := metric.New( pt3 := metric.New(
"test3", "test3",
map[string]string{ map[string]string{
"hostname": "192.168.0.1", "hostname": "192.168.0.1",
@ -193,7 +193,7 @@ func TestBuildGaugeWithSource(t *testing.T) {
map[string]interface{}{"value": 1.0}, map[string]interface{}{"value": 1.0},
mtime, mtime,
) )
pt4, _ := metric.New( pt4 := metric.New(
"test4", "test4",
map[string]string{ map[string]string{
"hostname": "192.168.0.1", "hostname": "192.168.0.1",

View File

@ -1,10 +1,11 @@
package riemann package riemann
import ( import (
"github.com/influxdata/telegraf/testutil"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf/testutil"
"github.com/amir/raidman" "github.com/amir/raidman"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -76,7 +77,7 @@ func TestMetricEvents(t *testing.T) {
} }
// build a single event // build a single event
m, _ := metric.New( m := metric.New(
"test1", "test1",
map[string]string{"tag1": "value1", "host": "abc123"}, map[string]string{"tag1": "value1", "host": "abc123"},
map[string]interface{}{"value": 5.6}, map[string]interface{}{"value": 5.6},
@ -101,7 +102,7 @@ func TestMetricEvents(t *testing.T) {
require.Equal(t, expectedEvent, events[0]) require.Equal(t, expectedEvent, events[0])
// build 2 events // build 2 events
m, _ = metric.New( m = metric.New(
"test2", "test2",
map[string]string{"host": "xyz987"}, map[string]string{"host": "xyz987"},
map[string]interface{}{"point": 1}, map[string]interface{}{"point": 1},
@ -136,7 +137,7 @@ func TestStateEvents(t *testing.T) {
} }
// string metrics will be skipped unless explicitly enabled // string metrics will be skipped unless explicitly enabled
m, _ := metric.New( m := metric.New(
"test", "test",
map[string]string{"host": "host"}, map[string]string{"host": "host"},
map[string]interface{}{"value": "running"}, map[string]interface{}{"value": "running"},

View File

@ -429,12 +429,10 @@ func TestSignalFx_SignalFx(t *testing.T) {
measurements := []telegraf.Metric{} measurements := []telegraf.Metric{}
for _, measurement := range tt.measurements { for _, measurement := range tt.measurements {
m, err := metric.New( m := metric.New(
measurement.name, measurement.tags, measurement.fields, measurement.time, measurement.tp, measurement.name, measurement.tags, measurement.fields, measurement.time, measurement.tp,
) )
if err != nil {
t.Errorf("Error creating measurement %v", measurement)
}
measurements = append(measurements, m) measurements = append(measurements, m)
} }
@ -594,12 +592,10 @@ func TestSignalFx_Errors(t *testing.T) {
} }
for _, measurement := range tt.measurements { for _, measurement := range tt.measurements {
m, err := metric.New( m := metric.New(
measurement.name, measurement.tags, measurement.fields, measurement.time, measurement.tp, measurement.name, measurement.tags, measurement.fields, measurement.time, measurement.tp,
) )
if err != nil {
t.Errorf("Error creating measurement %v", measurement)
}
s.Write([]telegraf.Metric{m}) s.Write([]telegraf.Metric{m})
} }
for !(len(s.client.(*errorsink).dps) == len(tt.want.datapoints) && len(s.client.(*errorsink).evs) == len(tt.want.events)) { for !(len(s.client.(*errorsink).dps) == len(tt.want.datapoints) && len(s.client.(*errorsink).evs) == len(tt.want.events)) {

View File

@ -27,7 +27,7 @@ import (
) )
func getMetric(t *testing.T) telegraf.Metric { func getMetric(t *testing.T) telegraf.Metric {
m, err := metric.New( m := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
@ -35,7 +35,6 @@ func getMetric(t *testing.T) telegraf.Metric {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
require.NoError(t, err)
return m return m
} }
@ -44,7 +43,7 @@ func getMetrics(t *testing.T) []telegraf.Metric {
var metrics = make([]telegraf.Metric, count) var metrics = make([]telegraf.Metric, count)
for i := 0; i < count; i++ { for i := 0; i < count; i++ {
m, err := metric.New( m := metric.New(
fmt.Sprintf("cpu-%d", i), fmt.Sprintf("cpu-%d", i),
map[string]string{ map[string]string{
"ec2_instance": "aws-129038123", "ec2_instance": "aws-129038123",
@ -59,7 +58,6 @@ func getMetrics(t *testing.T) []telegraf.Metric {
}, },
time.Unix(0, 0), time.Unix(0, 0),
) )
require.NoError(t, err)
metrics[i] = m metrics[i] = m
} }
return metrics return metrics

View File

@ -15,7 +15,7 @@ func TestSyslogMapperWithDefaults(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{}, map[string]string{},
map[string]interface{}{}, map[string]interface{}{},
@ -34,7 +34,7 @@ func TestSyslogMapperWithHostname(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"hostname": "testhost", "hostname": "testhost",
@ -54,7 +54,7 @@ func TestSyslogMapperWithHostnameSourceFallback(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"source": "sourcevalue", "source": "sourcevalue",
@ -74,7 +74,7 @@ func TestSyslogMapperWithHostnameHostFallback(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"host": "hostvalue", "host": "hostvalue",
@ -94,7 +94,7 @@ func TestSyslogMapperWithDefaultSdid(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"appname": "testapp", "appname": "testapp",
@ -130,7 +130,7 @@ func TestSyslogMapperWithDefaultSdidAndOtherSdids(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"appname": "testapp", "appname": "testapp",
@ -167,7 +167,7 @@ func TestSyslogMapperWithNoSdids(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"appname": "testapp", "appname": "testapp",

View File

@ -20,7 +20,7 @@ func TestGetSyslogMessageWithFramingOctectCounting(t *testing.T) {
s.initializeSyslogMapper() s.initializeSyslogMapper()
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"hostname": "testhost", "hostname": "testhost",
@ -44,7 +44,7 @@ func TestGetSyslogMessageWithFramingNonTransparent(t *testing.T) {
s.Framing = framing.NonTransparent s.Framing = framing.NonTransparent
// Init metrics // Init metrics
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{ map[string]string{
"hostname": "testhost", "hostname": "testhost",
@ -92,7 +92,7 @@ func TestSyslogWriteWithUdp(t *testing.T) {
func testSyslogWriteWithStream(t *testing.T, s *Syslog, lconn net.Conn) { func testSyslogWriteWithStream(t *testing.T, s *Syslog, lconn net.Conn) {
metrics := []telegraf.Metric{} metrics := []telegraf.Metric{}
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{}, map[string]string{},
map[string]interface{}{}, map[string]interface{}{},
@ -116,7 +116,7 @@ func testSyslogWriteWithStream(t *testing.T, s *Syslog, lconn net.Conn) {
func testSyslogWriteWithPacket(t *testing.T, s *Syslog, lconn net.PacketConn) { func testSyslogWriteWithPacket(t *testing.T, s *Syslog, lconn net.PacketConn) {
s.Framing = framing.NonTransparent s.Framing = framing.NonTransparent
metrics := []telegraf.Metric{} metrics := []telegraf.Metric{}
m1, _ := metric.New( m1 := metric.New(
"testmetric", "testmetric",
map[string]string{}, map[string]string{},
map[string]interface{}{}, map[string]interface{}{},

View File

@ -1,14 +1,15 @@
package wavefront package wavefront
import ( import (
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
"reflect" "reflect"
"strings" "strings"
"testing" "testing"
"time" "time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
) )
// default config used by Tests // default config used by Tests
@ -32,7 +33,7 @@ func TestBuildMetrics(t *testing.T) {
pathReplacer = strings.NewReplacer("_", w.MetricSeparator) pathReplacer = strings.NewReplacer("_", w.MetricSeparator)
testMetric1, _ := metric.New( testMetric1 := metric.New(
"test.simple.metric", "test.simple.metric",
map[string]string{"tag1": "value1", "host": "testHost"}, map[string]string{"tag1": "value1", "host": "testHost"},
map[string]interface{}{"value": 123}, map[string]interface{}{"value": 123},
@ -121,7 +122,7 @@ func TestBuildMetricsWithSimpleFields(t *testing.T) {
pathReplacer = strings.NewReplacer("_", w.MetricSeparator) pathReplacer = strings.NewReplacer("_", w.MetricSeparator)
testMetric1, _ := metric.New( testMetric1 := metric.New(
"test.simple.metric", "test.simple.metric",
map[string]string{"tag1": "value1"}, map[string]string{"tag1": "value1"},
map[string]interface{}{"value": 123}, map[string]interface{}{"value": 123},

View File

@ -156,11 +156,7 @@ func UnmarshalValueList(vl *api.ValueList, multiValue string) []telegraf.Metric
} }
// Drop invalid points // Drop invalid points
m, err := metric.New(name, tags, fields, timestamp) m := metric.New(name, tags, fields, timestamp)
if err != nil {
log.Printf("E! Dropping metric %v: %v", name, err)
continue
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }
@ -192,10 +188,7 @@ func UnmarshalValueList(vl *api.ValueList, multiValue string) []telegraf.Metric
} }
} }
m, err := metric.New(name, tags, fields, timestamp) m := metric.New(name, tags, fields, timestamp)
if err != nil {
log.Printf("E! Dropping metric %v: %v", name, err)
}
metrics = append(metrics, m) metrics = append(metrics, m)
default: default:

View File

@ -280,10 +280,8 @@ outer:
delete(recordFields, p.TimestampColumn) delete(recordFields, p.TimestampColumn)
delete(recordFields, p.MeasurementColumn) delete(recordFields, p.MeasurementColumn)
m, err := metric.New(measurementName, tags, recordFields, metricTime) m := metric.New(measurementName, tags, recordFields, metricTime)
if err != nil {
return nil, err
}
return m, nil return m, nil
} }

View File

@ -226,10 +226,8 @@ func TestValueConversion(t *testing.T) {
metrics, err := p.Parse([]byte(testCSV)) metrics, err := p.Parse([]byte(testCSV))
require.NoError(t, err) require.NoError(t, err)
expectedMetric, err1 := metric.New("test_value", expectedTags, expectedFields, time.Unix(0, 0)) expectedMetric := metric.New("test_value", expectedTags, expectedFields, time.Unix(0, 0))
returnedMetric, err2 := metric.New(metrics[0].Name(), metrics[0].Tags(), metrics[0].Fields(), time.Unix(0, 0)) returnedMetric := metric.New(metrics[0].Name(), metrics[0].Tags(), metrics[0].Fields(), time.Unix(0, 0))
require.NoError(t, err1)
require.NoError(t, err2)
//deep equal fields //deep equal fields
require.Equal(t, expectedMetric.Fields(), returnedMetric.Fields()) require.Equal(t, expectedMetric.Fields(), returnedMetric.Fields())
@ -240,8 +238,7 @@ func TestValueConversion(t *testing.T) {
metrics, err = p.Parse([]byte(testCSV)) metrics, err = p.Parse([]byte(testCSV))
require.NoError(t, err) require.NoError(t, err)
returnedMetric, err2 = metric.New(metrics[0].Name(), metrics[0].Tags(), metrics[0].Fields(), time.Unix(0, 0)) returnedMetric = metric.New(metrics[0].Name(), metrics[0].Tags(), metrics[0].Fields(), time.Unix(0, 0))
require.NoError(t, err2)
//deep equal fields //deep equal fields
require.Equal(t, expectedMetric.Fields(), returnedMetric.Fields()) require.Equal(t, expectedMetric.Fields(), returnedMetric.Fields())

View File

@ -227,11 +227,7 @@ func (p *parser) readDWMetrics(metricType string, dwms interface{}, metrics []te
parsed, err := p.seriesParser.Parse([]byte(measurementName)) parsed, err := p.seriesParser.Parse([]byte(measurementName))
var m telegraf.Metric var m telegraf.Metric
if err != nil || len(parsed) != 1 { if err != nil || len(parsed) != 1 {
m, err = metric.New(measurementName, map[string]string{}, map[string]interface{}{}, tm) m = metric.New(measurementName, map[string]string{}, map[string]interface{}{}, tm)
if err != nil {
log.Printf("W! failed to create metric of type '%s': %s\n", metricType, err)
continue
}
} else { } else {
m = parsed[0] m = parsed[0]
m.SetTime(tm) m.SetTime(tm)

View File

@ -497,13 +497,6 @@ func containsAll(t1 map[string]string, t2 map[string]string) bool {
return true return true
} }
func Metric(v telegraf.Metric, err error) telegraf.Metric {
if err != nil {
panic(err)
}
return v
}
func NoError(t *testing.T, err error) { func NoError(t *testing.T, err error) {
require.NoError(t, err) require.NoError(t, err)
} }
@ -519,17 +512,15 @@ func TestDropWizard(t *testing.T) {
name: "minimal", name: "minimal",
input: []byte(`{"version": "3.0.0", "counters": {"cpu": {"value": 42}}}`), input: []byte(`{"version": "3.0.0", "counters": {"cpu": {"value": 42}}}`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "metric_type": "counter",
"metric_type": "counter", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, testTimeFunc(),
testTimeFunc(),
),
), ),
}, },
errFunc: NoError, errFunc: NoError,
@ -538,17 +529,15 @@ func TestDropWizard(t *testing.T) {
name: "name with space unescaped", name: "name with space unescaped",
input: []byte(`{"version": "3.0.0", "counters": {"hello world": {"value": 42}}}`), input: []byte(`{"version": "3.0.0", "counters": {"hello world": {"value": 42}}}`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "hello world",
"hello world", map[string]string{
map[string]string{ "metric_type": "counter",
"metric_type": "counter", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, testTimeFunc(),
testTimeFunc(),
),
), ),
}, },
errFunc: NoError, errFunc: NoError,
@ -564,17 +553,15 @@ func TestDropWizard(t *testing.T) {
name: "name with space double slash escape", name: "name with space double slash escape",
input: []byte(`{"version": "3.0.0", "counters": {"hello\\ world": {"value": 42}}}`), input: []byte(`{"version": "3.0.0", "counters": {"hello\\ world": {"value": 42}}}`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "hello world",
"hello world", map[string]string{
map[string]string{ "metric_type": "counter",
"metric_type": "counter", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, testTimeFunc(),
testTimeFunc(),
),
), ),
}, },
errFunc: NoError, errFunc: NoError,

View File

@ -47,12 +47,9 @@ func (p Parser) Parse(buf []byte) ([]telegraf.Metric, error) {
tags[key] = value tags[key] = value
} }
metric, err := metric.New(p.MetricName, tags, fields, time.Now().UTC()) m := metric.New(p.MetricName, tags, fields, time.Now().UTC())
if err != nil {
return nil, err
}
return []telegraf.Metric{metric}, nil return []telegraf.Metric{m}, nil
} }
// ParseLine delegates a single line of text to the Parse function // ParseLine delegates a single line of text to the Parse function

View File

@ -174,7 +174,7 @@ func (p *GraphiteParser) ParseLine(line string) (telegraf.Metric, error) {
} }
} }
return metric.New(measurement, tags, fieldValues, timestamp) return metric.New(measurement, tags, fieldValues, timestamp), nil
} }
// ApplyTemplate extracts the template fields from the given line and // ApplyTemplate extracts the template fields from the given line and

View File

@ -472,11 +472,10 @@ func TestFilterMatchDefault(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("miss.servers.localhost.cpu_load", exp := metric.New("miss.servers.localhost.cpu_load",
map[string]string{}, map[string]string{},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("miss.servers.localhost.cpu_load 11 1435077219") m, err := p.ParseLine("miss.servers.localhost.cpu_load 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -490,11 +489,10 @@ func TestFilterMatchMultipleMeasurement(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("cpu.cpu_load.10", exp := metric.New("cpu.cpu_load.10",
map[string]string{"host": "localhost"}, map[string]string{"host": "localhost"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.localhost.cpu.cpu_load.10 11 1435077219") m, err := p.ParseLine("servers.localhost.cpu.cpu_load.10 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -509,11 +507,10 @@ func TestFilterMatchMultipleMeasurementSeparator(t *testing.T) {
) )
assert.NoError(t, err) assert.NoError(t, err)
exp, err := metric.New("cpu_cpu_load_10", exp := metric.New("cpu_cpu_load_10",
map[string]string{"host": "localhost"}, map[string]string{"host": "localhost"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.localhost.cpu.cpu_load.10 11 1435077219") m, err := p.ParseLine("servers.localhost.cpu.cpu_load.10 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -527,7 +524,7 @@ func TestFilterMatchSingle(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("cpu_load", exp := metric.New("cpu_load",
map[string]string{"host": "localhost"}, map[string]string{"host": "localhost"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
@ -544,11 +541,10 @@ func TestParseNoMatch(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("servers.localhost.memory.VmallocChunk", exp := metric.New("servers.localhost.memory.VmallocChunk",
map[string]string{}, map[string]string{},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.localhost.memory.VmallocChunk 11 1435077219") m, err := p.ParseLine("servers.localhost.memory.VmallocChunk 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -562,11 +558,10 @@ func TestFilterMatchWildcard(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("cpu_load", exp := metric.New("cpu_load",
map[string]string{"host": "localhost"}, map[string]string{"host": "localhost"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219") m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -582,11 +577,10 @@ func TestFilterMatchExactBeforeWildcard(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("cpu_load", exp := metric.New("cpu_load",
map[string]string{"host": "localhost"}, map[string]string{"host": "localhost"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219") m, err := p.ParseLine("servers.localhost.cpu_load 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)
@ -631,11 +625,10 @@ func TestFilterMatchMultipleWildcards(t *testing.T) {
t.Fatalf("unexpected error creating parser, got %v", err) t.Fatalf("unexpected error creating parser, got %v", err)
} }
exp, err := metric.New("cpu_load", exp := metric.New("cpu_load",
map[string]string{"host": "server01"}, map[string]string{"host": "server01"},
map[string]interface{}{"value": float64(11)}, map[string]interface{}{"value": float64(11)},
time.Unix(1435077219, 0)) time.Unix(1435077219, 0))
assert.NoError(t, err)
m, err := p.ParseLine("servers.server01.cpu_load 11 1435077219") m, err := p.ParseLine("servers.server01.cpu_load 11 1435077219")
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -370,10 +370,10 @@ func (p *Parser) ParseLine(line string) (telegraf.Metric, error) {
} }
if p.UniqueTimestamp != "auto" { if p.UniqueTimestamp != "auto" {
return metric.New(p.Measurement, tags, fields, timestamp) return metric.New(p.Measurement, tags, fields, timestamp), nil
} }
return metric.New(p.Measurement, tags, fields, p.tsModder.tsMod(timestamp)) return metric.New(p.Measurement, tags, fields, p.tsModder.tsMod(timestamp)), nil
} }
func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) { func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) {

View File

@ -46,10 +46,9 @@ func (h *MetricHandler) Metric() (telegraf.Metric, error) {
} }
func (h *MetricHandler) SetMeasurement(name []byte) error { func (h *MetricHandler) SetMeasurement(name []byte) error {
var err error h.metric = metric.New(nameUnescape(name),
h.metric, err = metric.New(nameUnescape(name),
nil, nil, time.Time{}) nil, nil, time.Time{})
return err return nil
} }
func (h *MetricHandler) AddTag(key []byte, value []byte) error { func (h *MetricHandler) AddTag(key []byte, value []byte) error {

View File

@ -15,13 +15,6 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func Metric(v telegraf.Metric, err error) telegraf.Metric {
if err != nil {
panic(err)
}
return v
}
var DefaultTime = func() time.Time { var DefaultTime = func() time.Time {
return time.Unix(42, 0) return time.Unix(42, 0)
} }
@ -37,15 +30,13 @@ var ptests = []struct {
name: "minimal", name: "minimal",
input: []byte("cpu value=42 0"), input: []byte("cpu value=42 0"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
err: nil, err: nil,
@ -54,15 +45,13 @@ var ptests = []struct {
name: "minimal with newline", name: "minimal with newline",
input: []byte("cpu value=42 0\n"), input: []byte("cpu value=42 0\n"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
err: nil, err: nil,
@ -71,15 +60,13 @@ var ptests = []struct {
name: "measurement escape space", name: "measurement escape space",
input: []byte(`c\ pu value=42`), input: []byte(`c\ pu value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "c pu",
"c pu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -88,15 +75,13 @@ var ptests = []struct {
name: "measurement escape comma", name: "measurement escape comma",
input: []byte(`c\,pu value=42`), input: []byte(`c\,pu value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "c,pu",
"c,pu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -105,18 +90,16 @@ var ptests = []struct {
name: "tags", name: "tags",
input: []byte(`cpu,cpu=cpu0,host=localhost value=42`), input: []byte(`cpu,cpu=cpu0,host=localhost value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "cpu": "cpu0",
"cpu": "cpu0", "host": "localhost",
"host": "localhost", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -125,17 +108,15 @@ var ptests = []struct {
name: "tags escape unescapable", name: "tags escape unescapable",
input: []byte(`cpu,ho\st=localhost value=42`), input: []byte(`cpu,ho\st=localhost value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ `ho\st`: "localhost",
`ho\st`: "localhost", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -144,17 +125,15 @@ var ptests = []struct {
name: "tags escape equals", name: "tags escape equals",
input: []byte(`cpu,ho\=st=localhost value=42`), input: []byte(`cpu,ho\=st=localhost value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "ho=st": "localhost",
"ho=st": "localhost", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -163,17 +142,15 @@ var ptests = []struct {
name: "tags escape comma", name: "tags escape comma",
input: []byte(`cpu,ho\,st=localhost value=42`), input: []byte(`cpu,ho\,st=localhost value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "ho,st": "localhost",
"ho,st": "localhost", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -182,17 +159,15 @@ var ptests = []struct {
name: "tag value escape space", name: "tag value escape space",
input: []byte(`cpu,host=two\ words value=42`), input: []byte(`cpu,host=two\ words value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": "two words",
"host": "two words", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -201,17 +176,15 @@ var ptests = []struct {
name: "tag value double escape space", name: "tag value double escape space",
input: []byte(`cpu,host=two\\ words value=42`), input: []byte(`cpu,host=two\\ words value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": `two\ words`,
"host": `two\ words`, },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -220,17 +193,15 @@ var ptests = []struct {
name: "tag value triple escape space", name: "tag value triple escape space",
input: []byte(`cpu,host=two\\\ words value=42`), input: []byte(`cpu,host=two\\\ words value=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": `two\\ words`,
"host": `two\\ words`, },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -239,15 +210,13 @@ var ptests = []struct {
name: "field key escape not escapable", name: "field key escape not escapable",
input: []byte(`cpu va\lue=42`), input: []byte(`cpu va\lue=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `va\lue`: 42.0,
`va\lue`: 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -256,15 +225,13 @@ var ptests = []struct {
name: "field key escape equals", name: "field key escape equals",
input: []byte(`cpu va\=lue=42`), input: []byte(`cpu va\=lue=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `va=lue`: 42.0,
`va=lue`: 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -273,15 +240,13 @@ var ptests = []struct {
name: "field key escape comma", name: "field key escape comma",
input: []byte(`cpu va\,lue=42`), input: []byte(`cpu va\,lue=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `va,lue`: 42.0,
`va,lue`: 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -290,15 +255,13 @@ var ptests = []struct {
name: "field key escape space", name: "field key escape space",
input: []byte(`cpu va\ lue=42`), input: []byte(`cpu va\ lue=42`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `va lue`: 42.0,
`va lue`: 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -307,15 +270,13 @@ var ptests = []struct {
name: "field int", name: "field int",
input: []byte("cpu value=42i"), input: []byte("cpu value=42i"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -336,15 +297,13 @@ var ptests = []struct {
name: "field int max value", name: "field int max value",
input: []byte("cpu value=9223372036854775807i"), input: []byte("cpu value=9223372036854775807i"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": int64(9223372036854775807),
"value": int64(9223372036854775807), },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -353,15 +312,13 @@ var ptests = []struct {
name: "field uint", name: "field uint",
input: []byte("cpu value=42u"), input: []byte("cpu value=42u"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(42),
"value": uint64(42), },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -382,15 +339,13 @@ var ptests = []struct {
name: "field uint max value", name: "field uint max value",
input: []byte("cpu value=18446744073709551615u"), input: []byte("cpu value=18446744073709551615u"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(18446744073709551615),
"value": uint64(18446744073709551615), },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -399,15 +354,13 @@ var ptests = []struct {
name: "field boolean", name: "field boolean",
input: []byte("cpu value=true"), input: []byte("cpu value=true"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": true,
"value": true, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -416,15 +369,13 @@ var ptests = []struct {
name: "field string", name: "field string",
input: []byte(`cpu value="42"`), input: []byte(`cpu value="42"`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": "42",
"value": "42", },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -433,15 +384,13 @@ var ptests = []struct {
name: "field string escape quote", name: "field string escape quote",
input: []byte(`cpu value="how\"dy"`), input: []byte(`cpu value="how\"dy"`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `value`: `how"dy`,
`value`: `how"dy`, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -450,15 +399,13 @@ var ptests = []struct {
name: "field string escape backslash", name: "field string escape backslash",
input: []byte(`cpu value="how\\dy"`), input: []byte(`cpu value="how\\dy"`),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ `value`: `how\dy`,
`value`: `how\dy`, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -467,15 +414,13 @@ var ptests = []struct {
name: "field string newline", name: "field string newline",
input: []byte("cpu value=\"4\n2\""), input: []byte("cpu value=\"4\n2\""),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": "4\n2",
"value": "4\n2", },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -484,15 +429,13 @@ var ptests = []struct {
name: "no timestamp", name: "no timestamp",
input: []byte("cpu value=42"), input: []byte("cpu value=42"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -504,15 +447,13 @@ var ptests = []struct {
return time.Unix(42, 123456789) return time.Unix(42, 123456789)
}, },
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 123456789),
time.Unix(42, 123456789),
),
), ),
}, },
err: nil, err: nil,
@ -521,25 +462,21 @@ var ptests = []struct {
name: "multiple lines", name: "multiple lines",
input: []byte("cpu value=42\ncpu value=42"), input: []byte("cpu value=42\ncpu value=42"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(42, 0),
time.Unix(42, 0),
),
), ),
}, },
err: nil, err: nil,
@ -560,69 +497,67 @@ var ptests = []struct {
name: "procstat", name: "procstat",
input: []byte("procstat,exe=bash,process_name=bash voluntary_context_switches=42i,memory_rss=5103616i,rlimit_memory_data_hard=2147483647i,cpu_time_user=0.02,rlimit_file_locks_soft=2147483647i,pid=29417i,cpu_time_nice=0,rlimit_memory_locked_soft=65536i,read_count=259i,rlimit_memory_vms_hard=2147483647i,memory_swap=0i,rlimit_num_fds_soft=1024i,rlimit_nice_priority_hard=0i,cpu_time_soft_irq=0,cpu_time=0i,rlimit_memory_locked_hard=65536i,realtime_priority=0i,signals_pending=0i,nice_priority=20i,cpu_time_idle=0,memory_stack=139264i,memory_locked=0i,rlimit_memory_stack_soft=8388608i,cpu_time_iowait=0,cpu_time_guest=0,cpu_time_guest_nice=0,rlimit_memory_data_soft=2147483647i,read_bytes=0i,rlimit_cpu_time_soft=2147483647i,involuntary_context_switches=2i,write_bytes=106496i,cpu_time_system=0,cpu_time_irq=0,cpu_usage=0,memory_vms=21659648i,memory_data=1576960i,rlimit_memory_stack_hard=2147483647i,num_threads=1i,rlimit_memory_rss_soft=2147483647i,rlimit_realtime_priority_soft=0i,num_fds=4i,write_count=35i,rlimit_signals_pending_soft=78994i,cpu_time_steal=0,rlimit_num_fds_hard=4096i,rlimit_file_locks_hard=2147483647i,rlimit_cpu_time_hard=2147483647i,rlimit_signals_pending_hard=78994i,rlimit_nice_priority_soft=0i,rlimit_memory_rss_hard=2147483647i,rlimit_memory_vms_soft=2147483647i,rlimit_realtime_priority_hard=0i 1517620624000000000"), input: []byte("procstat,exe=bash,process_name=bash voluntary_context_switches=42i,memory_rss=5103616i,rlimit_memory_data_hard=2147483647i,cpu_time_user=0.02,rlimit_file_locks_soft=2147483647i,pid=29417i,cpu_time_nice=0,rlimit_memory_locked_soft=65536i,read_count=259i,rlimit_memory_vms_hard=2147483647i,memory_swap=0i,rlimit_num_fds_soft=1024i,rlimit_nice_priority_hard=0i,cpu_time_soft_irq=0,cpu_time=0i,rlimit_memory_locked_hard=65536i,realtime_priority=0i,signals_pending=0i,nice_priority=20i,cpu_time_idle=0,memory_stack=139264i,memory_locked=0i,rlimit_memory_stack_soft=8388608i,cpu_time_iowait=0,cpu_time_guest=0,cpu_time_guest_nice=0,rlimit_memory_data_soft=2147483647i,read_bytes=0i,rlimit_cpu_time_soft=2147483647i,involuntary_context_switches=2i,write_bytes=106496i,cpu_time_system=0,cpu_time_irq=0,cpu_usage=0,memory_vms=21659648i,memory_data=1576960i,rlimit_memory_stack_hard=2147483647i,num_threads=1i,rlimit_memory_rss_soft=2147483647i,rlimit_realtime_priority_soft=0i,num_fds=4i,write_count=35i,rlimit_signals_pending_soft=78994i,cpu_time_steal=0,rlimit_num_fds_hard=4096i,rlimit_file_locks_hard=2147483647i,rlimit_cpu_time_hard=2147483647i,rlimit_signals_pending_hard=78994i,rlimit_nice_priority_soft=0i,rlimit_memory_rss_hard=2147483647i,rlimit_memory_vms_soft=2147483647i,rlimit_realtime_priority_hard=0i 1517620624000000000"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "procstat",
"procstat", map[string]string{
map[string]string{ "exe": "bash",
"exe": "bash", "process_name": "bash",
"process_name": "bash", },
}, map[string]interface{}{
map[string]interface{}{ "cpu_time": 0,
"cpu_time": 0, "cpu_time_guest": float64(0),
"cpu_time_guest": float64(0), "cpu_time_guest_nice": float64(0),
"cpu_time_guest_nice": float64(0), "cpu_time_idle": float64(0),
"cpu_time_idle": float64(0), "cpu_time_iowait": float64(0),
"cpu_time_iowait": float64(0), "cpu_time_irq": float64(0),
"cpu_time_irq": float64(0), "cpu_time_nice": float64(0),
"cpu_time_nice": float64(0), "cpu_time_soft_irq": float64(0),
"cpu_time_soft_irq": float64(0), "cpu_time_steal": float64(0),
"cpu_time_steal": float64(0), "cpu_time_system": float64(0),
"cpu_time_system": float64(0), "cpu_time_user": float64(0.02),
"cpu_time_user": float64(0.02), "cpu_usage": float64(0),
"cpu_usage": float64(0), "involuntary_context_switches": 2,
"involuntary_context_switches": 2, "memory_data": 1576960,
"memory_data": 1576960, "memory_locked": 0,
"memory_locked": 0, "memory_rss": 5103616,
"memory_rss": 5103616, "memory_stack": 139264,
"memory_stack": 139264, "memory_swap": 0,
"memory_swap": 0, "memory_vms": 21659648,
"memory_vms": 21659648, "nice_priority": 20,
"nice_priority": 20, "num_fds": 4,
"num_fds": 4, "num_threads": 1,
"num_threads": 1, "pid": 29417,
"pid": 29417, "read_bytes": 0,
"read_bytes": 0, "read_count": 259,
"read_count": 259, "realtime_priority": 0,
"realtime_priority": 0, "rlimit_cpu_time_hard": 2147483647,
"rlimit_cpu_time_hard": 2147483647, "rlimit_cpu_time_soft": 2147483647,
"rlimit_cpu_time_soft": 2147483647, "rlimit_file_locks_hard": 2147483647,
"rlimit_file_locks_hard": 2147483647, "rlimit_file_locks_soft": 2147483647,
"rlimit_file_locks_soft": 2147483647, "rlimit_memory_data_hard": 2147483647,
"rlimit_memory_data_hard": 2147483647, "rlimit_memory_data_soft": 2147483647,
"rlimit_memory_data_soft": 2147483647, "rlimit_memory_locked_hard": 65536,
"rlimit_memory_locked_hard": 65536, "rlimit_memory_locked_soft": 65536,
"rlimit_memory_locked_soft": 65536, "rlimit_memory_rss_hard": 2147483647,
"rlimit_memory_rss_hard": 2147483647, "rlimit_memory_rss_soft": 2147483647,
"rlimit_memory_rss_soft": 2147483647, "rlimit_memory_stack_hard": 2147483647,
"rlimit_memory_stack_hard": 2147483647, "rlimit_memory_stack_soft": 8388608,
"rlimit_memory_stack_soft": 8388608, "rlimit_memory_vms_hard": 2147483647,
"rlimit_memory_vms_hard": 2147483647, "rlimit_memory_vms_soft": 2147483647,
"rlimit_memory_vms_soft": 2147483647, "rlimit_nice_priority_hard": 0,
"rlimit_nice_priority_hard": 0, "rlimit_nice_priority_soft": 0,
"rlimit_nice_priority_soft": 0, "rlimit_num_fds_hard": 4096,
"rlimit_num_fds_hard": 4096, "rlimit_num_fds_soft": 1024,
"rlimit_num_fds_soft": 1024, "rlimit_realtime_priority_hard": 0,
"rlimit_realtime_priority_hard": 0, "rlimit_realtime_priority_soft": 0,
"rlimit_realtime_priority_soft": 0, "rlimit_signals_pending_hard": 78994,
"rlimit_signals_pending_hard": 78994, "rlimit_signals_pending_soft": 78994,
"rlimit_signals_pending_soft": 78994, "signals_pending": 0,
"signals_pending": 0, "voluntary_context_switches": 42,
"voluntary_context_switches": 42, "write_bytes": 106496,
"write_bytes": 106496, "write_count": 35,
"write_count": 35, },
}, time.Unix(0, 1517620624000000000),
time.Unix(0, 1517620624000000000),
),
), ),
}, },
err: nil, err: nil,
@ -712,13 +647,11 @@ func TestSeriesParser(t *testing.T) {
name: "minimal", name: "minimal",
input: []byte("cpu"), input: []byte("cpu"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{},
map[string]interface{}{}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
}, },
@ -726,16 +659,14 @@ func TestSeriesParser(t *testing.T) {
name: "tags", name: "tags",
input: []byte("cpu,a=x,b=y"), input: []byte("cpu,a=x,b=y"),
metrics: []telegraf.Metric{ metrics: []telegraf.Metric{
Metric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "a": "x",
"a": "x", "b": "y",
"b": "y", },
}, map[string]interface{}{},
map[string]interface{}{}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
}, },

View File

@ -142,11 +142,9 @@ func (p *Parser) parseObject(data map[string]interface{}, timestamp time.Time) (
} }
tags, nFields := p.switchFieldToTag(tags, f.Fields) tags, nFields := p.switchFieldToTag(tags, f.Fields)
metric, err := metric.New(name, tags, nFields, timestamp) m := metric.New(name, tags, nFields, timestamp)
if err != nil {
return nil, err return []telegraf.Metric{m}, nil
}
return []telegraf.Metric{metric}, nil
} }
// will take in field map with strings and bools, // will take in field map with strings and bools,

View File

@ -67,10 +67,7 @@ func (p *Parser) Parse(b []byte) ([]telegraf.Metric, error) {
continue continue
} }
m, err := metric.New(p.MetricName, map[string]string{}, fields, p.Now()) m := metric.New(p.MetricName, map[string]string{}, fields, p.Now())
if err != nil {
return nil, err
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }

View File

@ -11,10 +11,8 @@ import (
func MustMetric(t *testing.T, m *testutil.Metric) telegraf.Metric { func MustMetric(t *testing.T, m *testutil.Metric) telegraf.Metric {
t.Helper() t.Helper()
v, err := metric.New(m.Measurement, m.Tags, m.Fields, m.Time) v := metric.New(m.Measurement, m.Tags, m.Fields, m.Time)
if err != nil {
t.Fatal(err)
}
return v return v
} }

View File

@ -65,10 +65,8 @@ func TryAddState(runErr error, metrics []telegraf.Metric) ([]telegraf.Metric, er
f := map[string]interface{}{ f := map[string]interface{}{
"state": state, "state": state,
} }
m, err := metric.New("nagios_state", nil, f, ts) m := metric.New("nagios_state", nil, f, ts)
if err != nil {
return metrics, err
}
metrics = append(metrics, m) metrics = append(metrics, m)
return metrics, nil return metrics, nil
} }
@ -166,12 +164,8 @@ func (p *NagiosParser) Parse(buf []byte) ([]telegraf.Metric, error) {
fields["long_service_output"] = longmsg.String() fields["long_service_output"] = longmsg.String()
} }
m, err := metric.New("nagios_state", nil, fields, ts) m := metric.New("nagios_state", nil, fields, ts)
if err == nil { metrics = append(metrics, m)
metrics = append(metrics, m)
} else {
log.Printf("E! [parser.nagios] failed to add nagios_state: %s\n", err)
}
return metrics, nil return metrics, nil
} }
@ -247,12 +241,10 @@ func parsePerfData(perfdatas string, timestamp time.Time) ([]telegraf.Metric, er
} }
// Create metric // Create metric
metric, err := metric.New("nagios", tags, fields, timestamp) m := metric.New("nagios", tags, fields, timestamp)
if err != nil {
return nil, err
}
// Add Metric // Add Metric
metrics = append(metrics, metric) metrics = append(metrics, m)
} }
return metrics, nil return metrics, nil

View File

@ -74,10 +74,7 @@ func (b *metricBuilder) f(k string, v interface{}) *metricBuilder {
} }
func (b *metricBuilder) b() telegraf.Metric { func (b *metricBuilder) b() telegraf.Metric {
m, err := metric.New(b.name, b.tags, b.fields, b.timestamp) m := metric.New(b.name, b.tags, b.fields, b.timestamp)
if err != nil {
panic(err)
}
return m return m
} }

View File

@ -4,13 +4,14 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"fmt" "fmt"
"github.com/matttproud/golang_protobuf_extensions/pbutil"
"io" "io"
"math" "math"
"mime" "mime"
"net/http" "net/http"
"time" "time"
"github.com/matttproud/golang_protobuf_extensions/pbutil"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"github.com/influxdata/telegraf/plugins/parsers/prometheus/common" "github.com/influxdata/telegraf/plugins/parsers/prometheus/common"
@ -80,10 +81,8 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) {
// converting to telegraf metric // converting to telegraf metric
if len(fields) > 0 { if len(fields) > 0 {
t := getTimestamp(m, now) t := getTimestamp(m, now)
metric, err := metric.New("prometheus", tags, fields, t, common.ValueType(mf.GetType())) m := metric.New("prometheus", tags, fields, t, common.ValueType(mf.GetType()))
if err == nil { metrics = append(metrics, m)
metrics = append(metrics, metric)
}
} }
} }
} }
@ -121,10 +120,8 @@ func makeQuantiles(m *dto.Metric, tags map[string]string, metricName string, met
fields[metricName+"_count"] = float64(m.GetSummary().GetSampleCount()) fields[metricName+"_count"] = float64(m.GetSummary().GetSampleCount())
fields[metricName+"_sum"] = float64(m.GetSummary().GetSampleSum()) fields[metricName+"_sum"] = float64(m.GetSummary().GetSampleSum())
met, err := metric.New("prometheus", tags, fields, t, common.ValueType(metricType)) met := metric.New("prometheus", tags, fields, t, common.ValueType(metricType))
if err == nil { metrics = append(metrics, met)
metrics = append(metrics, met)
}
for _, q := range m.GetSummary().Quantile { for _, q := range m.GetSummary().Quantile {
newTags := tags newTags := tags
@ -133,10 +130,8 @@ func makeQuantiles(m *dto.Metric, tags map[string]string, metricName string, met
newTags["quantile"] = fmt.Sprint(q.GetQuantile()) newTags["quantile"] = fmt.Sprint(q.GetQuantile())
fields[metricName] = float64(q.GetValue()) fields[metricName] = float64(q.GetValue())
quantileMetric, err := metric.New("prometheus", newTags, fields, t, common.ValueType(metricType)) quantileMetric := metric.New("prometheus", newTags, fields, t, common.ValueType(metricType))
if err == nil { metrics = append(metrics, quantileMetric)
metrics = append(metrics, quantileMetric)
}
} }
return metrics return metrics
} }
@ -150,10 +145,8 @@ func makeBuckets(m *dto.Metric, tags map[string]string, metricName string, metri
fields[metricName+"_count"] = float64(m.GetHistogram().GetSampleCount()) fields[metricName+"_count"] = float64(m.GetHistogram().GetSampleCount())
fields[metricName+"_sum"] = float64(m.GetHistogram().GetSampleSum()) fields[metricName+"_sum"] = float64(m.GetHistogram().GetSampleSum())
met, err := metric.New("prometheus", tags, fields, t, common.ValueType(metricType)) met := metric.New("prometheus", tags, fields, t, common.ValueType(metricType))
if err == nil { metrics = append(metrics, met)
metrics = append(metrics, met)
}
for _, b := range m.GetHistogram().Bucket { for _, b := range m.GetHistogram().Bucket {
newTags := tags newTags := tags
@ -161,10 +154,8 @@ func makeBuckets(m *dto.Metric, tags map[string]string, metricName string, metri
newTags["le"] = fmt.Sprint(b.GetUpperBound()) newTags["le"] = fmt.Sprint(b.GetUpperBound())
fields[metricName+"_bucket"] = float64(b.GetCumulativeCount()) fields[metricName+"_bucket"] = float64(b.GetCumulativeCount())
histogramMetric, err := metric.New("prometheus", newTags, fields, t, common.ValueType(metricType)) histogramMetric := metric.New("prometheus", newTags, fields, t, common.ValueType(metricType))
if err == nil { metrics = append(metrics, histogramMetric)
metrics = append(metrics, histogramMetric)
}
} }
return metrics return metrics
} }

View File

@ -55,10 +55,7 @@ func (p *Parser) Parse(buf []byte) ([]telegraf.Metric, error) {
if s.Timestamp > 0 { if s.Timestamp > 0 {
t = time.Unix(0, s.Timestamp*1000000) t = time.Unix(0, s.Timestamp*1000000)
} }
m, err := metric.New("prometheus_remote_write", tags, fields, t) m := metric.New("prometheus_remote_write", tags, fields, t)
if err != nil {
return nil, fmt.Errorf("unable to convert to telegraf metric: %s", err)
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }
} }

View File

@ -48,13 +48,10 @@ func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
} }
fields := map[string]interface{}{v.FieldName: value} fields := map[string]interface{}{v.FieldName: value}
metric, err := metric.New(v.MetricName, v.DefaultTags, m := metric.New(v.MetricName, v.DefaultTags,
fields, time.Now().UTC()) fields, time.Now().UTC())
if err != nil {
return nil, err
}
return []telegraf.Metric{metric}, nil return []telegraf.Metric{m}, nil
} }
func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) { func (v *ValueParser) ParseLine(line string) (telegraf.Metric, error) {

View File

@ -152,10 +152,7 @@ func (p *PointParser) convertPointToTelegrafMetric(points []Point) ([]telegraf.M
} }
fields["value"] = v fields["value"] = v
m, err := metric.New(point.Name, tags, fields, time.Unix(point.Timestamp, 0)) m := metric.New(point.Name, tags, fields, time.Unix(point.Timestamp, 0))
if err != nil {
return nil, err
}
metrics = append(metrics, m) metrics = append(metrics, m)
} }

View File

@ -14,77 +14,65 @@ func TestParse(t *testing.T) {
parsedMetrics, err := parser.Parse([]byte("test.metric 1")) parsedMetrics, err := parser.Parse([]byte("test.metric 1"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0)) testMetric := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0))
assert.NoError(t, err)
assert.Equal(t, parsedMetrics[0].Name(), testMetric.Name()) assert.Equal(t, parsedMetrics[0].Name(), testMetric.Name())
assert.Equal(t, parsedMetrics[0].Fields(), testMetric.Fields()) assert.Equal(t, parsedMetrics[0].Fields(), testMetric.Fields())
parsedMetrics, err = parser.Parse([]byte("\u2206test.delta 1 1530939936")) parsedMetrics, err = parser.Parse([]byte("\u2206test.delta 1 1530939936"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("\u2206test.delta", map[string]string{}, testMetric = metric.New("\u2206test.delta", map[string]string{},
map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\u0394test.delta 1 1530939936")) parsedMetrics, err = parser.Parse([]byte("\u0394test.delta 1 1530939936"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("\u0394test.delta", map[string]string{}, testMetric = metric.New("\u0394test.delta", map[string]string{},
map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\u0394test.delta 1.234 1530939936 source=\"mysource\" tag2=value2")) parsedMetrics, err = parser.Parse([]byte("\u0394test.delta 1.234 1530939936 source=\"mysource\" tag2=value2"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("\u0394test.delta", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.234}, time.Unix(1530939936, 0)) testMetric = metric.New("\u0394test.delta", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936")) parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource")) parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 source=\"mysource\"")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 source=\"mysource\""))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" -1.1234 1530939936 \"source\"=\"mysource\" tag2=value2")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" -1.1234 1530939936 \"source\"=\"mysource\" tag2=value2"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": -1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": -1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234e04 1530939936 \"source\"=\"mysource\" tag2=value2")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234e04 1530939936 \"source\"=\"mysource\" tag2=value2"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234e04}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234e04}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234e-04 1530939936 \"source\"=\"mysource\" tag2=value2")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234e-04 1530939936 \"source\"=\"mysource\" tag2=value2"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234e-04}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234e-04}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("test.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 ")) parsedMetrics, err = parser.Parse([]byte("test.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 "))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
} }
@ -93,39 +81,33 @@ func TestParseLine(t *testing.T) {
parsedMetric, err := parser.ParseLine("test.metric 1") parsedMetric, err := parser.ParseLine("test.metric 1")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0)) testMetric := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0))
assert.NoError(t, err)
assert.Equal(t, parsedMetric.Name(), testMetric.Name()) assert.Equal(t, parsedMetric.Name(), testMetric.Name())
assert.Equal(t, parsedMetric.Fields(), testMetric.Fields()) assert.Equal(t, parsedMetric.Fields(), testMetric.Fields())
parsedMetric, err = parser.ParseLine("test.metric 1 1530939936") parsedMetric, err = parser.ParseLine("test.metric 1 1530939936")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
parsedMetric, err = parser.ParseLine("test.metric 1 1530939936 source=mysource") parsedMetric, err = parser.ParseLine("test.metric 1 1530939936 source=mysource")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
parsedMetric, err = parser.ParseLine("\"test.metric\" 1.1234 1530939936 source=\"mysource\"") parsedMetric, err = parser.ParseLine("\"test.metric\" 1.1234 1530939936 source=\"mysource\"")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
parsedMetric, err = parser.ParseLine("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2") parsedMetric, err = parser.ParseLine("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
parsedMetric, err = parser.ParseLine("test.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 ") parsedMetric, err = parser.ParseLine("test.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 ")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
} }
@ -134,10 +116,8 @@ func TestParseMultiple(t *testing.T) {
parsedMetrics, err := parser.Parse([]byte("test.metric 1\ntest.metric2 2 1530939936")) parsedMetrics, err := parser.Parse([]byte("test.metric 1\ntest.metric2 2 1530939936"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric1, err := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0)) testMetric1 := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(0, 0))
assert.NoError(t, err) testMetric2 := metric.New("test.metric2", map[string]string{}, map[string]interface{}{"value": 2.}, time.Unix(1530939936, 0))
testMetric2, err := metric.New("test.metric2", map[string]string{}, map[string]interface{}{"value": 2.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
testMetrics := []telegraf.Metric{testMetric1, testMetric2} testMetrics := []telegraf.Metric{testMetric1, testMetric2}
assert.Equal(t, parsedMetrics[0].Name(), testMetrics[0].Name()) assert.Equal(t, parsedMetrics[0].Name(), testMetrics[0].Name())
assert.Equal(t, parsedMetrics[0].Fields(), testMetrics[0].Fields()) assert.Equal(t, parsedMetrics[0].Fields(), testMetrics[0].Fields())
@ -145,30 +125,23 @@ func TestParseMultiple(t *testing.T) {
parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource\n\"test.metric\" 1.1234 1530939936 source=\"mysource\"")) parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource\n\"test.metric\" 1.1234 1530939936 source=\"mysource\""))
assert.NoError(t, err) assert.NoError(t, err)
testMetric1, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric1 = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err) testMetric2 = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
testMetric2, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
testMetrics = []telegraf.Metric{testMetric1, testMetric2} testMetrics = []telegraf.Metric{testMetric1, testMetric2}
assert.EqualValues(t, parsedMetrics, testMetrics) assert.EqualValues(t, parsedMetrics, testMetrics)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2\ntest.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 ")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 \"source\"=\"mysource\" tag2=value2\ntest.metric 1.1234 1530939936 source=\"mysource\" tag2=value2 "))
assert.NoError(t, err) assert.NoError(t, err)
testMetric1, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric1 = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err) testMetric2 = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
testMetric2, err = metric.New("test.metric", map[string]string{"source": "mysource", "tag2": "value2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
testMetrics = []telegraf.Metric{testMetric1, testMetric2} testMetrics = []telegraf.Metric{testMetric1, testMetric2}
assert.EqualValues(t, parsedMetrics, testMetrics) assert.EqualValues(t, parsedMetrics, testMetrics)
parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource\n\"test.metric\" 1.1234 1530939936 source=\"mysource\"\ntest.metric3 333 1530939936 tagit=valueit")) parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource\n\"test.metric\" 1.1234 1530939936 source=\"mysource\"\ntest.metric3 333 1530939936 tagit=valueit"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric1, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric1 = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err) testMetric2 = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
testMetric2, err = metric.New("test.metric", map[string]string{"source": "mysource"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric3 := metric.New("test.metric3", map[string]string{"tagit": "valueit"}, map[string]interface{}{"value": 333.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
testMetric3, err := metric.New("test.metric3", map[string]string{"tagit": "valueit"}, map[string]interface{}{"value": 333.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
testMetrics = []telegraf.Metric{testMetric1, testMetric2, testMetric3} testMetrics = []telegraf.Metric{testMetric1, testMetric2, testMetric3}
assert.EqualValues(t, parsedMetrics, testMetrics) assert.EqualValues(t, parsedMetrics, testMetrics)
} }
@ -178,14 +151,12 @@ func TestParseSpecial(t *testing.T) {
parsedMetric, err := parser.ParseLine("\"test.metric\" 1 1530939936") parsedMetric, err := parser.ParseLine("\"test.metric\" 1 1530939936")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric := metric.New("test.metric", map[string]string{}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
parsedMetric, err = parser.ParseLine("test.metric 1 1530939936 tag1=\"val\\\"ue1\"") parsedMetric, err = parser.ParseLine("test.metric 1 1530939936 tag1=\"val\\\"ue1\"")
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"tag1": "val\\\"ue1"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"tag1": "val\\\"ue1"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetric, testMetric) assert.EqualValues(t, parsedMetric, testMetric)
} }
@ -225,19 +196,16 @@ func TestParseDefaultTags(t *testing.T) {
parsedMetrics, err := parser.Parse([]byte("test.metric 1 1530939936")) parsedMetrics, err := parser.Parse([]byte("test.metric 1 1530939936"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err := metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric := metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource")) parsedMetrics, err = parser.Parse([]byte("test.metric 1 1530939936 source=mysource"))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2", "source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2", "source": "mysource"}, map[string]interface{}{"value": 1.}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 another=\"test3\"")) parsedMetrics, err = parser.Parse([]byte("\"test.metric\" 1.1234 1530939936 another=\"test3\""))
assert.NoError(t, err) assert.NoError(t, err)
testMetric, err = metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0)) testMetric = metric.New("test.metric", map[string]string{"myDefault": "value1", "another": "test2"}, map[string]interface{}{"value": 1.1234}, time.Unix(1530939936, 0))
assert.NoError(t, err)
assert.EqualValues(t, parsedMetrics[0], testMetric) assert.EqualValues(t, parsedMetrics[0], testMetric)
} }

View File

@ -292,7 +292,7 @@ func (p *Parser) parseQuery(starttime time.Time, doc, selected *xmlquery.Node, c
} }
} }
return metric.New(metricname, tags, fields, timestamp) return metric.New(metricname, tags, fields, timestamp), nil
} }
func getNodePath(node, relativeTo *xmlquery.Node, sep string) string { func getNodePath(node, relativeTo *xmlquery.Node, sep string) string {

View File

@ -10,12 +10,12 @@ import (
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
metric, _ := metric.New("m1", m := metric.New("m1",
map[string]string{"metric_tag": "from_metric"}, map[string]string{"metric_tag": "from_metric"},
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now(), time.Now(),
) )
return metric return m
} }
func calculateProcessedTags(processor Clone, metric telegraf.Metric) map[string]string { func calculateProcessedTags(processor Clone, metric telegraf.Metric) map[string]string {

View File

@ -19,7 +19,7 @@ func MustMetric(name string, tags map[string]string, fields map[string]interface
if fields == nil { if fields == nil {
fields = map[string]interface{}{} fields = map[string]interface{}{}
} }
m, _ := metric.New(name, tags, fields, metricTime) m := metric.New(name, tags, fields, metricTime)
return m return m
} }

View File

@ -14,7 +14,7 @@ import (
const metricName = "m1" const metricName = "m1"
func createMetric(value int64, when time.Time) telegraf.Metric { func createMetric(value int64, when time.Time) telegraf.Metric {
m, _ := metric.New(metricName, m := metric.New(metricName,
map[string]string{"tag": "tag_value"}, map[string]string{"tag": "tag_value"},
map[string]interface{}{"value": value}, map[string]interface{}{"value": value},
when, when,
@ -162,7 +162,7 @@ func TestSameTimestamp(t *testing.T) {
var in telegraf.Metric var in telegraf.Metric
var out []telegraf.Metric var out []telegraf.Metric
in, _ = metric.New("metric", in = metric.New("metric",
map[string]string{"tag": "value"}, map[string]string{"tag": "value"},
map[string]interface{}{"foo": 1}, // field map[string]interface{}{"foo": 1}, // field
now, now,
@ -170,7 +170,7 @@ func TestSameTimestamp(t *testing.T) {
out = dedup.Apply(in) out = dedup.Apply(in)
require.Equal(t, []telegraf.Metric{in}, out) // pass require.Equal(t, []telegraf.Metric{in}, out) // pass
in, _ = metric.New("metric", in = metric.New("metric",
map[string]string{"tag": "value"}, map[string]string{"tag": "value"},
map[string]interface{}{"bar": 1}, // different field map[string]interface{}{"bar": 1}, // different field
now, now,
@ -178,7 +178,7 @@ func TestSameTimestamp(t *testing.T) {
out = dedup.Apply(in) out = dedup.Apply(in)
require.Equal(t, []telegraf.Metric{in}, out) // pass require.Equal(t, []telegraf.Metric{in}, out) // pass
in, _ = metric.New("metric", in = metric.New("metric",
map[string]string{"tag": "value"}, map[string]string{"tag": "value"},
map[string]interface{}{"bar": 2}, // same field different value map[string]interface{}{"bar": 2}, // same field different value
now, now,
@ -186,7 +186,7 @@ func TestSameTimestamp(t *testing.T) {
out = dedup.Apply(in) out = dedup.Apply(in)
require.Equal(t, []telegraf.Metric{in}, out) // pass require.Equal(t, []telegraf.Metric{in}, out) // pass
in, _ = metric.New("metric", in = metric.New("metric",
map[string]string{"tag": "value"}, map[string]string{"tag": "value"},
map[string]interface{}{"bar": 2}, // same field same value map[string]interface{}{"bar": 2}, // same field same value
now, now,

View File

@ -11,7 +11,7 @@ import (
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
metric, _ := metric.New("m1", m := metric.New("m1",
map[string]string{ map[string]string{
"tag": "tag_value", "tag": "tag_value",
"duplicate_tag": "tag_value", "duplicate_tag": "tag_value",
@ -26,7 +26,7 @@ func createTestMetric() telegraf.Metric {
}, },
time.Now(), time.Now(),
) )
return metric return m
} }
func calculateProcessedValues(mapper EnumMapper, metric telegraf.Metric) map[string]interface{} { func calculateProcessedValues(mapper EnumMapper, metric telegraf.Metric) map[string]interface{} {

View File

@ -34,7 +34,7 @@ func TestExternalProcessorWorks(t *testing.T) {
orig := now orig := now
metrics := []telegraf.Metric{} metrics := []telegraf.Metric{}
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
m, err := metric.New("test", m := metric.New("test",
map[string]string{ map[string]string{
"city": "Toronto", "city": "Toronto",
}, },
@ -43,7 +43,6 @@ func TestExternalProcessorWorks(t *testing.T) {
"count": 1, "count": 1,
}, },
now) now)
require.NoError(t, err)
metrics = append(metrics, m) metrics = append(metrics, m)
now = now.Add(1) now = now.Add(1)
@ -96,7 +95,7 @@ func TestParseLinesWithNewLines(t *testing.T) {
now := time.Now() now := time.Now()
orig := now orig := now
m, err := metric.New("test", m := metric.New("test",
map[string]string{ map[string]string{
"author": "Mr. Gopher", "author": "Mr. Gopher",
}, },
@ -106,8 +105,6 @@ func TestParseLinesWithNewLines(t *testing.T) {
}, },
now) now)
require.NoError(t, err)
e.Add(m, acc) e.Add(m, acc)
acc.Wait(1) acc.Wait(1)

View File

@ -10,12 +10,12 @@ import (
) )
func createTestMetric() telegraf.Metric { func createTestMetric() telegraf.Metric {
metric, _ := metric.New("m1", m := metric.New("m1",
map[string]string{"metric_tag": "from_metric"}, map[string]string{"metric_tag": "from_metric"},
map[string]interface{}{"value": int64(1)}, map[string]interface{}{"value": int64(1)},
time.Now(), time.Now(),
) )
return metric return m
} }
func calculateProcessedTags(processor Override, metric telegraf.Metric) map[string]string { func calculateProcessedTags(processor Override, metric telegraf.Metric) map[string]string {

View File

@ -21,13 +21,6 @@ func compareMetrics(t *testing.T, expected, actual []telegraf.Metric) {
} }
} }
func Metric(v telegraf.Metric, err error) telegraf.Metric {
if err != nil {
panic(err)
}
return v
}
func TestApply(t *testing.T) { func TestApply(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@ -51,18 +44,17 @@ func TestApply(t *testing.T) {
"method", "method",
}, },
}, },
input: Metric( input: metric.New(
metric.New( "singleField",
"singleField", map[string]string{
map[string]string{ "some": "tag",
"some": "tag", },
}, map[string]interface{}{
map[string]interface{}{ "sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"singleField", "singleField",
map[string]string{ map[string]string{
"ts": "2018-07-24T19:43:40.275Z", "ts": "2018-07-24T19:43:40.275Z",
@ -71,7 +63,7 @@ func TestApply(t *testing.T) {
"method": "POST", "method": "POST",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -88,18 +80,17 @@ func TestApply(t *testing.T) {
"method", "method",
}, },
}, },
input: Metric( input: metric.New(
metric.New( "singleField",
"singleField", map[string]string{
map[string]string{ "some": "tag",
"some": "tag", },
}, map[string]interface{}{
map[string]interface{}{ "sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"singleField", "singleField",
map[string]string{ map[string]string{
"some": "tag", "some": "tag",
@ -111,7 +102,7 @@ func TestApply(t *testing.T) {
map[string]interface{}{ map[string]interface{}{
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -127,7 +118,16 @@ func TestApply(t *testing.T) {
"method", "method",
}, },
}, },
input: Metric( input: metric.New(
"singleField",
map[string]string{
"some": "tag",
},
map[string]interface{}{
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"singleField", "singleField",
map[string]string{ map[string]string{
@ -136,18 +136,8 @@ func TestApply(t *testing.T) {
map[string]interface{}{ map[string]interface{}{
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{ metric.New(
Metric(metric.New(
"singleField",
map[string]string{
"some": "tag",
},
map[string]interface{}{
"sample": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
},
time.Unix(0, 0))),
Metric(metric.New(
"singleField", "singleField",
map[string]string{ map[string]string{
"ts": "2018-07-24T19:43:40.275Z", "ts": "2018-07-24T19:43:40.275Z",
@ -156,7 +146,7 @@ func TestApply(t *testing.T) {
"method": "POST", "method": "POST",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -166,23 +156,22 @@ func TestApply(t *testing.T) {
DataFormat: "influx", DataFormat: "influx",
}, },
dropOriginal: false, dropOriginal: false,
input: Metric( input: metric.New(
"influxField",
map[string]string{},
map[string]interface{}{
"message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790",
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"influxField", "influxField",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790", "message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790",
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{ metric.New(
Metric(metric.New(
"influxField",
map[string]string{},
map[string]interface{}{
"message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790",
},
time.Unix(0, 0))),
Metric(metric.New(
"deal", "deal",
map[string]string{ map[string]string{
"computer_name": "hosta", "computer_name": "hosta",
@ -190,7 +179,7 @@ func TestApply(t *testing.T) {
map[string]interface{}{ map[string]interface{}{
"message": "stuff", "message": "stuff",
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -201,18 +190,17 @@ func TestApply(t *testing.T) {
config: parsers.Config{ config: parsers.Config{
DataFormat: "influx", DataFormat: "influx",
}, },
input: Metric( input: metric.New(
metric.New( "influxField",
"influxField", map[string]string{
map[string]string{ "some": "tag",
"some": "tag", },
}, map[string]interface{}{
map[string]interface{}{ "message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790",
"message": "deal,computer_name=hosta message=\"stuff\" 1530654676316265790", },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"deal", "deal",
map[string]string{ map[string]string{
"computer_name": "hosta", "computer_name": "hosta",
@ -221,7 +209,7 @@ func TestApply(t *testing.T) {
map[string]interface{}{ map[string]interface{}{
"message": "stuff", "message": "stuff",
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -232,16 +220,15 @@ func TestApply(t *testing.T) {
DataFormat: "grok", DataFormat: "grok",
GrokPatterns: []string{"%{COMBINED_LOG_FORMAT}"}, GrokPatterns: []string{"%{COMBINED_LOG_FORMAT}"},
}, },
input: Metric( input: metric.New(
metric.New( "success",
"success", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "grokSample": "127.0.0.1 - - [11/Dec/2013:00:01:45 -0800] \"GET /xampp/status.php HTTP/1.1\" 200 3891 \"http://cadenza/xampp/navi.php\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0\"",
"grokSample": "127.0.0.1 - - [11/Dec/2013:00:01:45 -0800] \"GET /xampp/status.php HTTP/1.1\" 200 3891 \"http://cadenza/xampp/navi.php\" \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/25.0\"", },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"success", "success",
map[string]string{ map[string]string{
"resp_code": "200", "resp_code": "200",
@ -257,7 +244,7 @@ func TestApply(t *testing.T) {
"ident": "-", "ident": "-",
"http_version": float64(1.1), "http_version": float64(1.1),
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -268,30 +255,29 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl", "err"}, TagKeys: []string{"lvl", "err"},
}, },
input: Metric( input: metric.New(
metric.New( "bigMeasure",
"bigMeasure", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "field_1": `{"lvl":"info","msg":"http request"}`,
"field_1": `{"lvl":"info","msg":"http request"}`, "field_2": `{"err":"fatal","fatal":"security threat"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`, },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"bigMeasure", "bigMeasure",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
Metric(metric.New( metric.New(
"bigMeasure", "bigMeasure",
map[string]string{ map[string]string{
"err": "fatal", "err": "fatal",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -303,17 +289,16 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl", "msg", "err", "fatal"}, TagKeys: []string{"lvl", "msg", "err", "fatal"},
}, },
input: Metric( input: metric.New(
metric.New( "bigMeasure",
"bigMeasure", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "field_1": `{"lvl":"info","msg":"http request"}`,
"field_1": `{"lvl":"info","msg":"http request"}`, "field_2": `{"err":"fatal","fatal":"security threat"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`, },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"bigMeasure", "bigMeasure",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
@ -325,7 +310,7 @@ func TestApply(t *testing.T) {
"field_1": `{"lvl":"info","msg":"http request"}`, "field_1": `{"lvl":"info","msg":"http request"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`, "field_2": `{"err":"fatal","fatal":"security threat"}`,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -336,7 +321,15 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl", "msg", "err", "fatal"}, TagKeys: []string{"lvl", "msg", "err", "fatal"},
}, },
input: Metric( input: metric.New(
"bigMeasure",
map[string]string{},
map[string]interface{}{
"field_1": `{"lvl":"info","msg":"http request"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`,
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"bigMeasure", "bigMeasure",
map[string]string{}, map[string]string{},
@ -344,32 +337,23 @@ func TestApply(t *testing.T) {
"field_1": `{"lvl":"info","msg":"http request"}`, "field_1": `{"lvl":"info","msg":"http request"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`, "field_2": `{"err":"fatal","fatal":"security threat"}`,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{ metric.New(
Metric(metric.New(
"bigMeasure",
map[string]string{},
map[string]interface{}{
"field_1": `{"lvl":"info","msg":"http request"}`,
"field_2": `{"err":"fatal","fatal":"security threat"}`,
},
time.Unix(0, 0))),
Metric(metric.New(
"bigMeasure", "bigMeasure",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
"msg": "http request", "msg": "http request",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
Metric(metric.New( metric.New(
"bigMeasure", "bigMeasure",
map[string]string{ map[string]string{
"err": "fatal", "err": "fatal",
"fatal": "security threat", "fatal": "security threat",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -380,7 +364,15 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl"}, TagKeys: []string{"lvl"},
}, },
input: Metric( input: metric.New(
"success",
map[string]string{},
map[string]interface{}{
"good": `{"lvl":"info"}`,
"bad": "why",
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"success", "success",
map[string]string{}, map[string]string{},
@ -388,23 +380,14 @@ func TestApply(t *testing.T) {
"good": `{"lvl":"info"}`, "good": `{"lvl":"info"}`,
"bad": "why", "bad": "why",
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{ metric.New(
Metric(metric.New(
"success",
map[string]string{},
map[string]interface{}{
"good": `{"lvl":"info"}`,
"bad": "why",
},
time.Unix(0, 0))),
Metric(metric.New(
"success", "success",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -415,7 +398,16 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl", "thing"}, TagKeys: []string{"lvl", "thing"},
}, },
input: Metric( input: metric.New(
"success",
map[string]string{},
map[string]interface{}{
"bad": "why",
"good": `{"lvl":"info"}`,
"ok": `{"thing":"thang"}`,
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"success", "success",
map[string]string{}, map[string]string{},
@ -424,31 +416,21 @@ func TestApply(t *testing.T) {
"good": `{"lvl":"info"}`, "good": `{"lvl":"info"}`,
"ok": `{"thing":"thang"}`, "ok": `{"thing":"thang"}`,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{ metric.New(
Metric(metric.New(
"success",
map[string]string{},
map[string]interface{}{
"bad": "why",
"good": `{"lvl":"info"}`,
"ok": `{"thing":"thang"}`,
},
time.Unix(0, 0))),
Metric(metric.New(
"success", "success",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
Metric(metric.New( metric.New(
"success", "success",
map[string]string{ map[string]string{
"thing": "thang", "thing": "thang",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -460,19 +442,18 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl"}, TagKeys: []string{"lvl"},
}, },
input: Metric( input: metric.New(
metric.New( "success",
"success", map[string]string{
map[string]string{ "a": "tag",
"a": "tag", },
}, map[string]interface{}{
map[string]interface{}{ "good": `{"lvl":"info"}`,
"good": `{"lvl":"info"}`, "bad": "why",
"bad": "why", },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"success", "success",
map[string]string{ map[string]string{
"a": "tag", "a": "tag",
@ -482,7 +463,7 @@ func TestApply(t *testing.T) {
"good": `{"lvl":"info"}`, "good": `{"lvl":"info"}`,
"bad": "why", "bad": "why",
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
{ {
@ -493,25 +474,24 @@ func TestApply(t *testing.T) {
DataFormat: "json", DataFormat: "json",
TagKeys: []string{"lvl"}, TagKeys: []string{"lvl"},
}, },
input: Metric( input: metric.New(
metric.New( "success",
"success", map[string]string{
map[string]string{ "thing": "tag",
"thing": "tag", },
}, map[string]interface{}{
map[string]interface{}{ "good": `{"lvl":"info"}`,
"good": `{"lvl":"info"}`, "bad": "why",
"bad": "why", },
}, time.Unix(0, 0)),
time.Unix(0, 0))),
expected: []telegraf.Metric{ expected: []telegraf.Metric{
Metric(metric.New( metric.New(
"success", "success",
map[string]string{ map[string]string{
"lvl": "info", "lvl": "info",
}, },
map[string]interface{}{}, map[string]interface{}{},
time.Unix(0, 0))), time.Unix(0, 0)),
}, },
}, },
} }
@ -546,22 +526,21 @@ func TestBadApply(t *testing.T) {
config: parsers.Config{ config: parsers.Config{
DataFormat: "json", DataFormat: "json",
}, },
input: Metric( input: metric.New(
"bad",
map[string]string{},
map[string]interface{}{
"some_field": 5,
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"bad", "bad",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"some_field": 5, "some_field": 5,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{
Metric(metric.New(
"bad",
map[string]string{},
map[string]interface{}{
"some_field": 5,
},
time.Unix(0, 0))),
}, },
}, },
{ {
@ -570,22 +549,21 @@ func TestBadApply(t *testing.T) {
config: parsers.Config{ config: parsers.Config{
DataFormat: "json", DataFormat: "json",
}, },
input: Metric( input: metric.New(
"bad",
map[string]string{},
map[string]interface{}{
"some_field": 5,
},
time.Unix(0, 0)),
expected: []telegraf.Metric{
metric.New( metric.New(
"bad", "bad",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"some_field": 5, "some_field": 5,
}, },
time.Unix(0, 0))), time.Unix(0, 0)),
expected: []telegraf.Metric{
Metric(metric.New(
"bad",
map[string]string{},
map[string]interface{}{
"some_field": 5,
},
time.Unix(0, 0))),
}, },
}, },
} }
@ -626,7 +604,7 @@ func getMetricFieldList(metric telegraf.Metric) interface{} {
} }
func BenchmarkFieldListing(b *testing.B) { func BenchmarkFieldListing(b *testing.B) {
metric := Metric(metric.New( m := metric.New(
"test", "test",
map[string]string{ map[string]string{
"some": "tag", "some": "tag",
@ -640,15 +618,15 @@ func BenchmarkFieldListing(b *testing.B) {
"field5": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "field5": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
"field6": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "field6": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
}, },
time.Unix(0, 0))) time.Unix(0, 0))
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
getMetricFieldList(metric) getMetricFieldList(m)
} }
} }
func BenchmarkFields(b *testing.B) { func BenchmarkFields(b *testing.B) {
metric := Metric(metric.New( m := metric.New(
"test", "test",
map[string]string{ map[string]string{
"some": "tag", "some": "tag",
@ -662,9 +640,9 @@ func BenchmarkFields(b *testing.B) {
"field5": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "field5": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
"field6": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`, "field6": `{"ts":"2018-07-24T19:43:40.275Z","lvl":"info","msg":"http request","method":"POST"}`,
}, },
time.Unix(0, 0))) time.Unix(0, 0))
for n := 0; n < b.N; n++ { for n := 0; n < b.N; n++ {
getMetricFields(metric) getMetricFields(m)
} }
} }

View File

@ -10,7 +10,7 @@ import (
) )
func newM1() telegraf.Metric { func newM1() telegraf.Metric {
m1, _ := metric.New("access_log", m1 := metric.New("access_log",
map[string]string{ map[string]string{
"verb": "GET", "verb": "GET",
"resp_code": "200", "resp_code": "200",
@ -24,7 +24,7 @@ func newM1() telegraf.Metric {
} }
func newM2() telegraf.Metric { func newM2() telegraf.Metric {
m2, _ := metric.New("access_log", m2 := metric.New("access_log",
map[string]string{ map[string]string{
"verb": "GET", "verb": "GET",
"resp_code": "200", "resp_code": "200",

View File

@ -16,7 +16,7 @@ func newMetric(name string, tags map[string]string, fields map[string]interface{
if fields == nil { if fields == nil {
fields = map[string]interface{}{} fields = map[string]interface{}{}
} }
m, _ := metric.New(name, tags, fields, time.Now()) m := metric.New(name, tags, fields, time.Now())
return m return m
} }

View File

@ -14,7 +14,7 @@ import (
func TestSimpleReverseLookup(t *testing.T) { func TestSimpleReverseLookup(t *testing.T) {
now := time.Now() now := time.Now()
m, _ := metric.New("name", map[string]string{ m := metric.New("name", map[string]string{
"dest_ip": "8.8.8.8", "dest_ip": "8.8.8.8",
}, map[string]interface{}{ }, map[string]interface{}{
"source_ip": "127.0.0.1", "source_ip": "127.0.0.1",

View File

@ -15,10 +15,7 @@ func newMetric(_ *starlark.Thread, _ *starlark.Builtin, args starlark.Tuple, kwa
return nil, err return nil, err
} }
m, err := metric.New(string(name), nil, nil, time.Now()) m := metric.New(string(name), nil, nil, time.Now())
if err != nil {
return nil, err
}
return &Metric{metric: m}, nil return &Metric{metric: m}, nil
} }

View File

@ -12,7 +12,7 @@ import (
) )
func newM1() telegraf.Metric { func newM1() telegraf.Metric {
m1, _ := metric.New("IIS_log", m1 := metric.New("IIS_log",
map[string]string{ map[string]string{
"verb": "GET", "verb": "GET",
"s-computername": "MIXEDCASE_hostname", "s-computername": "MIXEDCASE_hostname",
@ -27,7 +27,7 @@ func newM1() telegraf.Metric {
} }
func newM2() telegraf.Metric { func newM2() telegraf.Metric {
m1, _ := metric.New("IIS_log", m1 := metric.New("IIS_log",
map[string]string{ map[string]string{
"verb": "GET", "verb": "GET",
"S-ComputerName": "MIXEDCASE_hostname", "S-ComputerName": "MIXEDCASE_hostname",
@ -795,7 +795,7 @@ func TestMultipleConversions(t *testing.T) {
}, },
} }
m, _ := metric.New("IIS_log", m := metric.New("IIS_log",
map[string]string{ map[string]string{
"verb": "GET", "verb": "GET",
"resp_code": "200", "resp_code": "200",
@ -856,7 +856,7 @@ func TestReadmeExample(t *testing.T) {
}, },
} }
m, _ := metric.New("iis_log", m := metric.New("iis_log",
map[string]string{ map[string]string{
"verb": "get", "verb": "get",
"uri_stem": "/API/HealthCheck", "uri_stem": "/API/HealthCheck",
@ -895,7 +895,7 @@ func TestReadmeExample(t *testing.T) {
func newMetric(name string) telegraf.Metric { func newMetric(name string) telegraf.Metric {
tags := map[string]string{} tags := map[string]string{}
fields := map[string]interface{}{} fields := map[string]interface{}{}
m, _ := metric.New(name, tags, fields, time.Now()) m := metric.New(name, tags, fields, time.Now())
return m return m
} }

View File

@ -16,7 +16,7 @@ func MustMetric(name string, tags map[string]string, fields map[string]interface
if fields == nil { if fields == nil {
fields = map[string]interface{}{} fields = map[string]interface{}{}
} }
m, _ := metric.New(name, tags, fields, metricTime) m := metric.New(name, tags, fields, metricTime)
return m return m
} }

View File

@ -1,13 +1,14 @@
package topk package topk
import ( import (
"time"
"github.com/influxdata/telegraf" "github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
"time"
) )
///// Test set 1 ///// ///// Test set 1 /////
var metric11, _ = metric.New( var metric11 = metric.New(
"m1", "m1",
map[string]string{"tag_name": "tag_value1"}, map[string]string{"tag_name": "tag_value1"},
map[string]interface{}{ map[string]interface{}{
@ -17,7 +18,7 @@ var metric11, _ = metric.New(
time.Now(), time.Now(),
) )
var metric12, _ = metric.New( var metric12 = metric.New(
"m1", "m1",
map[string]string{"tag_name": "tag_value1"}, map[string]string{"tag_name": "tag_value1"},
map[string]interface{}{ map[string]interface{}{
@ -26,7 +27,7 @@ var metric12, _ = metric.New(
time.Now(), time.Now(),
) )
var metric13, _ = metric.New( var metric13 = metric.New(
"m1", "m1",
map[string]string{"tag_name": "tag_value1"}, map[string]string{"tag_name": "tag_value1"},
map[string]interface{}{ map[string]interface{}{
@ -36,7 +37,7 @@ var metric13, _ = metric.New(
time.Now(), time.Now(),
) )
var metric14, _ = metric.New( var metric14 = metric.New(
"m1", "m1",
map[string]string{"tag_name": "tag_value1"}, map[string]string{"tag_name": "tag_value1"},
map[string]interface{}{ map[string]interface{}{
@ -46,7 +47,7 @@ var metric14, _ = metric.New(
time.Now(), time.Now(),
) )
var metric15, _ = metric.New( var metric15 = metric.New(
"m1", "m1",
map[string]string{"tag_name": "tag_value1"}, map[string]string{"tag_name": "tag_value1"},
map[string]interface{}{ map[string]interface{}{
@ -60,7 +61,7 @@ var metric15, _ = metric.New(
var MetricsSet1 = []telegraf.Metric{metric11, metric12, metric13, metric14, metric15} var MetricsSet1 = []telegraf.Metric{metric11, metric12, metric13, metric14, metric15}
///// Test set 2 ///// ///// Test set 2 /////
var metric21, _ = metric.New( var metric21 = metric.New(
"metric1", "metric1",
map[string]string{ map[string]string{
"id": "1", "id": "1",
@ -77,7 +78,7 @@ var metric21, _ = metric.New(
time.Now(), time.Now(),
) )
var metric22, _ = metric.New( var metric22 = metric.New(
"metric1", "metric1",
map[string]string{ map[string]string{
"id": "2", "id": "2",
@ -93,7 +94,7 @@ var metric22, _ = metric.New(
time.Now(), time.Now(),
) )
var metric23, _ = metric.New( var metric23 = metric.New(
"metric1", "metric1",
map[string]string{ map[string]string{
"id": "3", "id": "3",
@ -110,7 +111,7 @@ var metric23, _ = metric.New(
time.Now(), time.Now(),
) )
var metric24, _ = metric.New( var metric24 = metric.New(
"metric2", "metric2",
map[string]string{ map[string]string{
"id": "4", "id": "4",
@ -126,7 +127,7 @@ var metric24, _ = metric.New(
time.Now(), time.Now(),
) )
var metric25, _ = metric.New( var metric25 = metric.New(
"metric2", "metric2",
map[string]string{ map[string]string{
"id": "5", "id": "5",
@ -143,7 +144,7 @@ var metric25, _ = metric.New(
time.Now(), time.Now(),
) )
var metric26, _ = metric.New( var metric26 = metric.New(
"metric2", "metric2",
map[string]string{ map[string]string{
"id": "6", "id": "6",

View File

@ -312,10 +312,7 @@ func (t *TopK) push() []telegraf.Metric {
result := make([]telegraf.Metric, 0, len(ret)) result := make([]telegraf.Metric, 0, len(ret))
for _, m := range ret { for _, m := range ret {
newMetric, err := metric.New(m.Name(), m.Tags(), m.Fields(), m.Time(), m.Type()) newMetric := metric.New(m.Name(), m.Tags(), m.Fields(), m.Time(), m.Type())
if err != nil {
continue
}
result = append(result, newMetric) result = append(result, newMetric)
} }

View File

@ -12,13 +12,6 @@ import (
"github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/metric"
) )
func MustMetric(v telegraf.Metric, err error) telegraf.Metric {
if err != nil {
panic(err)
}
return v
}
func TestSerializeMetricFloat(t *testing.T) { func TestSerializeMetricFloat(t *testing.T) {
now := time.Now() now := time.Now()
tags := map[string]string{ tags := map[string]string{
@ -27,8 +20,7 @@ func TestSerializeMetricFloat(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
require.NoError(t, err)
testcases := []struct { testcases := []struct {
format format format format
@ -65,8 +57,7 @@ func TestSerializeMetricWithEmptyStringTag(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
require.NoError(t, err)
testcases := []struct { testcases := []struct {
format format format format
@ -103,8 +94,7 @@ func TestSerializeWithSpaces(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle 1": float64(91.5), "usage_idle 1": float64(91.5),
} }
m, err := metric.New("cpu metric", tags, fields, now) m := metric.New("cpu metric", tags, fields, now)
require.NoError(t, err)
testcases := []struct { testcases := []struct {
format format format format
@ -141,8 +131,7 @@ func TestSerializeMetricInt(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(90), "usage_idle": int64(90),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
require.NoError(t, err)
testcases := []struct { testcases := []struct {
format format format format
@ -179,8 +168,7 @@ func TestSerializeMetricString(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": "foobar", "usage_idle": "foobar",
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
testcases := []struct { testcases := []struct {
format format format format
@ -218,8 +206,7 @@ func TestSerializeMetricBool(t *testing.T) {
"java_lang_GarbageCollector_Valid": value, "java_lang_GarbageCollector_Valid": value,
} }
m, err := metric.New("cpu", tags, fields, tim) m := metric.New("cpu", tags, fields, tim)
require.NoError(t, err)
return m return m
} }
@ -267,15 +254,13 @@ func TestSerializeMetricBool(t *testing.T) {
} }
func TestSerializeBatch(t *testing.T) { func TestSerializeBatch(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, m} metrics := []telegraf.Metric{m, m}
@ -315,14 +300,14 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
now := time.Now() now := time.Now()
testcases := []struct { testcases := []struct {
metricFunc func() (telegraf.Metric, error) metricFunc func() telegraf.Metric
format format format format
expected string expected string
replaceChar string replaceChar string
expectedErr bool expectedErr bool
}{ }{
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -333,7 +318,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: DefaultSanitizeReplaceChar, replaceChar: DefaultSanitizeReplaceChar,
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -344,7 +329,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: "_", replaceChar: "_",
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -355,7 +340,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: DefaultSanitizeReplaceChar, replaceChar: DefaultSanitizeReplaceChar,
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -366,7 +351,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: DefaultSanitizeReplaceChar, replaceChar: DefaultSanitizeReplaceChar,
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -377,7 +362,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: DefaultSanitizeReplaceChar, replaceChar: DefaultSanitizeReplaceChar,
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -388,7 +373,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
replaceChar: "_", replaceChar: "_",
}, },
{ {
metricFunc: func() (telegraf.Metric, error) { metricFunc: func() telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
@ -402,8 +387,7 @@ func TestSerializeMetricIsProperlySanitized(t *testing.T) {
for _, tc := range testcases { for _, tc := range testcases {
t.Run(string(tc.format), func(t *testing.T) { t.Run(string(tc.format), func(t *testing.T) {
m, err := tc.metricFunc() m := tc.metricFunc()
require.NoError(t, err)
s, err := NewSerializer(string(tc.format), tc.replaceChar) s, err := NewSerializer(string(tc.format), tc.replaceChar)
if tc.expectedErr { if tc.expectedErr {

View File

@ -32,19 +32,19 @@ const (
) )
func TestGraphiteTags(t *testing.T) { func TestGraphiteTags(t *testing.T) {
m1, _ := metric.New( m1 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1"}, map[string]string{"host": "192.168.0.1"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m2, _ := metric.New( m2 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"host": "192.168.0.1", "afoo": "first", "bfoo": "second"}, map[string]string{"host": "192.168.0.1", "afoo": "first", "bfoo": "second"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC), time.Date(2010, time.November, 10, 23, 0, 0, 0, time.UTC),
) )
m3, _ := metric.New( m3 := metric.New(
"mymeasurement", "mymeasurement",
map[string]string{"afoo": "first", "bfoo": "second"}, map[string]string{"afoo": "first", "bfoo": "second"},
map[string]interface{}{"value": float64(3.14)}, map[string]interface{}{"value": float64(3.14)},
@ -70,13 +70,11 @@ func TestSerializeMetricNoHost(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{} s := GraphiteSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()), fmt.Sprintf("cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()),
@ -97,8 +95,7 @@ func TestSerializeMetricNoHostWithTagSupport(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -106,7 +103,6 @@ func TestSerializeMetricNoHostWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu.usage_idle;cpu=cpu0;datacenter=us-west-2 91.5 %d", now.Unix()), fmt.Sprintf("cpu.usage_idle;cpu=cpu0;datacenter=us-west-2 91.5 %d", now.Unix()),
@ -128,13 +124,11 @@ func TestSerializeMetricHost(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{} s := GraphiteSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()),
@ -156,9 +150,8 @@ func TestSerializeMetricHostWithMultipleTemplates(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m1, err := metric.New("cpu", tags, fields, now) m1 := metric.New("cpu", tags, fields, now)
m2, err := metric.New("new_cpu", tags, fields, now) m2 := metric.New("new_cpu", tags, fields, now)
assert.NoError(t, err)
templates, defaultTemplate, err := InitGraphiteTemplates([]string{ templates, defaultTemplate, err := InitGraphiteTemplates([]string{
"cp* tags.measurement.host.field", "cp* tags.measurement.host.field",
@ -201,9 +194,8 @@ func TestSerializeMetricHostWithMultipleTemplatesWithDefault(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m1, err := metric.New("cpu", tags, fields, now) m1 := metric.New("cpu", tags, fields, now)
m2, err := metric.New("new_cpu", tags, fields, now) m2 := metric.New("new_cpu", tags, fields, now)
assert.NoError(t, err)
templates, defaultTemplate, err := InitGraphiteTemplates([]string{ templates, defaultTemplate, err := InitGraphiteTemplates([]string{
"cp* tags.measurement.host.field", "cp* tags.measurement.host.field",
@ -247,8 +239,7 @@ func TestSerializeMetricHostWithTagSupport(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -256,7 +247,6 @@ func TestSerializeMetricHostWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu.usage_idle;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()), fmt.Sprintf("cpu.usage_idle;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()),
@ -278,13 +268,11 @@ func TestSerializeValueField(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(91.5), "value": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{} s := GraphiteSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()),
@ -302,8 +290,7 @@ func TestSerializeValueFieldWithTagSupport(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(91.5), "value": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -311,7 +298,6 @@ func TestSerializeValueFieldWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()), fmt.Sprintf("cpu;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()),
@ -330,15 +316,13 @@ func TestSerializeValueField2(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(91.5), "value": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "host.field.tags.measurement", Template: "host.field.tags.measurement",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()),
@ -356,15 +340,13 @@ func TestSerializeValueString(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": "asdasd", "value": "asdasd",
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "host.field.tags.measurement", Template: "host.field.tags.measurement",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
assert.Equal(t, "", mS[0]) assert.Equal(t, "", mS[0])
} }
@ -378,8 +360,7 @@ func TestSerializeValueStringWithTagSupport(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": "asdasd", "value": "asdasd",
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -387,7 +368,6 @@ func TestSerializeValueStringWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
assert.Equal(t, "", mS[0]) assert.Equal(t, "", mS[0])
} }
@ -402,15 +382,13 @@ func TestSerializeValueBoolean(t *testing.T) {
"enabled": true, "enabled": true,
"disabled": false, "disabled": false,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "host.field.tags.measurement", Template: "host.field.tags.measurement",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.enabled.cpu0.us-west-2.cpu 1 %d", now.Unix()), fmt.Sprintf("localhost.enabled.cpu0.us-west-2.cpu 1 %d", now.Unix()),
@ -432,8 +410,7 @@ func TestSerializeValueBooleanWithTagSupport(t *testing.T) {
"enabled": true, "enabled": true,
"disabled": false, "disabled": false,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -441,7 +418,6 @@ func TestSerializeValueBooleanWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu.enabled;cpu=cpu0;datacenter=us-west-2;host=localhost 1 %d", now.Unix()), fmt.Sprintf("cpu.enabled;cpu=cpu0;datacenter=us-west-2;host=localhost 1 %d", now.Unix()),
@ -458,8 +434,7 @@ func TestSerializeValueUnsigned(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"free": uint64(42), "free": uint64(42),
} }
m, err := metric.New("mem", tags, fields, now) m := metric.New("mem", tags, fields, now)
require.NoError(t, err)
s := GraphiteSerializer{} s := GraphiteSerializer{}
buf, err := s.Serialize(m) buf, err := s.Serialize(m)
@ -479,15 +454,13 @@ func TestSerializeFieldWithSpaces(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
`field\ with\ spaces`: float64(91.5), `field\ with\ spaces`: float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "host.tags.measurement.field", Template: "host.tags.measurement.field",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu0.us-west-2.cpu.field_with_spaces 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu0.us-west-2.cpu.field_with_spaces 91.5 %d", now.Unix()),
@ -505,8 +478,7 @@ func TestSerializeFieldWithSpacesWithTagSupport(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
`field\ with\ spaces`: float64(91.5), `field\ with\ spaces`: float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -514,7 +486,6 @@ func TestSerializeFieldWithSpacesWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu.field_with_spaces;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()), fmt.Sprintf("cpu.field_with_spaces;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()),
@ -533,15 +504,13 @@ func TestSerializeTagWithSpaces(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
`field_with_spaces`: float64(91.5), `field_with_spaces`: float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "host.tags.measurement.field", Template: "host.tags.measurement.field",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu_0.us-west-2.cpu.field_with_spaces 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu_0.us-west-2.cpu.field_with_spaces 91.5 %d", now.Unix()),
@ -559,8 +528,7 @@ func TestSerializeTagWithSpacesWithTagSupport(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
`field_with_spaces`: float64(91.5), `field_with_spaces`: float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
TagSupport: true, TagSupport: true,
@ -568,7 +536,6 @@ func TestSerializeTagWithSpacesWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("cpu.field_with_spaces;cpu=cpu_0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()), fmt.Sprintf("cpu.field_with_spaces;cpu=cpu_0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()),
@ -587,15 +554,13 @@ func TestSerializeValueField3(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(91.5), "value": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: "field.host.tags.measurement", Template: "field.host.tags.measurement",
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()), fmt.Sprintf("localhost.cpu0.us-west-2.cpu 91.5 %d", now.Unix()),
@ -614,15 +579,13 @@ func TestSerializeValueField5(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": float64(91.5), "value": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Template: template5, Template: template5,
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("localhost.us-west-2.cpu0.cpu 91.5 %d", now.Unix()), fmt.Sprintf("localhost.us-west-2.cpu0.cpu 91.5 %d", now.Unix()),
@ -641,13 +604,11 @@ func TestSerializeMetricPrefix(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{Prefix: "prefix"} s := GraphiteSerializer{Prefix: "prefix"}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("prefix.localhost.cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()), fmt.Sprintf("prefix.localhost.cpu0.us-west-2.cpu.usage_idle 91.5 %d", now.Unix()),
@ -669,8 +630,7 @@ func TestSerializeMetricPrefixWithTagSupport(t *testing.T) {
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
"usage_busy": float64(8.5), "usage_busy": float64(8.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := GraphiteSerializer{ s := GraphiteSerializer{
Prefix: "prefix", Prefix: "prefix",
@ -679,7 +639,6 @@ func TestSerializeMetricPrefixWithTagSupport(t *testing.T) {
} }
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{ expS := []string{
fmt.Sprintf("prefix.cpu.usage_idle;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()), fmt.Sprintf("prefix.cpu.usage_idle;cpu=cpu0;datacenter=us-west-2;host=localhost 91.5 %d", now.Unix()),
@ -699,8 +658,7 @@ func TestSerializeBucketNameNoHost(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), "", "") mS := SerializeBucketName(m.Name(), m.Tags(), "", "")
@ -713,8 +671,7 @@ func TestSerializeBucketNameHost(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), "", "") mS := SerializeBucketName(m.Name(), m.Tags(), "", "")
@ -727,8 +684,7 @@ func TestSerializeBucketNamePrefix(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), "", "prefix") mS := SerializeBucketName(m.Name(), m.Tags(), "", "prefix")
@ -741,8 +697,7 @@ func TestTemplate1(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), template1, "") mS := SerializeBucketName(m.Name(), m.Tags(), template1, "")
@ -755,8 +710,7 @@ func TestTemplate2(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), template2, "") mS := SerializeBucketName(m.Name(), m.Tags(), template2, "")
@ -769,8 +723,7 @@ func TestTemplate3(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), template3, "") mS := SerializeBucketName(m.Name(), m.Tags(), template3, "")
@ -783,8 +736,7 @@ func TestTemplate4(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), template4, "") mS := SerializeBucketName(m.Name(), m.Tags(), template4, "")
@ -797,8 +749,7 @@ func TestTemplate6(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", defaultTags, fields, now) m := metric.New("cpu", defaultTags, fields, now)
assert.NoError(t, err)
mS := SerializeBucketName(m.Name(), m.Tags(), template6, "") mS := SerializeBucketName(m.Name(), m.Tags(), template6, "")
@ -890,8 +841,7 @@ func TestClean(t *testing.T) {
s := GraphiteSerializer{} s := GraphiteSerializer{}
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m, err := metric.New(tt.metricName, tt.tags, tt.fields, now) m := metric.New(tt.metricName, tt.tags, tt.fields, now)
assert.NoError(t, err)
actual, _ := s.Serialize(m) actual, _ := s.Serialize(m)
require.Equal(t, tt.expected, string(actual)) require.Equal(t, tt.expected, string(actual))
}) })
@ -985,8 +935,7 @@ func TestCleanWithTagsSupport(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m, err := metric.New(tt.metricName, tt.tags, tt.fields, now) m := metric.New(tt.metricName, tt.tags, tt.fields, now)
assert.NoError(t, err)
actual, _ := s.Serialize(m) actual, _ := s.Serialize(m)
require.Equal(t, tt.expected, string(actual)) require.Equal(t, tt.expected, string(actual))
}) })
@ -1014,8 +963,7 @@ func TestSerializeBatch(t *testing.T) {
s := GraphiteSerializer{} s := GraphiteSerializer{}
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m, err := metric.New(tt.metricName, tt.tags, tt.fields, now) m := metric.New(tt.metricName, tt.tags, tt.fields, now)
assert.NoError(t, err)
actual, _ := s.SerializeBatch([]telegraf.Metric{m, m}) actual, _ := s.SerializeBatch([]telegraf.Metric{m, m})
require.Equal(t, tt.expected, string(actual)) require.Equal(t, tt.expected, string(actual))
}) })
@ -1046,8 +994,7 @@ func TestSerializeBatchWithTagsSupport(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m, err := metric.New(tt.metricName, tt.tags, tt.fields, now) m := metric.New(tt.metricName, tt.tags, tt.fields, now)
assert.NoError(t, err)
actual, _ := s.SerializeBatch([]telegraf.Metric{m, m}) actual, _ := s.SerializeBatch([]telegraf.Metric{m, m})
require.Equal(t, tt.expected, string(actual)) require.Equal(t, tt.expected, string(actual))
}) })

View File

@ -10,13 +10,6 @@ import (
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
func MustMetric(v telegraf.Metric, err error) telegraf.Metric {
if err != nil {
panic(err)
}
return v
}
var tests = []struct { var tests = []struct {
name string name string
maxBytes int maxBytes int
@ -27,506 +20,446 @@ var tests = []struct {
}{ }{
{ {
name: "minimal", name: "minimal",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42 0\n"), output: []byte("cpu value=42 0\n"),
}, },
{ {
name: "multiple tags", name: "multiple tags",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": "localhost",
"host": "localhost", "cpu": "CPU0",
"cpu": "CPU0", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu,cpu=CPU0,host=localhost value=42 0\n"), output: []byte("cpu,cpu=CPU0,host=localhost value=42 0\n"),
}, },
{ {
name: "multiple fields", name: "multiple fields",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "x": 42.0,
"x": 42.0, "y": 42.0,
"y": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu x=42,y=42 0\n"), output: []byte("cpu x=42,y=42 0\n"),
}, },
{ {
name: "float NaN", name: "float NaN",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "x": math.NaN(),
"x": math.NaN(), "y": 42,
"y": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu y=42i 0\n"), output: []byte("cpu y=42i 0\n"),
}, },
{ {
name: "float NaN only", name: "float NaN only",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": math.NaN(),
"value": math.NaN(), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
errReason: NoFields, errReason: NoFields,
}, },
{ {
name: "float Inf", name: "float Inf",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": math.Inf(1),
"value": math.Inf(1), "y": 42,
"y": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu y=42i 0\n"), output: []byte("cpu y=42i 0\n"),
}, },
{ {
name: "integer field", name: "integer field",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42i 0\n"), output: []byte("cpu value=42i 0\n"),
}, },
{ {
name: "integer field 64-bit", name: "integer field 64-bit",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": int64(123456789012345),
"value": int64(123456789012345), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=123456789012345i 0\n"), output: []byte("cpu value=123456789012345i 0\n"),
}, },
{ {
name: "uint field", name: "uint field",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(42),
"value": uint64(42), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42u 0\n"), output: []byte("cpu value=42u 0\n"),
typeSupport: UintSupport, typeSupport: UintSupport,
}, },
{ {
name: "uint field max value", name: "uint field max value",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(18446744073709551615),
"value": uint64(18446744073709551615), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=18446744073709551615u 0\n"), output: []byte("cpu value=18446744073709551615u 0\n"),
typeSupport: UintSupport, typeSupport: UintSupport,
}, },
{ {
name: "uint field no uint support", name: "uint field no uint support",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(42),
"value": uint64(42), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42i 0\n"), output: []byte("cpu value=42i 0\n"),
}, },
{ {
name: "uint field no uint support overflow", name: "uint field no uint support overflow",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": uint64(18446744073709551615),
"value": uint64(18446744073709551615), },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=9223372036854775807i 0\n"), output: []byte("cpu value=9223372036854775807i 0\n"),
}, },
{ {
name: "bool field", name: "bool field",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": true,
"value": true, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=true 0\n"), output: []byte("cpu value=true 0\n"),
}, },
{ {
name: "string field", name: "string field",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": "howdy",
"value": "howdy", },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=\"howdy\" 0\n"), output: []byte("cpu value=\"howdy\" 0\n"),
}, },
{ {
name: "timestamp", name: "timestamp",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(1519194109, 42),
time.Unix(1519194109, 42),
),
), ),
output: []byte("cpu value=42 1519194109000000042\n"), output: []byte("cpu value=42 1519194109000000042\n"),
}, },
{ {
name: "split fields exact", name: "split fields exact",
maxBytes: 33, maxBytes: 33,
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "abc": 123,
"abc": 123, "def": 456,
"def": 456, },
}, time.Unix(1519194109, 42),
time.Unix(1519194109, 42),
),
), ),
output: []byte("cpu abc=123i 1519194109000000042\ncpu def=456i 1519194109000000042\n"), output: []byte("cpu abc=123i 1519194109000000042\ncpu def=456i 1519194109000000042\n"),
}, },
{ {
name: "split fields extra", name: "split fields extra",
maxBytes: 34, maxBytes: 34,
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "abc": 123,
"abc": 123, "def": 456,
"def": 456, },
}, time.Unix(1519194109, 42),
time.Unix(1519194109, 42),
),
), ),
output: []byte("cpu abc=123i 1519194109000000042\ncpu def=456i 1519194109000000042\n"), output: []byte("cpu abc=123i 1519194109000000042\ncpu def=456i 1519194109000000042\n"),
}, },
{ {
name: "split_fields_overflow", name: "split_fields_overflow",
maxBytes: 43, maxBytes: 43,
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "abc": 123,
"abc": 123, "def": 456,
"def": 456, "ghi": 789,
"ghi": 789, "jkl": 123,
"jkl": 123, },
}, time.Unix(1519194109, 42),
time.Unix(1519194109, 42),
),
), ),
output: []byte("cpu abc=123i,def=456i 1519194109000000042\ncpu ghi=789i,jkl=123i 1519194109000000042\n"), output: []byte("cpu abc=123i,def=456i 1519194109000000042\ncpu ghi=789i,jkl=123i 1519194109000000042\n"),
}, },
{ {
name: "name newline", name: "name newline",
input: MustMetric( input: metric.New(
metric.New( "c\npu",
"c\npu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("c\\npu value=42i 0\n"), output: []byte("c\\npu value=42i 0\n"),
}, },
{ {
name: "tag newline", name: "tag newline",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": "x\ny",
"host": "x\ny", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu,host=x\\ny value=42i 0\n"), output: []byte("cpu,host=x\\ny value=42i 0\n"),
}, },
{ {
name: "empty tag value is removed", name: "empty tag value is removed",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "host": "",
"host": "", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42i 0\n"), output: []byte("cpu value=42i 0\n"),
}, },
{ {
name: "empty tag key is removed", name: "empty tag key is removed",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{
map[string]string{ "": "example.org",
"": "example.org", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=42i 0\n"), output: []byte("cpu value=42i 0\n"),
}, },
{ {
name: "tag value ends with backslash is trimmed", name: "tag value ends with backslash is trimmed",
input: MustMetric( input: metric.New(
metric.New( "disk",
"disk", map[string]string{
map[string]string{ "path": `C:\`,
"path": `C:\`, },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("disk,path=C: value=42i 0\n"), output: []byte("disk,path=C: value=42i 0\n"),
}, },
{ {
name: "tag key ends with backslash is trimmed", name: "tag key ends with backslash is trimmed",
input: MustMetric( input: metric.New(
metric.New( "disk",
"disk", map[string]string{
map[string]string{ `path\`: "/",
`path\`: "/", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("disk,path=/ value=42i 0\n"), output: []byte("disk,path=/ value=42i 0\n"),
}, },
{ {
name: "tag key backslash is trimmed and removed", name: "tag key backslash is trimmed and removed",
input: MustMetric( input: metric.New(
metric.New( "disk",
"disk", map[string]string{
map[string]string{ `\`: "example.org",
`\`: "example.org", },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("disk value=42i 0\n"), output: []byte("disk value=42i 0\n"),
}, },
{ {
name: "tag value backslash is trimmed and removed", name: "tag value backslash is trimmed and removed",
input: MustMetric( input: metric.New(
metric.New( "disk",
"disk", map[string]string{
map[string]string{ "host": `\`,
"host": `\`, },
}, map[string]interface{}{
map[string]interface{}{ "value": 42,
"value": 42, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("disk value=42i 0\n"), output: []byte("disk value=42i 0\n"),
}, },
{ {
name: "string newline", name: "string newline",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": "x\ny",
"value": "x\ny", },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
output: []byte("cpu value=\"x\ny\" 0\n"), output: []byte("cpu value=\"x\ny\" 0\n"),
}, },
{ {
name: "need more space", name: "need more space",
maxBytes: 32, maxBytes: 32,
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "abc": 123,
"abc": 123, "def": 456,
"def": 456, },
}, time.Unix(1519194109, 42),
time.Unix(1519194109, 42),
),
), ),
output: nil, output: nil,
errReason: NeedMoreSpace, errReason: NeedMoreSpace,
}, },
{ {
name: "no fields", name: "no fields",
input: MustMetric( input: metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{},
map[string]interface{}{}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
errReason: NoFields, errReason: NoFields,
}, },
{ {
name: "procstat", name: "procstat",
input: MustMetric( input: metric.New(
metric.New( "procstat",
"procstat", map[string]string{
map[string]string{ "exe": "bash",
"exe": "bash", "process_name": "bash",
"process_name": "bash", },
}, map[string]interface{}{
map[string]interface{}{ "cpu_time": 0,
"cpu_time": 0, "cpu_time_guest": float64(0),
"cpu_time_guest": float64(0), "cpu_time_guest_nice": float64(0),
"cpu_time_guest_nice": float64(0), "cpu_time_idle": float64(0),
"cpu_time_idle": float64(0), "cpu_time_iowait": float64(0),
"cpu_time_iowait": float64(0), "cpu_time_irq": float64(0),
"cpu_time_irq": float64(0), "cpu_time_nice": float64(0),
"cpu_time_nice": float64(0), "cpu_time_soft_irq": float64(0),
"cpu_time_soft_irq": float64(0), "cpu_time_steal": float64(0),
"cpu_time_steal": float64(0), "cpu_time_system": float64(0),
"cpu_time_system": float64(0), "cpu_time_user": float64(0.02),
"cpu_time_user": float64(0.02), "cpu_usage": float64(0),
"cpu_usage": float64(0), "involuntary_context_switches": 2,
"involuntary_context_switches": 2, "memory_data": 1576960,
"memory_data": 1576960, "memory_locked": 0,
"memory_locked": 0, "memory_rss": 5103616,
"memory_rss": 5103616, "memory_stack": 139264,
"memory_stack": 139264, "memory_swap": 0,
"memory_swap": 0, "memory_vms": 21659648,
"memory_vms": 21659648, "nice_priority": 20,
"nice_priority": 20, "num_fds": 4,
"num_fds": 4, "num_threads": 1,
"num_threads": 1, "pid": 29417,
"pid": 29417, "read_bytes": 0,
"read_bytes": 0, "read_count": 259,
"read_count": 259, "realtime_priority": 0,
"realtime_priority": 0, "rlimit_cpu_time_hard": 2147483647,
"rlimit_cpu_time_hard": 2147483647, "rlimit_cpu_time_soft": 2147483647,
"rlimit_cpu_time_soft": 2147483647, "rlimit_file_locks_hard": 2147483647,
"rlimit_file_locks_hard": 2147483647, "rlimit_file_locks_soft": 2147483647,
"rlimit_file_locks_soft": 2147483647, "rlimit_memory_data_hard": 2147483647,
"rlimit_memory_data_hard": 2147483647, "rlimit_memory_data_soft": 2147483647,
"rlimit_memory_data_soft": 2147483647, "rlimit_memory_locked_hard": 65536,
"rlimit_memory_locked_hard": 65536, "rlimit_memory_locked_soft": 65536,
"rlimit_memory_locked_soft": 65536, "rlimit_memory_rss_hard": 2147483647,
"rlimit_memory_rss_hard": 2147483647, "rlimit_memory_rss_soft": 2147483647,
"rlimit_memory_rss_soft": 2147483647, "rlimit_memory_stack_hard": 2147483647,
"rlimit_memory_stack_hard": 2147483647, "rlimit_memory_stack_soft": 8388608,
"rlimit_memory_stack_soft": 8388608, "rlimit_memory_vms_hard": 2147483647,
"rlimit_memory_vms_hard": 2147483647, "rlimit_memory_vms_soft": 2147483647,
"rlimit_memory_vms_soft": 2147483647, "rlimit_nice_priority_hard": 0,
"rlimit_nice_priority_hard": 0, "rlimit_nice_priority_soft": 0,
"rlimit_nice_priority_soft": 0, "rlimit_num_fds_hard": 4096,
"rlimit_num_fds_hard": 4096, "rlimit_num_fds_soft": 1024,
"rlimit_num_fds_soft": 1024, "rlimit_realtime_priority_hard": 0,
"rlimit_realtime_priority_hard": 0, "rlimit_realtime_priority_soft": 0,
"rlimit_realtime_priority_soft": 0, "rlimit_signals_pending_hard": 78994,
"rlimit_signals_pending_hard": 78994, "rlimit_signals_pending_soft": 78994,
"rlimit_signals_pending_soft": 78994, "signals_pending": 0,
"signals_pending": 0, "voluntary_context_switches": 42,
"voluntary_context_switches": 42, "write_bytes": 106496,
"write_bytes": 106496, "write_count": 35,
"write_count": 35, },
}, time.Unix(0, 1517620624000000000),
time.Unix(0, 1517620624000000000),
),
), ),
output: []byte("procstat,exe=bash,process_name=bash cpu_time=0i,cpu_time_guest=0,cpu_time_guest_nice=0,cpu_time_idle=0,cpu_time_iowait=0,cpu_time_irq=0,cpu_time_nice=0,cpu_time_soft_irq=0,cpu_time_steal=0,cpu_time_system=0,cpu_time_user=0.02,cpu_usage=0,involuntary_context_switches=2i,memory_data=1576960i,memory_locked=0i,memory_rss=5103616i,memory_stack=139264i,memory_swap=0i,memory_vms=21659648i,nice_priority=20i,num_fds=4i,num_threads=1i,pid=29417i,read_bytes=0i,read_count=259i,realtime_priority=0i,rlimit_cpu_time_hard=2147483647i,rlimit_cpu_time_soft=2147483647i,rlimit_file_locks_hard=2147483647i,rlimit_file_locks_soft=2147483647i,rlimit_memory_data_hard=2147483647i,rlimit_memory_data_soft=2147483647i,rlimit_memory_locked_hard=65536i,rlimit_memory_locked_soft=65536i,rlimit_memory_rss_hard=2147483647i,rlimit_memory_rss_soft=2147483647i,rlimit_memory_stack_hard=2147483647i,rlimit_memory_stack_soft=8388608i,rlimit_memory_vms_hard=2147483647i,rlimit_memory_vms_soft=2147483647i,rlimit_nice_priority_hard=0i,rlimit_nice_priority_soft=0i,rlimit_num_fds_hard=4096i,rlimit_num_fds_soft=1024i,rlimit_realtime_priority_hard=0i,rlimit_realtime_priority_soft=0i,rlimit_signals_pending_hard=78994i,rlimit_signals_pending_soft=78994i,signals_pending=0i,voluntary_context_switches=42i,write_bytes=106496i,write_count=35i 1517620624000000000\n"), output: []byte("procstat,exe=bash,process_name=bash cpu_time=0i,cpu_time_guest=0,cpu_time_guest_nice=0,cpu_time_idle=0,cpu_time_iowait=0,cpu_time_irq=0,cpu_time_nice=0,cpu_time_soft_irq=0,cpu_time_steal=0,cpu_time_system=0,cpu_time_user=0.02,cpu_usage=0,involuntary_context_switches=2i,memory_data=1576960i,memory_locked=0i,memory_rss=5103616i,memory_stack=139264i,memory_swap=0i,memory_vms=21659648i,nice_priority=20i,num_fds=4i,num_threads=1i,pid=29417i,read_bytes=0i,read_count=259i,realtime_priority=0i,rlimit_cpu_time_hard=2147483647i,rlimit_cpu_time_soft=2147483647i,rlimit_file_locks_hard=2147483647i,rlimit_file_locks_soft=2147483647i,rlimit_memory_data_hard=2147483647i,rlimit_memory_data_soft=2147483647i,rlimit_memory_locked_hard=65536i,rlimit_memory_locked_soft=65536i,rlimit_memory_rss_hard=2147483647i,rlimit_memory_rss_soft=2147483647i,rlimit_memory_stack_hard=2147483647i,rlimit_memory_stack_soft=8388608i,rlimit_memory_vms_hard=2147483647i,rlimit_memory_vms_soft=2147483647i,rlimit_nice_priority_hard=0i,rlimit_nice_priority_soft=0i,rlimit_num_fds_hard=4096i,rlimit_num_fds_soft=1024i,rlimit_realtime_priority_hard=0i,rlimit_realtime_priority_soft=0i,rlimit_signals_pending_hard=78994i,rlimit_signals_pending_soft=78994i,signals_pending=0i,voluntary_context_switches=42i,write_bytes=106496i,write_count=35i 1517620624000000000\n"),
}, },
@ -565,15 +498,13 @@ func BenchmarkSerializer(b *testing.B) {
} }
func TestSerialize_SerializeBatch(t *testing.T) { func TestSerialize_SerializeBatch(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, m} metrics := []telegraf.Metric{m, m}

View File

@ -24,15 +24,13 @@ func TestReader(t *testing.T) {
maxLineBytes: 4096, maxLineBytes: 4096,
bufferSize: 20, bufferSize: 20,
input: []telegraf.Metric{ input: []telegraf.Metric{
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
expected: []byte("cpu value=42 0\n"), expected: []byte("cpu value=42 0\n"),
@ -42,25 +40,21 @@ func TestReader(t *testing.T) {
maxLineBytes: 4096, maxLineBytes: 4096,
bufferSize: 20, bufferSize: 20,
input: []telegraf.Metric{ input: []telegraf.Metric{
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
expected: []byte("cpu value=42 0\ncpu value=42 0\n"), expected: []byte("cpu value=42 0\ncpu value=42 0\n"),
@ -70,15 +64,13 @@ func TestReader(t *testing.T) {
maxLineBytes: 4096, maxLineBytes: 4096,
bufferSize: 15, bufferSize: 15,
input: []telegraf.Metric{ input: []telegraf.Metric{
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
expected: []byte("cpu value=42 0\n"), expected: []byte("cpu value=42 0\n"),
@ -88,25 +80,21 @@ func TestReader(t *testing.T) {
maxLineBytes: 4096, maxLineBytes: 4096,
bufferSize: 15, bufferSize: 15,
input: []telegraf.Metric{ input: []telegraf.Metric{
MustMetric( metric.New(
metric.New( "",
"", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
expected: []byte("cpu value=42 0\n"), expected: []byte("cpu value=42 0\n"),
@ -116,25 +104,21 @@ func TestReader(t *testing.T) {
maxLineBytes: 4096, maxLineBytes: 4096,
bufferSize: 15, bufferSize: 15,
input: []telegraf.Metric{ input: []telegraf.Metric{
MustMetric( metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
MustMetric( metric.New(
metric.New( "",
"", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
), ),
}, },
expected: []byte("cpu value=42 0\n"), expected: []byte("cpu value=42 0\n"),
@ -169,15 +153,13 @@ func TestReader(t *testing.T) {
} }
func TestZeroLengthBufferNoError(t *testing.T) { func TestZeroLengthBufferNoError(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
serializer := NewSerializer() serializer := NewSerializer()
serializer.SetFieldSortOrder(SortFields) serializer.SetFieldSortOrder(SortFields)
@ -191,71 +173,68 @@ func TestZeroLengthBufferNoError(t *testing.T) {
} }
func BenchmarkReader(b *testing.B) { func BenchmarkReader(b *testing.B) {
m := MustMetric( m := metric.New(
metric.New( "procstat",
"procstat", map[string]string{
map[string]string{ "exe": "bash",
"exe": "bash", "process_name": "bash",
"process_name": "bash", },
}, map[string]interface{}{
map[string]interface{}{ "cpu_time": 0,
"cpu_time": 0, "cpu_time_guest": float64(0),
"cpu_time_guest": float64(0), "cpu_time_guest_nice": float64(0),
"cpu_time_guest_nice": float64(0), "cpu_time_idle": float64(0),
"cpu_time_idle": float64(0), "cpu_time_iowait": float64(0),
"cpu_time_iowait": float64(0), "cpu_time_irq": float64(0),
"cpu_time_irq": float64(0), "cpu_time_nice": float64(0),
"cpu_time_nice": float64(0), "cpu_time_soft_irq": float64(0),
"cpu_time_soft_irq": float64(0), "cpu_time_steal": float64(0),
"cpu_time_steal": float64(0), "cpu_time_system": float64(0),
"cpu_time_system": float64(0), "cpu_time_user": float64(0.02),
"cpu_time_user": float64(0.02), "cpu_usage": float64(0),
"cpu_usage": float64(0), "involuntary_context_switches": 2,
"involuntary_context_switches": 2, "memory_data": 1576960,
"memory_data": 1576960, "memory_locked": 0,
"memory_locked": 0, "memory_rss": 5103616,
"memory_rss": 5103616, "memory_stack": 139264,
"memory_stack": 139264, "memory_swap": 0,
"memory_swap": 0, "memory_vms": 21659648,
"memory_vms": 21659648, "nice_priority": 20,
"nice_priority": 20, "num_fds": 4,
"num_fds": 4, "num_threads": 1,
"num_threads": 1, "pid": 29417,
"pid": 29417, "read_bytes": 0,
"read_bytes": 0, "read_count": 259,
"read_count": 259, "realtime_priority": 0,
"realtime_priority": 0, "rlimit_cpu_time_hard": 2147483647,
"rlimit_cpu_time_hard": 2147483647, "rlimit_cpu_time_soft": 2147483647,
"rlimit_cpu_time_soft": 2147483647, "rlimit_file_locks_hard": 2147483647,
"rlimit_file_locks_hard": 2147483647, "rlimit_file_locks_soft": 2147483647,
"rlimit_file_locks_soft": 2147483647, "rlimit_memory_data_hard": 2147483647,
"rlimit_memory_data_hard": 2147483647, "rlimit_memory_data_soft": 2147483647,
"rlimit_memory_data_soft": 2147483647, "rlimit_memory_locked_hard": 65536,
"rlimit_memory_locked_hard": 65536, "rlimit_memory_locked_soft": 65536,
"rlimit_memory_locked_soft": 65536, "rlimit_memory_rss_hard": 2147483647,
"rlimit_memory_rss_hard": 2147483647, "rlimit_memory_rss_soft": 2147483647,
"rlimit_memory_rss_soft": 2147483647, "rlimit_memory_stack_hard": 2147483647,
"rlimit_memory_stack_hard": 2147483647, "rlimit_memory_stack_soft": 8388608,
"rlimit_memory_stack_soft": 8388608, "rlimit_memory_vms_hard": 2147483647,
"rlimit_memory_vms_hard": 2147483647, "rlimit_memory_vms_soft": 2147483647,
"rlimit_memory_vms_soft": 2147483647, "rlimit_nice_priority_hard": 0,
"rlimit_nice_priority_hard": 0, "rlimit_nice_priority_soft": 0,
"rlimit_nice_priority_soft": 0, "rlimit_num_fds_hard": 4096,
"rlimit_num_fds_hard": 4096, "rlimit_num_fds_soft": 1024,
"rlimit_num_fds_soft": 1024, "rlimit_realtime_priority_hard": 0,
"rlimit_realtime_priority_hard": 0, "rlimit_realtime_priority_soft": 0,
"rlimit_realtime_priority_soft": 0, "rlimit_signals_pending_hard": 78994,
"rlimit_signals_pending_hard": 78994, "rlimit_signals_pending_soft": 78994,
"rlimit_signals_pending_soft": 78994, "signals_pending": 0,
"signals_pending": 0, "voluntary_context_switches": 42,
"voluntary_context_switches": 42, "write_bytes": 106496,
"write_bytes": 106496, "write_count": 35,
"write_count": 35, },
}, time.Unix(0, 1517620624000000000),
time.Unix(0, 1517620624000000000),
),
) )
metrics := make([]telegraf.Metric, 1000) metrics := make([]telegraf.Metric, 1000)
for i := range metrics { for i := range metrics {
metrics[i] = m metrics[i] = m

View File

@ -28,12 +28,11 @@ func TestSerializeMetricFloat(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(0) s, _ := NewSerializer(0)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":91.5},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n") expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":91.5},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n")
assert.Equal(t, string(expS), string(buf)) assert.Equal(t, string(expS), string(buf))
@ -78,15 +77,13 @@ func TestSerialize_TimestampUnits(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(1525478795, 123456789),
time.Unix(1525478795, 123456789),
),
) )
s, _ := NewSerializer(tt.timestampUnits) s, _ := NewSerializer(tt.timestampUnits)
actual, err := s.Serialize(m) actual, err := s.Serialize(m)
@ -104,12 +101,11 @@ func TestSerializeMetricInt(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(90), "usage_idle": int64(90),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(0) s, _ := NewSerializer(0)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":90},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n") expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":90},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n")
@ -124,12 +120,11 @@ func TestSerializeMetricString(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": "foobar", "usage_idle": "foobar",
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(0) s, _ := NewSerializer(0)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":"foobar"},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n") expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":"foobar"},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n")
@ -145,12 +140,11 @@ func TestSerializeMultiFields(t *testing.T) {
"usage_idle": int64(90), "usage_idle": int64(90),
"usage_total": 8559615, "usage_total": 8559615,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(0) s, _ := NewSerializer(0)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":90,"usage_total":8559615},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n") expS := []byte(fmt.Sprintf(`{"fields":{"usage_idle":90,"usage_total":8559615},"name":"cpu","tags":{"cpu":"cpu0"},"timestamp":%d}`, now.Unix()) + "\n")
@ -165,8 +159,7 @@ func TestSerializeMetricWithEscapes(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"U,age=Idle": int64(90), "U,age=Idle": int64(90),
} }
m, err := metric.New("My CPU", tags, fields, now) m := metric.New("My CPU", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(0) s, _ := NewSerializer(0)
buf, err := s.Serialize(m) buf, err := s.Serialize(m)
@ -177,15 +170,13 @@ func TestSerializeMetricWithEscapes(t *testing.T) {
} }
func TestSerializeBatch(t *testing.T) { func TestSerializeBatch(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, m} metrics := []telegraf.Metric{m, m}

View File

@ -10,8 +10,7 @@ import (
) )
func toTelegrafMetric(m Metric) telegraf.Metric { func toTelegrafMetric(m Metric) telegraf.Metric {
tm, _ := metric.New(m.Name, m.Tags, m.Fields, m.Time.time) tm := metric.New(m.Name, m.Tags, m.Fields, m.Time.time)
return tm return tm
} }

View File

@ -27,12 +27,11 @@ func TestSerializeMetricFloat(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer() s, _ := NewSerializer()
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":91.5,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond)))) expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":91.5,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond))))
assert.Equal(t, string(expS), string(buf)) assert.Equal(t, string(expS), string(buf))
@ -67,15 +66,13 @@ func TestSerialize_TimestampUnits(t *testing.T) {
} }
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(1525478795, 123456789),
time.Unix(1525478795, 123456789),
),
) )
s, _ := NewSerializer() s, _ := NewSerializer()
actual, err := s.Serialize(m) actual, err := s.Serialize(m)
@ -93,12 +90,11 @@ func TestSerializeMetricInt(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(90), "usage_idle": int64(90),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer() s, _ := NewSerializer()
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":90,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond)))) expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":90,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond))))
@ -113,12 +109,11 @@ func TestSerializeMetricString(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": "foobar", "usage_idle": "foobar",
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer() s, _ := NewSerializer()
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "null", string(buf)) assert.Equal(t, "null", string(buf))
@ -133,8 +128,7 @@ func TestSerializeMultiFields(t *testing.T) {
"usage_idle": int64(90), "usage_idle": int64(90),
"usage_total": 8559615, "usage_total": 8559615,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
// Sort for predictable field order // Sort for predictable field order
sort.Slice(m.FieldList(), func(i, j int) bool { sort.Slice(m.FieldList(), func(i, j int) bool {
@ -143,7 +137,7 @@ func TestSerializeMultiFields(t *testing.T) {
s, _ := NewSerializer() s, _ := NewSerializer()
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":90,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"},{"metric_type":"usage_total","resource":"","node":"","value":8559615,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond)), (now.UnixNano() / int64(time.Millisecond)))) expS := []byte(fmt.Sprintf(`[{"metric_type":"usage_idle","resource":"","node":"","value":90,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"},{"metric_type":"usage_total","resource":"","node":"","value":8559615,"timestamp":%d,"ci2metric_id":null,"source":"Telegraf"}]`, (now.UnixNano() / int64(time.Millisecond)), (now.UnixNano() / int64(time.Millisecond))))
@ -158,8 +152,7 @@ func TestSerializeMetricWithEscapes(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"U,age=Idle": int64(90), "U,age=Idle": int64(90),
} }
m, err := metric.New("My CPU", tags, fields, now) m := metric.New("My CPU", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer() s, _ := NewSerializer()
buf, err := s.Serialize(m) buf, err := s.Serialize(m)
@ -170,17 +163,14 @@ func TestSerializeMetricWithEscapes(t *testing.T) {
} }
func TestSerializeBatch(t *testing.T) { func TestSerializeBatch(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, m} metrics := []telegraf.Metric{m, m}
s, _ := NewSerializer() s, _ := NewSerializer()
buf, err := s.SerializeBatch(metrics) buf, err := s.SerializeBatch(metrics)

View File

@ -25,12 +25,11 @@ func TestSerializeMetricFloat(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(false, false) s, _ := NewSerializer(false, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":1529875740.819}` expS := `{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":1529875740.819}`
assert.Equal(t, expS, string(buf)) assert.Equal(t, expS, string(buf))
@ -45,12 +44,11 @@ func TestSerializeMetricFloatHec(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(true, false) s, _ := NewSerializer(true, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":1529875740.819,"fields":{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` expS := `{"time":1529875740.819,"fields":{"_value":91.5,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}`
assert.Equal(t, expS, string(buf)) assert.Equal(t, expS, string(buf))
@ -64,12 +62,11 @@ func TestSerializeMetricInt(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(90), "usage_idle": int64(90),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(false, false) s, _ := NewSerializer(false, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` expS := `{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}`
@ -84,12 +81,11 @@ func TestSerializeMetricIntHec(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(90), "usage_idle": int64(90),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(true, false) s, _ := NewSerializer(true, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}` expS := `{"time":0,"fields":{"_value":90,"cpu":"cpu0","metric_name":"cpu.usage_idle"}}`
@ -104,12 +100,11 @@ func TestSerializeMetricBool(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"oomkiller": bool(true), "oomkiller": bool(true),
} }
m, err := metric.New("docker", tags, fields, now) m := metric.New("docker", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(false, false) s, _ := NewSerializer(false, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":1,"container-name":"telegraf-test","metric_name":"docker.oomkiller","time":0}` expS := `{"_value":1,"container-name":"telegraf-test","metric_name":"docker.oomkiller","time":0}`
@ -124,12 +119,11 @@ func TestSerializeMetricBoolHec(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"oomkiller": bool(false), "oomkiller": bool(false),
} }
m, err := metric.New("docker", tags, fields, now) m := metric.New("docker", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(true, false) s, _ := NewSerializer(true, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"time":0,"fields":{"_value":0,"container-name":"telegraf-test","metric_name":"docker.oomkiller"}}` expS := `{"time":0,"fields":{"_value":0,"container-name":"telegraf-test","metric_name":"docker.oomkiller"}}`
@ -145,12 +139,11 @@ func TestSerializeMetricString(t *testing.T) {
"processorType": "ARMv7 Processor rev 4 (v7l)", "processorType": "ARMv7 Processor rev 4 (v7l)",
"usage_idle": int64(5), "usage_idle": int64(5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s, _ := NewSerializer(false, false) s, _ := NewSerializer(false, false)
var buf []byte var buf []byte
buf, err = s.Serialize(m) buf, err := s.Serialize(m)
assert.NoError(t, err) assert.NoError(t, err)
expS := `{"_value":5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}` expS := `{"_value":5,"cpu":"cpu0","metric_name":"cpu.usage_idle","time":0}`
@ -159,25 +152,22 @@ func TestSerializeMetricString(t *testing.T) {
} }
func TestSerializeBatch(t *testing.T) { func TestSerializeBatch(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
n := MustMetric(
metric.New( n := metric.New(
"cpu", "cpu",
map[string]string{}, map[string]string{},
map[string]interface{}{ map[string]interface{}{
"value": 92.0, "value": 92.0,
}, },
time.Unix(0, 0), time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, n} metrics := []telegraf.Metric{m, n}
@ -190,16 +180,14 @@ func TestSerializeBatch(t *testing.T) {
} }
func TestSerializeMulti(t *testing.T) { func TestSerializeMulti(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "user": 42.0,
"user": 42.0, "system": 8.0,
"system": 8.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m} metrics := []telegraf.Metric{m}
@ -212,27 +200,22 @@ func TestSerializeMulti(t *testing.T) {
} }
func TestSerializeBatchHec(t *testing.T) { func TestSerializeBatchHec(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 42.0,
"value": 42.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
n := MustMetric( n := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "value": 92.0,
"value": 92.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m, n} metrics := []telegraf.Metric{m, n}
s, _ := NewSerializer(true, false) s, _ := NewSerializer(true, false)
buf, err := s.SerializeBatch(metrics) buf, err := s.SerializeBatch(metrics)
@ -243,16 +226,14 @@ func TestSerializeBatchHec(t *testing.T) {
} }
func TestSerializeMultiHec(t *testing.T) { func TestSerializeMultiHec(t *testing.T) {
m := MustMetric( m := metric.New(
metric.New( "cpu",
"cpu", map[string]string{},
map[string]string{}, map[string]interface{}{
map[string]interface{}{ "usage": 42.0,
"usage": 42.0, "system": 8.0,
"system": 8.0, },
}, time.Unix(0, 0),
time.Unix(0, 0),
),
) )
metrics := []telegraf.Metric{m} metrics := []telegraf.Metric{m}

View File

@ -178,13 +178,11 @@ func TestSerializeMetricFloat(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": float64(91.5), "usage_idle": float64(91.5),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{} s := WavefrontSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 91.500000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 91.500000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -199,13 +197,11 @@ func TestSerializeMetricInt(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(91), "usage_idle": int64(91),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{} s := WavefrontSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -220,13 +216,11 @@ func TestSerializeMetricBoolTrue(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": true, "usage_idle": true,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{} s := WavefrontSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 1.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 1.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -241,13 +235,11 @@ func TestSerializeMetricBoolFalse(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": false, "usage_idle": false,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{} s := WavefrontSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 0.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"cpu.usage.idle\" 0.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -262,13 +254,11 @@ func TestSerializeMetricFieldValue(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"value": int64(91), "value": int64(91),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{} s := WavefrontSerializer{}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"cpu\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"cpu\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -283,13 +273,11 @@ func TestSerializeMetricPrefix(t *testing.T) {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": int64(91), "usage_idle": int64(91),
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
assert.NoError(t, err)
s := WavefrontSerializer{Prefix: "telegraf."} s := WavefrontSerializer{Prefix: "telegraf."}
buf, _ := s.Serialize(m) buf, _ := s.Serialize(m)
mS := strings.Split(strings.TrimSpace(string(buf)), "\n") mS := strings.Split(strings.TrimSpace(string(buf)), "\n")
assert.NoError(t, err)
expS := []string{fmt.Sprintf("\"telegraf.cpu.usage.idle\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)} expS := []string{fmt.Sprintf("\"telegraf.cpu.usage.idle\" 91.000000 %d source=\"realHost\" \"cpu\"=\"cpu0\"", now.UnixNano()/1000000000)}
assert.Equal(t, expS, mS) assert.Equal(t, expS, mS)
@ -306,10 +294,7 @@ func benchmarkMetrics(b *testing.B) [4]telegraf.Metric {
fields := map[string]interface{}{ fields := map[string]interface{}{
"usage_idle": v, "usage_idle": v,
} }
m, err := metric.New("cpu", tags, fields, now) m := metric.New("cpu", tags, fields, now)
if err != nil {
b.Fatal(err)
}
return m return m
} }
return [4]telegraf.Metric{ return [4]telegraf.Metric{

View File

@ -7,7 +7,6 @@ package selfstat
import ( import (
"hash/fnv" "hash/fnv"
"log"
"sort" "sort"
"sync" "sync"
"time" "time"
@ -96,12 +95,8 @@ func Metrics() []telegraf.Metric {
fields[fieldname] = stat.Get() fields[fieldname] = stat.Get()
j++ j++
} }
metric, err := metric.New(name, tags, fields, now) m := metric.New(name, tags, fields, now)
if err != nil { metrics[i] = m
log.Printf("E! Error creating selfstat metric: %s", err)
continue
}
metrics[i] = metric
i++ i++
} }
} }

View File

@ -185,17 +185,11 @@ func MustMetric(
tm time.Time, tm time.Time,
tp ...telegraf.ValueType, tp ...telegraf.ValueType,
) telegraf.Metric { ) telegraf.Metric {
m, err := metric.New(name, tags, fields, tm, tp...) m := metric.New(name, tags, fields, tm, tp...)
if err != nil {
panic("MustMetric")
}
return m return m
} }
func FromTestMetric(met *Metric) telegraf.Metric { func FromTestMetric(met *Metric) telegraf.Metric {
m, err := metric.New(met.Measurement, met.Tags, met.Fields, met.Time, met.Type) m := metric.New(met.Measurement, met.Tags, met.Fields, met.Time, met.Type)
if err != nil {
panic("MustMetric")
}
return m return m
} }

View File

@ -18,7 +18,7 @@ func TestRequireMetricEqual(t *testing.T) {
{ {
name: "equal metrics should be equal", name: "equal metrics should be equal",
got: func() telegraf.Metric { got: func() telegraf.Metric {
m, _ := metric.New( m := metric.New(
"test", "test",
map[string]string{ map[string]string{
"t1": "v1", "t1": "v1",
@ -34,7 +34,7 @@ func TestRequireMetricEqual(t *testing.T) {
return m return m
}(), }(),
want: func() telegraf.Metric { want: func() telegraf.Metric {
m, _ := metric.New( m := metric.New(
"test", "test",
map[string]string{ map[string]string{
"t1": "v1", "t1": "v1",

View File

@ -56,7 +56,7 @@ func TestMetric(value interface{}, name ...string) telegraf.Metric {
measurement = name[0] measurement = name[0]
} }
tags := map[string]string{"tag1": "value1"} tags := map[string]string{"tag1": "value1"}
pt, _ := metric.New( pt := metric.New(
measurement, measurement,
tags, tags,
map[string]interface{}{"value": value}, map[string]interface{}{"value": value},