alerting.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package api
  2. import (
  3. "fmt"
  4. "github.com/grafana/grafana/pkg/api/dtos"
  5. "github.com/grafana/grafana/pkg/bus"
  6. "github.com/grafana/grafana/pkg/middleware"
  7. "github.com/grafana/grafana/pkg/models"
  8. "github.com/grafana/grafana/pkg/services/alerting"
  9. )
  10. func ValidateOrgAlert(c *middleware.Context) {
  11. id := c.ParamsInt64(":alertId")
  12. query := models.GetAlertByIdQuery{Id: id}
  13. if err := bus.Dispatch(&query); err != nil {
  14. c.JsonApiErr(404, "Alert not found", nil)
  15. return
  16. }
  17. if c.OrgId != query.Result.OrgId {
  18. c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
  19. return
  20. }
  21. }
  22. // GET /api/alerts/rules/
  23. func GetAlerts(c *middleware.Context) Response {
  24. query := models.GetAlertsQuery{
  25. OrgId: c.OrgId,
  26. State: c.QueryStrings("state"),
  27. DashboardId: c.QueryInt64("dashboardId"),
  28. PanelId: c.QueryInt64("panelId"),
  29. }
  30. if err := bus.Dispatch(&query); err != nil {
  31. return ApiError(500, "List alerts failed", err)
  32. }
  33. dashboardIds := make([]int64, 0)
  34. alertDTOs := make([]*dtos.AlertRule, 0)
  35. for _, alert := range query.Result {
  36. dashboardIds = append(dashboardIds, alert.DashboardId)
  37. alertDTOs = append(alertDTOs, &dtos.AlertRule{
  38. Id: alert.Id,
  39. DashboardId: alert.DashboardId,
  40. PanelId: alert.PanelId,
  41. Name: alert.Name,
  42. Message: alert.Message,
  43. State: alert.State,
  44. EvalDate: alert.EvalDate,
  45. NewStateDate: alert.NewStateDate,
  46. ExecutionError: alert.ExecutionError,
  47. })
  48. }
  49. dashboardsQuery := models.GetDashboardsQuery{
  50. DashboardIds: dashboardIds,
  51. }
  52. if len(alertDTOs) > 0 {
  53. if err := bus.Dispatch(&dashboardsQuery); err != nil {
  54. return ApiError(500, "List alerts failed", err)
  55. }
  56. }
  57. //TODO: should be possible to speed this up with lookup table
  58. for _, alert := range alertDTOs {
  59. for _, dash := range dashboardsQuery.Result {
  60. if alert.DashboardId == dash.Id {
  61. alert.DashbboardUri = "db/" + dash.Slug
  62. }
  63. }
  64. }
  65. return Json(200, alertDTOs)
  66. }
  67. // POST /api/alerts/test
  68. func AlertTest(c *middleware.Context, dto dtos.AlertTestCommand) Response {
  69. backendCmd := alerting.AlertTestCommand{
  70. OrgId: c.OrgId,
  71. Dashboard: dto.Dashboard,
  72. PanelId: dto.PanelId,
  73. }
  74. if err := bus.Dispatch(&backendCmd); err != nil {
  75. if validationErr, ok := err.(alerting.ValidationError); ok {
  76. return ApiError(422, validationErr.Error(), nil)
  77. }
  78. return ApiError(500, "Failed to test rule", err)
  79. }
  80. res := backendCmd.Result
  81. dtoRes := &dtos.AlertTestResult{
  82. Firing: res.Firing,
  83. }
  84. if res.Error != nil {
  85. dtoRes.Error = res.Error.Error()
  86. }
  87. for _, log := range res.Logs {
  88. dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
  89. }
  90. for _, match := range res.EvalMatches {
  91. dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
  92. }
  93. dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
  94. return Json(200, dtoRes)
  95. }
  96. // GET /api/alerts/:id
  97. func GetAlert(c *middleware.Context) Response {
  98. id := c.ParamsInt64(":alertId")
  99. query := models.GetAlertByIdQuery{Id: id}
  100. if err := bus.Dispatch(&query); err != nil {
  101. return ApiError(500, "List alerts failed", err)
  102. }
  103. return Json(200, &query.Result)
  104. }
  105. // DEL /api/alerts/:id
  106. func DelAlert(c *middleware.Context) Response {
  107. alertId := c.ParamsInt64(":alertId")
  108. if alertId == 0 {
  109. return ApiError(401, "Failed to parse alertid", nil)
  110. }
  111. cmd := models.DeleteAlertCommand{AlertId: alertId}
  112. if err := bus.Dispatch(&cmd); err != nil {
  113. return ApiError(500, "Failed to delete alert", err)
  114. }
  115. var resp = map[string]interface{}{"alertId": alertId}
  116. return Json(200, resp)
  117. }
  118. func GetAlertNotifications(c *middleware.Context) Response {
  119. query := &models.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
  120. if err := bus.Dispatch(query); err != nil {
  121. return ApiError(500, "Failed to get alert notifications", err)
  122. }
  123. var result []dtos.AlertNotification
  124. for _, notification := range query.Result {
  125. result = append(result, dtos.AlertNotification{
  126. Id: notification.Id,
  127. Name: notification.Name,
  128. Type: notification.Type,
  129. IsDefault: notification.IsDefault,
  130. Created: notification.Created,
  131. Updated: notification.Updated,
  132. })
  133. }
  134. return Json(200, result)
  135. }
  136. func GetAlertNotificationById(c *middleware.Context) Response {
  137. query := &models.GetAlertNotificationsQuery{
  138. OrgId: c.OrgId,
  139. Id: c.ParamsInt64("notificationId"),
  140. }
  141. if err := bus.Dispatch(query); err != nil {
  142. return ApiError(500, "Failed to get alert notifications", err)
  143. }
  144. return Json(200, query.Result)
  145. }
  146. func CreateAlertNotification(c *middleware.Context, cmd models.CreateAlertNotificationCommand) Response {
  147. cmd.OrgId = c.OrgId
  148. if err := bus.Dispatch(&cmd); err != nil {
  149. return ApiError(500, "Failed to create alert notification", err)
  150. }
  151. return Json(200, cmd.Result)
  152. }
  153. func UpdateAlertNotification(c *middleware.Context, cmd models.UpdateAlertNotificationCommand) Response {
  154. cmd.OrgId = c.OrgId
  155. if err := bus.Dispatch(&cmd); err != nil {
  156. return ApiError(500, "Failed to update alert notification", err)
  157. }
  158. return Json(200, cmd.Result)
  159. }
  160. func DeleteAlertNotification(c *middleware.Context) Response {
  161. cmd := models.DeleteAlertNotificationCommand{
  162. OrgId: c.OrgId,
  163. Id: c.ParamsInt64("notificationId"),
  164. }
  165. if err := bus.Dispatch(&cmd); err != nil {
  166. return ApiError(500, "Failed to delete alert notification", err)
  167. }
  168. return ApiSuccess("Notification deleted")
  169. }
  170. //POST /api/alert-notifications/test
  171. func NotificationTest(c *middleware.Context, dto dtos.NotificationTestCommand) Response {
  172. cmd := &alerting.NotificationTestCommand{
  173. Name: dto.Name,
  174. Type: dto.Type,
  175. Settings: dto.Settings,
  176. }
  177. if err := bus.Dispatch(cmd); err != nil {
  178. return ApiError(500, "Failed to send alert notifications", err)
  179. }
  180. return ApiSuccess("Test notification sent")
  181. }
  182. func getAlertIdForRequest(c *middleware.Context) (int64, error) {
  183. alertId := c.QueryInt64("alertId")
  184. panelId := c.QueryInt64("panelId")
  185. dashboardId := c.QueryInt64("dashboardId")
  186. if alertId == 0 && dashboardId == 0 && panelId == 0 {
  187. return 0, fmt.Errorf("Missing alertId or dashboardId and panelId")
  188. }
  189. if alertId == 0 {
  190. //fetch alertId
  191. query := models.GetAlertsQuery{
  192. OrgId: c.OrgId,
  193. DashboardId: dashboardId,
  194. PanelId: panelId,
  195. }
  196. if err := bus.Dispatch(&query); err != nil {
  197. return 0, err
  198. }
  199. if len(query.Result) != 1 {
  200. return 0, fmt.Errorf("PanelId is not unique on dashboard")
  201. }
  202. alertId = query.Result[0].Id
  203. }
  204. return alertId, nil
  205. }