alert_rule.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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.Name = ruleDef.Name
  51. model.Description = ruleDef.Description
  52. model.Frequency = ruleDef.Frequency
  53. model.Severity = ruleDef.Severity
  54. model.State = ruleDef.State
  55. for _, v := range ruleDef.Settings.Get("notifications").MustArray() {
  56. if id, ok := v.(int64); ok {
  57. model.Notifications = append(model.Notifications, int64(id))
  58. }
  59. }
  60. for index, condition := range ruleDef.Settings.Get("conditions").MustArray() {
  61. conditionModel := simplejson.NewFromAny(condition)
  62. switch conditionModel.Get("type").MustString() {
  63. case "query":
  64. queryCondition, err := NewQueryCondition(conditionModel, index)
  65. if err != nil {
  66. return nil, err
  67. }
  68. model.Conditions = append(model.Conditions, queryCondition)
  69. }
  70. }
  71. if len(model.Conditions) == 0 {
  72. return nil, fmt.Errorf("Alert is missing conditions")
  73. }
  74. return model, nil
  75. }