alerts.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package models
  2. import (
  3. "github.com/grafana/grafana/pkg/components/simplejson"
  4. "time"
  5. )
  6. type AlertRule struct {
  7. Id int64
  8. OrgId int64
  9. DashboardId int64
  10. PanelId int64
  11. Query string
  12. QueryRefId string
  13. WarnLevel string
  14. CritLevel string
  15. Interval string
  16. Title string
  17. Description string
  18. QueryRange string
  19. Aggregator string
  20. DatasourceName string
  21. }
  22. type AlertRuleChange struct {
  23. OrgId int64
  24. AlertId int64
  25. Type string
  26. Created time.Time
  27. }
  28. func (cmd *SaveDashboardCommand) GetAlertModels() *[]AlertRule {
  29. alerts := make([]AlertRule, 0)
  30. for _, rowObj := range cmd.Dashboard.Get("rows").MustArray() {
  31. row := simplejson.NewFromAny(rowObj)
  32. for _, panelObj := range row.Get("panels").MustArray() {
  33. panel := simplejson.NewFromAny(panelObj)
  34. alerting := panel.Get("alerting")
  35. alert := AlertRule{
  36. DashboardId: cmd.Result.Id,
  37. OrgId: cmd.Result.OrgId,
  38. PanelId: panel.Get("id").MustInt64(),
  39. DatasourceName: panel.Get("datasource").MustString(),
  40. Id: alerting.Get("id").MustInt64(),
  41. QueryRefId: alerting.Get("queryRef").MustString(),
  42. WarnLevel: alerting.Get("warnLevel").MustString(),
  43. CritLevel: alerting.Get("critLevel").MustString(),
  44. Interval: alerting.Get("interval").MustString(),
  45. Title: alerting.Get("title").MustString(),
  46. Description: alerting.Get("description").MustString(),
  47. QueryRange: alerting.Get("queryRange").MustString(),
  48. Aggregator: alerting.Get("aggregator").MustString(),
  49. }
  50. for _, targetsObj := range panel.Get("targets").MustArray() {
  51. target := simplejson.NewFromAny(targetsObj)
  52. if target.Get("refId").MustString() == alert.QueryRefId {
  53. targetJson, err := target.MarshalJSON()
  54. if err == nil {
  55. alert.Query = string(targetJson)
  56. }
  57. continue
  58. }
  59. }
  60. if alert.Query != "" {
  61. alerts = append(alerts, alert)
  62. }
  63. }
  64. }
  65. return &alerts
  66. }
  67. // Commands
  68. type SaveAlertsCommand struct {
  69. DashboardId int64
  70. UserId int64
  71. OrgId int64
  72. Alerts *[]AlertRule
  73. }
  74. //Queries
  75. type GetAlertsQuery struct {
  76. OrgId int64
  77. Result []AlertRule
  78. }
  79. type GetAlertById struct {
  80. Id int64
  81. Result AlertRule
  82. }
  83. type GetAlertChangesQuery struct {
  84. OrgId int64
  85. Result []AlertRuleChange
  86. }