alerting.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. func GetAlertStatesForDashboard(c *middleware.Context) Response {
  23. dashboardId := c.QueryInt64("dashboardId")
  24. if dashboardId == 0 {
  25. return ApiError(400, "Missing query parameter dashboardId", nil)
  26. }
  27. query := models.GetAlertStatesForDashboardQuery{
  28. OrgId: c.OrgId,
  29. DashboardId: c.QueryInt64("dashboardId"),
  30. }
  31. if err := bus.Dispatch(&query); err != nil {
  32. return ApiError(500, "Failed to fetch alert states", err)
  33. }
  34. return Json(200, query.Result)
  35. }
  36. // GET /api/alerts
  37. func GetAlerts(c *middleware.Context) Response {
  38. query := models.GetAlertsQuery{
  39. OrgId: c.OrgId,
  40. DashboardId: c.QueryInt64("dashboardId"),
  41. PanelId: c.QueryInt64("panelId"),
  42. Limit: c.QueryInt64("limit"),
  43. }
  44. states := c.QueryStrings("state")
  45. if len(states) > 0 {
  46. query.State = states
  47. }
  48. if err := bus.Dispatch(&query); err != nil {
  49. return ApiError(500, "List alerts failed", err)
  50. }
  51. dashboardIds := make([]int64, 0)
  52. alertDTOs := make([]*dtos.AlertRule, 0)
  53. for _, alert := range query.Result {
  54. dashboardIds = append(dashboardIds, alert.DashboardId)
  55. alertDTOs = append(alertDTOs, &dtos.AlertRule{
  56. Id: alert.Id,
  57. DashboardId: alert.DashboardId,
  58. PanelId: alert.PanelId,
  59. Name: alert.Name,
  60. Message: alert.Message,
  61. State: alert.State,
  62. NewStateDate: alert.NewStateDate,
  63. ExecutionError: alert.ExecutionError,
  64. })
  65. }
  66. dashboardsQuery := models.GetDashboardsQuery{
  67. DashboardIds: dashboardIds,
  68. }
  69. if len(alertDTOs) > 0 {
  70. if err := bus.Dispatch(&dashboardsQuery); err != nil {
  71. return ApiError(500, "List alerts failed", err)
  72. }
  73. }
  74. //TODO: should be possible to speed this up with lookup table
  75. for _, alert := range alertDTOs {
  76. for _, dash := range dashboardsQuery.Result {
  77. if alert.DashboardId == dash.Id {
  78. alert.DashbboardUri = "db/" + dash.Slug
  79. }
  80. }
  81. }
  82. return Json(200, alertDTOs)
  83. }
  84. // POST /api/alerts/test
  85. func AlertTest(c *middleware.Context, dto dtos.AlertTestCommand) Response {
  86. if _, idErr := dto.Dashboard.Get("id").Int64(); idErr != nil {
  87. return ApiError(400, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
  88. }
  89. backendCmd := alerting.AlertTestCommand{
  90. OrgId: c.OrgId,
  91. Dashboard: dto.Dashboard,
  92. PanelId: dto.PanelId,
  93. }
  94. if err := bus.Dispatch(&backendCmd); err != nil {
  95. if validationErr, ok := err.(alerting.ValidationError); ok {
  96. return ApiError(422, validationErr.Error(), nil)
  97. }
  98. return ApiError(500, "Failed to test rule", err)
  99. }
  100. res := backendCmd.Result
  101. dtoRes := &dtos.AlertTestResult{
  102. Firing: res.Firing,
  103. ConditionEvals: res.ConditionEvals,
  104. State: res.Rule.State,
  105. }
  106. if res.Error != nil {
  107. dtoRes.Error = res.Error.Error()
  108. }
  109. for _, log := range res.Logs {
  110. dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
  111. }
  112. for _, match := range res.EvalMatches {
  113. dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
  114. }
  115. dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
  116. return Json(200, dtoRes)
  117. }
  118. // GET /api/alerts/:id
  119. func GetAlert(c *middleware.Context) Response {
  120. id := c.ParamsInt64(":alertId")
  121. query := models.GetAlertByIdQuery{Id: id}
  122. if err := bus.Dispatch(&query); err != nil {
  123. return ApiError(500, "List alerts failed", err)
  124. }
  125. return Json(200, &query.Result)
  126. }
  127. // DEL /api/alerts/:id
  128. func DelAlert(c *middleware.Context) Response {
  129. alertId := c.ParamsInt64(":alertId")
  130. if alertId == 0 {
  131. return ApiError(401, "Failed to parse alertid", nil)
  132. }
  133. cmd := models.DeleteAlertCommand{AlertId: alertId}
  134. if err := bus.Dispatch(&cmd); err != nil {
  135. return ApiError(500, "Failed to delete alert", err)
  136. }
  137. var resp = map[string]interface{}{"alertId": alertId}
  138. return Json(200, resp)
  139. }
  140. func GetAlertNotifiers(c *middleware.Context) Response {
  141. return Json(200, alerting.GetNotifiers())
  142. }
  143. func GetAlertNotifications(c *middleware.Context) Response {
  144. query := &models.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
  145. if err := bus.Dispatch(query); err != nil {
  146. return ApiError(500, "Failed to get alert notifications", err)
  147. }
  148. result := make([]*dtos.AlertNotification, 0)
  149. for _, notification := range query.Result {
  150. result = append(result, &dtos.AlertNotification{
  151. Id: notification.Id,
  152. Name: notification.Name,
  153. Type: notification.Type,
  154. IsDefault: notification.IsDefault,
  155. Created: notification.Created,
  156. Updated: notification.Updated,
  157. })
  158. }
  159. return Json(200, result)
  160. }
  161. func GetAlertNotificationById(c *middleware.Context) Response {
  162. query := &models.GetAlertNotificationsQuery{
  163. OrgId: c.OrgId,
  164. Id: c.ParamsInt64("notificationId"),
  165. }
  166. if err := bus.Dispatch(query); err != nil {
  167. return ApiError(500, "Failed to get alert notifications", err)
  168. }
  169. return Json(200, query.Result)
  170. }
  171. func CreateAlertNotification(c *middleware.Context, cmd models.CreateAlertNotificationCommand) Response {
  172. cmd.OrgId = c.OrgId
  173. if err := bus.Dispatch(&cmd); err != nil {
  174. return ApiError(500, "Failed to create alert notification", err)
  175. }
  176. return Json(200, cmd.Result)
  177. }
  178. func UpdateAlertNotification(c *middleware.Context, cmd models.UpdateAlertNotificationCommand) Response {
  179. cmd.OrgId = c.OrgId
  180. if err := bus.Dispatch(&cmd); err != nil {
  181. return ApiError(500, "Failed to update alert notification", err)
  182. }
  183. return Json(200, cmd.Result)
  184. }
  185. func DeleteAlertNotification(c *middleware.Context) Response {
  186. cmd := models.DeleteAlertNotificationCommand{
  187. OrgId: c.OrgId,
  188. Id: c.ParamsInt64("notificationId"),
  189. }
  190. if err := bus.Dispatch(&cmd); err != nil {
  191. return ApiError(500, "Failed to delete alert notification", err)
  192. }
  193. return ApiSuccess("Notification deleted")
  194. }
  195. //POST /api/alert-notifications/test
  196. func NotificationTest(c *middleware.Context, dto dtos.NotificationTestCommand) Response {
  197. cmd := &alerting.NotificationTestCommand{
  198. Name: dto.Name,
  199. Type: dto.Type,
  200. Settings: dto.Settings,
  201. }
  202. if err := bus.Dispatch(cmd); err != nil {
  203. return ApiError(500, "Failed to send alert notifications", err)
  204. }
  205. return ApiSuccess("Test notification sent")
  206. }
  207. //POST /api/alerts/:alertId/pause
  208. func PauseAlert(c *middleware.Context, dto dtos.PauseAlertCommand) Response {
  209. alertId := c.ParamsInt64("alertId")
  210. cmd := models.PauseAlertCommand{
  211. OrgId: c.OrgId,
  212. AlertIds: []int64{alertId},
  213. Paused: dto.Paused,
  214. }
  215. if err := bus.Dispatch(&cmd); err != nil {
  216. return ApiError(500, "", err)
  217. }
  218. var response models.AlertStateType = models.AlertStatePending
  219. pausedState := "un paused"
  220. if cmd.Paused {
  221. response = models.AlertStatePaused
  222. pausedState = "paused"
  223. }
  224. result := map[string]interface{}{
  225. "alertId": alertId,
  226. "state": response,
  227. "message": "alert " + pausedState,
  228. }
  229. return Json(200, result)
  230. }
  231. //POST /api/admin/pause-all-alerts
  232. func PauseAllAlerts(c *middleware.Context, dto dtos.PauseAllAlertsCommand) Response {
  233. updateCmd := models.PauseAllAlertCommand{
  234. Paused: dto.Paused,
  235. }
  236. if err := bus.Dispatch(&updateCmd); err != nil {
  237. return ApiError(500, "Failed to pause alerts", err)
  238. }
  239. var response models.AlertStateType = models.AlertStatePending
  240. pausedState := "un paused"
  241. if updateCmd.Paused {
  242. response = models.AlertStatePaused
  243. pausedState = "paused"
  244. }
  245. result := map[string]interface{}{
  246. "state": response,
  247. "message": "alerts " + pausedState,
  248. "alertsAffected": updateCmd.ResultCount,
  249. }
  250. return Json(200, result)
  251. }