alerting.go 6.5 KB

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