Skip to content

Commit 94f0598

Browse files
committed
feat(alerting): implemention duration parser
1 parent 2cf7271 commit 94f0598

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

pkg/services/alerting/alert_rule.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ package alerting
22

33
import (
44
"fmt"
5+
"regexp"
6+
"strconv"
57

68
"github.com/grafana/grafana/pkg/components/simplejson"
79
"github.com/grafana/grafana/pkg/services/alerting/transformers"
@@ -26,8 +28,28 @@ type AlertRule struct {
2628
Transformer transformers.Transformer
2729
}
2830

31+
var (
32+
ValueFormatRegex = regexp.MustCompile("^\\d+")
33+
UnitFormatRegex = regexp.MustCompile("\\w{1}$")
34+
)
35+
36+
var unitMultiplier = map[string]int{
37+
"s": 1,
38+
"m": 60,
39+
"h": 3600,
40+
}
41+
2942
func getTimeDurationStringToSeconds(str string) int64 {
30-
return 60
43+
multiplier := 1
44+
45+
value, _ := strconv.Atoi(ValueFormatRegex.FindAllString(str, 1)[0])
46+
unit := UnitFormatRegex.FindAllString(str, 1)[0]
47+
48+
if val, ok := unitMultiplier[unit]; ok {
49+
multiplier = val
50+
}
51+
52+
return int64(value * multiplier)
3153
}
3254

3355
func NewAlertRuleFromDBModel(ruleDef *m.Alert) (*AlertRule, error) {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package alerting
2+
3+
import (
4+
"testing"
5+
6+
. "github.com/smartystreets/goconvey/convey"
7+
)
8+
9+
func TestAlertRuleModel(t *testing.T) {
10+
Convey("Testing alert rule", t, func() {
11+
12+
Convey("Can parse seconds", func() {
13+
seconds := getTimeDurationStringToSeconds("10s")
14+
So(seconds, ShouldEqual, 10)
15+
})
16+
17+
Convey("Can parse minutes", func() {
18+
seconds := getTimeDurationStringToSeconds("10m")
19+
So(seconds, ShouldEqual, 600)
20+
})
21+
22+
Convey("Can parse hours", func() {
23+
seconds := getTimeDurationStringToSeconds("1h")
24+
So(seconds, ShouldEqual, 3600)
25+
})
26+
27+
Convey("defaults to seconds", func() {
28+
seconds := getTimeDurationStringToSeconds("1o")
29+
So(seconds, ShouldEqual, 1)
30+
})
31+
})
32+
}

0 commit comments

Comments
 (0)