Skip to content

Commit

Permalink
fix: add support for {{.Labels.<key>}} with dots in key for template (
Browse files Browse the repository at this point in the history
  • Loading branch information
srikanthccv authored Oct 30, 2024
1 parent cc90321 commit 68d25a8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
22 changes: 17 additions & 5 deletions pkg/query-service/rules/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,15 +234,27 @@ func AlertTemplateData(labels map[string]string, value string, threshold string)
// If there is a go template block, it won't be replaced.
// The example for existing go template block is: {{$threshold}} or {{$value}} or any other valid go template syntax.
func (te *TemplateExpander) preprocessTemplate() {
re := regexp.MustCompile(`({{.*?}})|(\$(\w+(?:\.\w+)*))`)
te.text = re.ReplaceAllStringFunc(te.text, func(match string) string {
// Handle the $variable syntax
reDollar := regexp.MustCompile(`({{.*?}})|(\$(\w+(?:\.\w+)*))`)
te.text = reDollar.ReplaceAllStringFunc(te.text, func(match string) string {
if strings.HasPrefix(match, "{{") {
// If it's a Go template block, leave it unchanged
return match
}
// Otherwise, it's our custom $variable syntax
path := strings.Split(match[1:], ".")
return "{{index $labels \"" + strings.Join(path, ".") + "\"}}"
path := match[1:] // Remove the '$'
return fmt.Sprintf(`{{index $labels "%s"}}`, path)
})

// Handle the {{.Labels.service.name}} syntax
reLabels := regexp.MustCompile(`{{\s*\.Labels\.([a-zA-Z0-9_.]+)(.*?)}}`)
te.text = reLabels.ReplaceAllStringFunc(te.text, func(match string) string {
submatches := reLabels.FindStringSubmatch(match)
if len(submatches) < 3 {
return match // Should not happen
}
path := submatches[1]
rest := submatches[2]
return fmt.Sprintf(`{{index .Labels "%s"%s}}`, path, rest)
})
}

Expand Down
11 changes: 11 additions & 0 deletions pkg/query-service/rules/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,14 @@ func TestTemplateExpander_WithMissingKey(t *testing.T) {
}
require.Equal(t, "test exceeds 100 and observed at 200", result)
}

func TestTemplateExpander_WithLablesDotSyntax(t *testing.T) {
defs := "{{$labels := .Labels}}{{$value := .Value}}{{$threshold := .Threshold}}"
data := AlertTemplateData(map[string]string{"service.name": "my-service"}, "200", "100")
expander := NewTemplateExpander(context.Background(), defs+"test {{.Labels.service.name}} exceeds {{$threshold}} and observed at {{$value}}", "test", data, times.Time(time.Now().Unix()), nil)
result, err := expander.Expand()
if err != nil {
t.Fatal(err)
}
require.Equal(t, "test my-service exceeds 100 and observed at 200", result)
}

0 comments on commit 68d25a8

Please sign in to comment.