alerting.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/bus"
  5. "github.com/grafana/grafana/pkg/middleware"
  6. "github.com/grafana/grafana/pkg/models"
  7. )
  8. func ValidateOrgAlert(c *middleware.Context) {
  9. id := c.ParamsInt64(":id")
  10. query := models.GetAlertById{Id: id}
  11. if err := bus.Dispatch(&query); err != nil {
  12. c.JsonApiErr(404, "Alert not found", nil)
  13. return
  14. }
  15. if c.OrgId != query.Result.OrgId {
  16. c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
  17. return
  18. }
  19. }
  20. // GET /api/alert_rule/changes
  21. func GetAlertChanges(c *middleware.Context) Response {
  22. query := models.GetAlertChangesQuery{
  23. OrgId: c.OrgId,
  24. }
  25. if err := bus.Dispatch(&query); err != nil {
  26. return ApiError(500, "List alerts failed", err)
  27. }
  28. return Json(200, query.Result)
  29. }
  30. // GET /api/alert_rule
  31. func GetAlerts(c *middleware.Context) Response {
  32. query := models.GetAlertsQuery{
  33. OrgId: c.OrgId,
  34. }
  35. if err := bus.Dispatch(&query); err != nil {
  36. return ApiError(500, "List alerts failed", err)
  37. }
  38. dashboardIds := make([]int64, 0)
  39. alertDTOs := make([]*dtos.AlertRuleDTO, 0)
  40. for _, alert := range query.Result {
  41. dashboardIds = append(dashboardIds, alert.DashboardId)
  42. alertDTOs = append(alertDTOs, &dtos.AlertRuleDTO{
  43. Id: alert.Id,
  44. DashboardId: alert.DashboardId,
  45. PanelId: alert.PanelId,
  46. Query: alert.Query,
  47. QueryRefId: alert.QueryRefId,
  48. WarnLevel: alert.WarnLevel,
  49. CritLevel: alert.CritLevel,
  50. Interval: alert.Interval,
  51. Title: alert.Title,
  52. Description: alert.Description,
  53. QueryRange: alert.QueryRange,
  54. Aggregator: alert.Aggregator,
  55. })
  56. }
  57. dashboardsQuery := models.GetDashboardsQuery{
  58. DashboardIds: dashboardIds,
  59. }
  60. if err := bus.Dispatch(&dashboardsQuery); err != nil {
  61. return ApiError(500, "List alerts failed", err)
  62. }
  63. //TODO: should be possible to speed this up with lookup table
  64. for _, alert := range alertDTOs {
  65. for _, dash := range *dashboardsQuery.Result {
  66. if alert.DashboardId == dash.Id {
  67. alert.DashbboardUri = "db/" + dash.Slug
  68. }
  69. }
  70. }
  71. return Json(200, alertDTOs)
  72. }
  73. // GET /api/alert_rule/:id
  74. func GetAlert(c *middleware.Context) Response {
  75. id := c.ParamsInt64(":id")
  76. query := models.GetAlertById{Id: id}
  77. if err := bus.Dispatch(&query); err != nil {
  78. return ApiError(500, "List alerts failed", err)
  79. }
  80. return Json(200, &query.Result)
  81. }