alert_rule.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package alerting
  2. import (
  3. "fmt"
  4. "regexp"
  5. "strconv"
  6. "github.com/grafana/grafana/pkg/components/simplejson"
  7. m "github.com/grafana/grafana/pkg/models"
  8. )
  9. type AlertRule struct {
  10. Id int64
  11. OrgId int64
  12. DashboardId int64
  13. PanelId int64
  14. Frequency int64
  15. Name string
  16. Description string
  17. Severity string
  18. Conditions []AlertCondition
  19. Notifications []int64
  20. }
  21. type AlertValidationError struct {
  22. Reason string
  23. }
  24. func (e AlertValidationError) Error() string {
  25. return e.Reason
  26. }
  27. var (
  28. ValueFormatRegex = regexp.MustCompile("^\\d+")
  29. UnitFormatRegex = regexp.MustCompile("\\w{1}$")
  30. )
  31. var unitMultiplier = map[string]int{
  32. "s": 1,
  33. "m": 60,
  34. "h": 3600,
  35. }
  36. func getTimeDurationStringToSeconds(str string) int64 {
  37. multiplier := 1
  38. value, _ := strconv.Atoi(ValueFormatRegex.FindAllString(str, 1)[0])
  39. unit := UnitFormatRegex.FindAllString(str, 1)[0]
  40. if val, ok := unitMultiplier[unit]; ok {
  41. multiplier = val
  42. }
  43. return int64(value * multiplier)
  44. }
  45. func NewAlertRuleFromDBModel(ruleDef *m.Alert) (*AlertRule, error) {
  46. model := &AlertRule{}
  47. model.Id = ruleDef.Id
  48. model.OrgId = ruleDef.OrgId
  49. model.Name = ruleDef.Name
  50. model.Description = ruleDef.Description
  51. model.Frequency = ruleDef.Frequency
  52. model.Severity = ruleDef.Severity
  53. for _, v := range ruleDef.Settings.Get("notifications").MustArray() {
  54. if id, ok := v.(int64); ok {
  55. model.Notifications = append(model.Notifications, int64(id))
  56. }
  57. }
  58. for _, condition := range ruleDef.Settings.Get("conditions").MustArray() {
  59. conditionModel := simplejson.NewFromAny(condition)
  60. switch conditionModel.Get("type").MustString() {
  61. case "query":
  62. queryCondition, err := NewQueryCondition(conditionModel)
  63. if err != nil {
  64. return nil, err
  65. }
  66. model.Conditions = append(model.Conditions, queryCondition)
  67. }
  68. }
  69. if len(model.Conditions) == 0 {
  70. return nil, fmt.Errorf("Alert is missing conditions")
  71. }
  72. return model, nil
  73. }