From 580c5b6ad260d821b45304dfa073fedfb14d87b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Philippe=20Qu=C3=A9m=C3=A9ner?= Date: Mon, 4 Jul 2022 12:03:34 +0200 Subject: [PATCH] Alerting: add YAML support for relative time range (#51694) --- pkg/services/ngalert/models/alert_query.go | 22 +++++++++++++++++-- .../ngalert/models/alert_rule_test.go | 15 +++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/pkg/services/ngalert/models/alert_query.go b/pkg/services/ngalert/models/alert_query.go index a57ceff1737..503f349362d 100644 --- a/pkg/services/ngalert/models/alert_query.go +++ b/pkg/services/ngalert/models/alert_query.go @@ -40,11 +40,29 @@ func (d *Duration) UnmarshalJSON(b []byte) error { } } +func (d Duration) MarshalYAML() (interface{}, error) { + return time.Duration(d).Seconds(), nil +} + +func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error { + var v interface{} + if err := unmarshal(&v); err != nil { + return err + } + switch value := v.(type) { + case int: + *d = Duration(time.Duration(value) * time.Second) + return nil + default: + return fmt.Errorf("invalid duration %v", v) + } +} + // RelativeTimeRange is the per query start and end time // for requests. type RelativeTimeRange struct { - From Duration `json:"from"` - To Duration `json:"to"` + From Duration `json:"from" yaml:"from"` + To Duration `json:"to" yaml:"to"` } // isValid checks that From duration is greater than To duration. diff --git a/pkg/services/ngalert/models/alert_rule_test.go b/pkg/services/ngalert/models/alert_rule_test.go index 7b8e3ebf9fb..b15ab5bcb2e 100644 --- a/pkg/services/ngalert/models/alert_rule_test.go +++ b/pkg/services/ngalert/models/alert_rule_test.go @@ -11,6 +11,7 @@ import ( "github.com/google/go-cmp/cmp" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "gopkg.in/yaml.v3" "github.com/grafana/grafana/pkg/util" ) @@ -582,3 +583,17 @@ func TestSortByGroupIndex(t *testing.T) { })) }) } + +func TestTimeRangeYAML(t *testing.T) { + yamlRaw := "from: 600\nto: 0\n" + var rtr RelativeTimeRange + err := yaml.Unmarshal([]byte(yamlRaw), &rtr) + require.NoError(t, err) + // nanoseconds + require.Equal(t, Duration(600000000000), rtr.From) + require.Equal(t, Duration(0), rtr.To) + + serialized, err := yaml.Marshal(rtr) + require.NoError(t, err) + require.Equal(t, yamlRaw, string(serialized)) +}