feat(alerting): implemention duration parser
This commit is contained in:
@@ -2,6 +2,8 @@ package alerting
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
|
||||
"github.com/grafana/grafana/pkg/components/simplejson"
|
||||
"github.com/grafana/grafana/pkg/services/alerting/transformers"
|
||||
@@ -26,8 +28,28 @@ type AlertRule struct {
|
||||
Transformer transformers.Transformer
|
||||
}
|
||||
|
||||
var (
|
||||
ValueFormatRegex = regexp.MustCompile("^\\d+")
|
||||
UnitFormatRegex = regexp.MustCompile("\\w{1}$")
|
||||
)
|
||||
|
||||
var unitMultiplier = map[string]int{
|
||||
"s": 1,
|
||||
"m": 60,
|
||||
"h": 3600,
|
||||
}
|
||||
|
||||
func getTimeDurationStringToSeconds(str string) int64 {
|
||||
return 60
|
||||
multiplier := 1
|
||||
|
||||
value, _ := strconv.Atoi(ValueFormatRegex.FindAllString(str, 1)[0])
|
||||
unit := UnitFormatRegex.FindAllString(str, 1)[0]
|
||||
|
||||
if val, ok := unitMultiplier[unit]; ok {
|
||||
multiplier = val
|
||||
}
|
||||
|
||||
return int64(value * multiplier)
|
||||
}
|
||||
|
||||
func NewAlertRuleFromDBModel(ruleDef *m.Alert) (*AlertRule, error) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package alerting
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
func TestAlertRuleModel(t *testing.T) {
|
||||
Convey("Testing alert rule", t, func() {
|
||||
|
||||
Convey("Can parse seconds", func() {
|
||||
seconds := getTimeDurationStringToSeconds("10s")
|
||||
So(seconds, ShouldEqual, 10)
|
||||
})
|
||||
|
||||
Convey("Can parse minutes", func() {
|
||||
seconds := getTimeDurationStringToSeconds("10m")
|
||||
So(seconds, ShouldEqual, 600)
|
||||
})
|
||||
|
||||
Convey("Can parse hours", func() {
|
||||
seconds := getTimeDurationStringToSeconds("1h")
|
||||
So(seconds, ShouldEqual, 3600)
|
||||
})
|
||||
|
||||
Convey("defaults to seconds", func() {
|
||||
seconds := getTimeDurationStringToSeconds("1o")
|
||||
So(seconds, ShouldEqual, 1)
|
||||
})
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user