alert_rule.go 2.3 KB

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