alert_rule.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. State m.AlertStateType
  18. Severity m.AlertSeverityType
  19. Conditions []AlertCondition
  20. Notifications []int64
  21. }
  22. type AlertValidationError struct {
  23. Reason string
  24. }
  25. func (e AlertValidationError) Error() string {
  26. return e.Reason
  27. }
  28. var (
  29. ValueFormatRegex = regexp.MustCompile("^\\d+")
  30. UnitFormatRegex = regexp.MustCompile("\\w{1}$")
  31. )
  32. var unitMultiplier = map[string]int{
  33. "s": 1,
  34. "m": 60,
  35. "h": 3600,
  36. }
  37. func getTimeDurationStringToSeconds(str string) int64 {
  38. multiplier := 1
  39. value, _ := strconv.Atoi(ValueFormatRegex.FindAllString(str, 1)[0])
  40. unit := UnitFormatRegex.FindAllString(str, 1)[0]
  41. if val, ok := unitMultiplier[unit]; ok {
  42. multiplier = val
  43. }
  44. return int64(value * multiplier)
  45. }
  46. func NewAlertRuleFromDBModel(ruleDef *m.Alert) (*AlertRule, error) {
  47. model := &AlertRule{}
  48. model.Id = ruleDef.Id
  49. model.OrgId = ruleDef.OrgId
  50. model.DashboardId = ruleDef.DashboardId
  51. model.PanelId = ruleDef.PanelId
  52. model.Name = ruleDef.Name
  53. model.Description = ruleDef.Description
  54. model.Frequency = ruleDef.Frequency
  55. model.Severity = ruleDef.Severity
  56. model.State = ruleDef.State
  57. for _, v := range ruleDef.Settings.Get("notifications").MustArray() {
  58. jsonModel := simplejson.NewFromAny(v)
  59. if id, err := jsonModel.Get("id").Int64(); err != nil {
  60. return nil, AlertValidationError{Reason: "Invalid notification schema"}
  61. } else {
  62. model.Notifications = append(model.Notifications, id)
  63. }
  64. }
  65. for index, condition := range ruleDef.Settings.Get("conditions").MustArray() {
  66. conditionModel := simplejson.NewFromAny(condition)
  67. switch conditionModel.Get("type").MustString() {
  68. case "query":
  69. queryCondition, err := NewQueryCondition(conditionModel, index)
  70. if err != nil {
  71. return nil, err
  72. }
  73. model.Conditions = append(model.Conditions, queryCondition)
  74. }
  75. }
  76. if len(model.Conditions) == 0 {
  77. return nil, fmt.Errorf("Alert is missing conditions")
  78. }
  79. return model, nil
  80. }