Alerting: add YAML support for relative time range (#51694)

This commit is contained in:
Jean-Philippe Quéméner 2022-07-04 12:03:34 +02:00 committed by GitHub
parent 75873d05d7
commit 580c5b6ad2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 2 deletions

View File

@ -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.

View File

@ -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))
}