Skip to content

Commit

Permalink
Merge pull request #45 from fujiwara/fix/validate-metric-name
Browse files Browse the repository at this point in the history
metric name is required.
  • Loading branch information
fujiwara authored Apr 5, 2024
2 parents 68bf9c9 + e1f848a commit aa6891e
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 5 deletions.
13 changes: 8 additions & 5 deletions command.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,14 @@ func (p *CommandProbe) Run(_ context.Context) (ms Metrics, err error) {
scanner := bufio.NewScanner(stdout)

if err := cmd.Start(); err != nil {
return ms, errors.Wrap(err, "command execute failed")
return ms, errors.Wrap(err, fmt.Sprintf("command execute failed. %s", strings.Join(p.Command, " ")))
}

for scanner.Scan() {
log.Println("[trace]", scanner.Text())
m, err := parseMetricLine(scanner.Text())
if err != nil {
log.Println("[warn]", err)
log.Printf("[warn] %s failed to parse metric line. %s", strings.Join(p.Command, " "), err)
continue
}
if p.GraphDefs {
Expand Down Expand Up @@ -287,9 +287,12 @@ func parseMetricLine(b string) (Metric, error) {
return Metric{}, errors.New("invalid metric format. insufficient columns")
}
name, value, timestamp := cols[0], cols[1], cols[2]
m := Metric{}
m.Name = name

if name == "" {
return Metric{}, errors.New("invalid metric format. name is empty")
}
m := Metric{
Name: name,
}
if v, err := strconv.ParseFloat(value, 64); err != nil {
return m, fmt.Errorf("invalid metric value: %s", value)
} else {
Expand Down
32 changes: 32 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package maprobe_test

import (
"context"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -85,3 +86,34 @@ func TestCommandFail(t *testing.T) {
t.Errorf("must be failed but got %#v", c)
}
}

var ngInputs = []struct {
Title string
Line string
}{
{
Title: "invalid value",
Line: strings.Join([]string{"test.foo", "x", "1523261168"}, "\t"),
},
{
Title: "invalid timestamp",
Line: strings.Join([]string{"test.foo", "1", "x"}, "\t"),
},
{
Title: "Empty",
Line: "",
},
{
Title: "No name",
Line: strings.Join([]string{"", "1", "1523261168"}, "\t"),
},
}

func TestParseMetricLineNG(t *testing.T) {
for _, c := range ngInputs {
_, err := maprobe.ParseMetricLine(c.Line)
if err == nil {
t.Errorf("%s: must be failed", c.Title)
}
}
}
5 changes: 5 additions & 0 deletions export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package maprobe

var (
ParseMetricLine = parseMetricLine
)

0 comments on commit aa6891e

Please sign in to comment.