Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix the parsing of threshold name tags containing tokens #2515

Merged
merged 3 commits into from
May 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions metrics/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ var ErrMetricNameParsing = errors.New("parsing metric name failed")
// of "key:value" strings. On failure, it returns an error containing the `ErrMetricNameParsing` in its chain.
func ParseMetricName(name string) (string, []string, error) {
openingTokenPos := strings.IndexByte(name, '{')
closingTokenPos := strings.IndexByte(name, '}')
closingTokenPos := strings.LastIndexByte(name, '}')
containsOpeningToken := openingTokenPos != -1
containsClosingToken := closingTokenPos != -1

Expand All @@ -147,37 +147,44 @@ func ParseMetricName(name string) (string, []string, error) {
// its counterpart, the expression is malformed.
if (containsOpeningToken && !containsClosingToken) ||
(!containsOpeningToken && containsClosingToken) {
return "", nil, fmt.Errorf("%w; reason: unmatched opening/close curly brace", ErrMetricNameParsing)
return "", nil, fmt.Errorf(
"%w, metric %q has unmatched opening/close curly brace",
ErrMetricNameParsing, name,
)
}

// If the closing brace token appears before the opening one,
// the expression is malformed
if closingTokenPos < openingTokenPos {
return "", nil, fmt.Errorf("%w; reason: closing curly brace appears before opening one", ErrMetricNameParsing)
return "", nil, fmt.Errorf("%w, metric %q closing curly brace appears before opening one", ErrMetricNameParsing, name)
}

parserFn := func(c rune) bool {
return c == '{' || c == '}'
// If the last character is not a closing brace token,
// the expression is malformed.
if closingTokenPos != (len(name) - 1) {
err := fmt.Errorf(
"%w, metric %q lacks a closing curly brace in its last position",
ErrMetricNameParsing,
name,
)
return "", nil, err
}

// Split the metric_name{tag_key:tag_value,...} expression
// into two "metric_name" and "tag_key:tag_value,..." strings.
parts := strings.FieldsFunc(name, parserFn)
if len(parts) == 0 || len(parts) > 2 {
return "", nil, ErrMetricNameParsing
}

// Split the tag key values
tags := strings.Split(parts[1], ",")
// We already know the position of the opening and closing curly brace
// tokens. Thus, we extract the string in between them, and split its
// content to obtain the tags key values.
tags := strings.Split(name[openingTokenPos+1:closingTokenPos], ",")

// For each tag definition, ensure
// For each tag definition, ensure it is correctly formed
for i, t := range tags {
keyValue := strings.SplitN(t, ":", 2)

if len(keyValue) != 2 || keyValue[1] == "" {
return "", nil, fmt.Errorf("%w; reason: malformed tag expression %q", ErrMetricNameParsing, t)
return "", nil, fmt.Errorf("%w, metric %q tag expression is malformed", ErrMetricNameParsing, t)
}

tags[i] = strings.TrimSpace(t)
}

return parts[0], tags, nil
return name[0:openingTokenPos], tags, nil
}
19 changes: 19 additions & 0 deletions metrics/metric_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,20 @@ func TestParseMetricName(t *testing.T) {
wantTags: []string{"group:::mygroup"},
wantErr: false,
},
{
name: "metric name with valid name and repeated curly braces tokens in tags definition",
metricNameExpression: "http_req_duration{name:http://${}.com}",
wantMetricName: "http_req_duration",
wantTags: []string{"name:http://${}.com"},
wantErr: false,
},
{
name: "metric name with valid name and repeated curly braces and colon tokens in tags definition",
metricNameExpression: "http_req_duration{name:http://${}.com,url:ssh://github.com:grafana/k6}",
wantMetricName: "http_req_duration",
wantTags: []string{"name:http://${}.com", "url:ssh://github.com:grafana/k6"},
wantErr: false,
},
{
name: "metric name with tag definition missing `:value`",
metricNameExpression: "test_metric{easyas}",
Expand Down Expand Up @@ -146,6 +160,11 @@ func TestParseMetricName(t *testing.T) {
metricNameExpression: "test_metric}abc{bar",
wantErr: true,
},
{
name: "metric name with valid name and trailing characters after closing curly brace in tags definition",
metricNameExpression: "test_metric{foo:ba}r",
wantErr: true,
},
}
for _, tt := range tests {
tt := tt
Expand Down
4 changes: 2 additions & 2 deletions metrics/thresholds.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,8 +260,8 @@ var ErrInvalidThreshold = errors.New("invalid threshold")
func (ts *Thresholds) Validate(metricName string, r *Registry) error {
parsedMetricName, _, err := ParseMetricName(metricName)
if err != nil {
err := fmt.Errorf("unable to validate threshold expressions: %w", ErrMetricNameParsing)
return errext.WithExitCodeIfNone(err, exitcodes.InvalidConfig)
parseErr := fmt.Errorf("unable to validate threshold expressions; reason: %w", err)
return errext.WithExitCodeIfNone(parseErr, exitcodes.InvalidConfig)
}

// Obtain the metric the thresholds apply to from the registry.
Expand Down