Browse Source

feat(alerting): implemention duration parser

bergquist 9 years ago
parent
commit
94f059838c
2 changed files with 55 additions and 1 deletions
  1. 23 1
      pkg/services/alerting/alert_rule.go
  2. 32 0
      pkg/services/alerting/alert_rule_test.go

+ 23 - 1
pkg/services/alerting/alert_rule.go

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

+ 32 - 0
pkg/services/alerting/alert_rule_test.go

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