Alerting: Handle edge cases without panicking during template migration (#76890)

* Handle empty variable, remove panics

* Use fmt.Errorf only where appropriate
pull/77468/head
William Wernert 2 years ago committed by GitHub
parent 087e081c5a
commit e562250f72
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 15
      pkg/services/ngalert/migration/template.go
  2. 6
      pkg/services/ngalert/migration/template_test.go

@ -35,7 +35,7 @@ func (t Token) String() string {
} else if t.IsVariable() {
return t.Variable
} else {
panic("empty token")
return ""
}
}
@ -108,7 +108,7 @@ func tokenizeVariable(in []rune) (Token, int, error) {
)
if !startVariable(in) {
panic("tokenizeVariable called with input that doesn't start with delimiter")
return Token{}, pos, fmt.Errorf("expected '${', got '%s'", string(in[:2]))
}
pos += 2 // seek past opening delimiter
@ -118,11 +118,11 @@ func tokenizeVariable(in []rune) (Token, int, error) {
r = in[pos]
if unicode.IsSpace(r) && r != ' ' {
return Token{}, pos, fmt.Errorf("unexpected whitespace")
return Token{}, pos, errors.New("unexpected whitespace")
}
if startVariable(in[pos:]) {
return Token{}, pos, fmt.Errorf("ambiguous delimiter")
return Token{}, pos, errors.New("ambiguous delimiter")
}
if r == '}' {
@ -139,7 +139,12 @@ func tokenizeVariable(in []rune) (Token, int, error) {
return Token{}, pos, fmt.Errorf("expected '}', got '%c'", r)
}
return Token{Variable: string(runes)}, pos, nil
token := Token{Variable: string(runes)}
if !token.IsVariable() {
return Token{}, pos, errors.New("empty variable")
}
return token, pos, nil
}
func startVariable(in []rune) bool {

@ -303,6 +303,12 @@ func TestMigrateTmpl(t *testing.T) {
expected: withDeduplicateMap("{{$mergedLabels.instance}}{{` is down ${`}}{{$mergedLabels.nestedVar}}}"),
vars: true,
},
{
name: "edge cases",
input: "Test test 123 \n$(metric)\n${.}\n${}\n${Condition[0]}",
expected: withDeduplicateMap("Test test 123 \n$(metric)\n{{index $mergedLabels \".\"}}\n${}\n{{index $mergedLabels \"Condition[0]\"}}"),
vars: true,
},
}
for _, tc := range cases {

Loading…
Cancel
Save