Skip to content

Commit 196509c

Browse files
zan-xhipesparrc
authored andcommitted
Trim null characters in Value data format (influxdata#2049)
* Trim null characters in Value data format Some producers (such as the paho embedded c mqtt client) add a null character "\x00" to the end of a message. The Value parser would fail on any message from such a producer. * Trim whitespace and null in all Value data formats * No unnecessary reassignments in Value data format parser * Update change log for Value data format fix
1 parent 94ce67c commit 196509c

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
### Bugfixes
1010

11+
- [#2049](https://github.com/influxdata/telegraf/pull/2049): Fix the Value data format not trimming null characters from input.
1112
- [#1949](https://github.com/influxdata/telegraf/issues/1949): Fix windows `net` plugin.
1213
- [#1775](https://github.com/influxdata/telegraf/issues/1775): Cache & expire metrics for delivery to prometheus
1314

plugins/parsers/value/parser.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,12 @@ type ValueParser struct {
1717
}
1818

1919
func (v *ValueParser) Parse(buf []byte) ([]telegraf.Metric, error) {
20+
vStr := string(bytes.TrimSpace(bytes.Trim(buf, "\x00")))
21+
2022
// unless it's a string, separate out any fields in the buffer,
2123
// ignore anything but the last.
22-
var vStr string
23-
if v.DataType == "string" {
24-
vStr = strings.TrimSpace(string(buf))
25-
} else {
26-
values := bytes.Fields(buf)
24+
if v.DataType != "string" {
25+
values := strings.Fields(vStr)
2726
if len(values) < 1 {
2827
return []telegraf.Metric{}, nil
2928
}

plugins/parsers/value/parser_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,3 +236,18 @@ func TestParseValidValuesDefaultTags(t *testing.T) {
236236
}, metrics[0].Fields())
237237
assert.Equal(t, map[string]string{"test": "tag"}, metrics[0].Tags())
238238
}
239+
240+
func TestParseValuesWithNullCharacter(t *testing.T) {
241+
parser := ValueParser{
242+
MetricName: "value_test",
243+
DataType: "integer",
244+
}
245+
metrics, err := parser.Parse([]byte("55\x00"))
246+
assert.NoError(t, err)
247+
assert.Len(t, metrics, 1)
248+
assert.Equal(t, "value_test", metrics[0].Name())
249+
assert.Equal(t, map[string]interface{}{
250+
"value": int64(55),
251+
}, metrics[0].Fields())
252+
assert.Equal(t, map[string]string{}, metrics[0].Tags())
253+
}

0 commit comments

Comments
 (0)