alerting.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. }
  105. if res.Error != nil {
  106. dtoRes.Error = res.Error.Error()
  107. }
  108. for _, log := range res.Logs {
  109. dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
  110. }
  111. for _, match := range res.EvalMatches {
  112. dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
  113. }
  114. dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
  115. return Json(200, dtoRes)
  116. }
  117. // GET /api/alerts/:id
  118. func GetAlert(c *middleware.Context) Response {
  119. id := c.ParamsInt64(":alertId")
  120. query := models.GetAlertByIdQuery{Id: id}
  121. if err := bus.Dispatch(&query); err != nil {
  122. return ApiError(500, "List alerts failed", err)
  123. }
  124. return Json(200, &query.Result)
  125. }
  126. // DEL /api/alerts/:id
  127. func DelAlert(c *middleware.Context) Response {
  128. alertId := c.ParamsInt64(":alertId")
  129. if alertId == 0 {
  130. return ApiError(401, "Failed to parse alertid", nil)
  131. }
  132. cmd := models.DeleteAlertCommand{AlertId: alertId}
  133. if err := bus.Dispatch(&cmd); err != nil {
  134. return ApiError(500, "Failed to delete alert", err)
  135. }
  136. var resp = map[string]interface{}{"alertId": alertId}
  137. return Json(200, resp)
  138. }
  139. func GetAlertNotifications(c *middleware.Context) Response {
  140. query := &models.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
  141. if err := bus.Dispatch(query); err != nil {
  142. return ApiError(500, "Failed to get alert notifications", err)
  143. }
  144. result := make([]*dtos.AlertNotification, 0)
  145. for _, notification := range query.Result {
  146. result = append(result, &dtos.AlertNotification{
  147. Id: notification.Id,
  148. Name: notification.Name,
  149. Type: notification.Type,
  150. IsDefault: notification.IsDefault,
  151. Created: notification.Created,
  152. Updated: notification.Updated,
  153. })
  154. }
  155. return Json(200, result)
  156. }
  157. func GetAlertNotificationById(c *middleware.Context) Response {
  158. query := &models.GetAlertNotificationsQuery{
  159. OrgId: c.OrgId,
  160. Id: c.ParamsInt64("notificationId"),
  161. }
  162. if err := bus.Dispatch(query); err != nil {
  163. return ApiError(500, "Failed to get alert notifications", err)
  164. }
  165. return Json(200, query.Result)
  166. }
  167. func CreateAlertNotification(c *middleware.Context, cmd models.CreateAlertNotificationCommand) Response {
  168. cmd.OrgId = c.OrgId
  169. if err := bus.Dispatch(&cmd); err != nil {
  170. return ApiError(500, "Failed to create alert notification", err)
  171. }
  172. return Json(200, cmd.Result)
  173. }
  174. func UpdateAlertNotification(c *middleware.Context, cmd models.UpdateAlertNotificationCommand) Response {
  175. cmd.OrgId = c.OrgId
  176. if err := bus.Dispatch(&cmd); err != nil {
  177. return ApiError(500, "Failed to update alert notification", err)
  178. }
  179. return Json(200, cmd.Result)
  180. }
  181. func DeleteAlertNotification(c *middleware.Context) Response {
  182. cmd := models.DeleteAlertNotificationCommand{
  183. OrgId: c.OrgId,
  184. Id: c.ParamsInt64("notificationId"),
  185. }
  186. if err := bus.Dispatch(&cmd); err != nil {
  187. return ApiError(500, "Failed to delete alert notification", err)
  188. }
  189. return ApiSuccess("Notification deleted")
  190. }
  191. //POST /api/alert-notifications/test
  192. func NotificationTest(c *middleware.Context, dto dtos.NotificationTestCommand) Response {
  193. cmd := &alerting.NotificationTestCommand{
  194. Name: dto.Name,
  195. Type: dto.Type,
  196. Settings: dto.Settings,
  197. }
  198. if err := bus.Dispatch(cmd); err != nil {
  199. return ApiError(500, "Failed to send alert notifications", err)
  200. }
  201. return ApiSuccess("Test notification sent")
  202. }
  203. //POST /api/alerts/:alertId/pause
  204. func PauseAlert(c *middleware.Context, dto dtos.PauseAlertCommand) Response {
  205. alertId := c.ParamsInt64("alertId")
  206. cmd := models.PauseAlertCommand{
  207. OrgId: c.OrgId,
  208. AlertIds: []int64{alertId},
  209. Paused: dto.Paused,
  210. }
  211. if err := bus.Dispatch(&cmd); err != nil {
  212. return ApiError(500, "", err)
  213. }
  214. var response models.AlertStateType = models.AlertStatePending
  215. pausedState := "un paused"
  216. if cmd.Paused {
  217. response = models.AlertStatePaused
  218. pausedState = "paused"
  219. }
  220. result := map[string]interface{}{
  221. "alertId": alertId,
  222. "state": response,
  223. "message": "alert " + pausedState,
  224. }
  225. return Json(200, result)
  226. }
  227. //POST /api/admin/pause-all-alerts
  228. func PauseAllAlerts(c *middleware.Context, dto dtos.PauseAllAlertsCommand) Response {
  229. updateCmd := models.PauseAllAlertCommand{
  230. Paused: dto.Paused,
  231. }
  232. if err := bus.Dispatch(&updateCmd); err != nil {
  233. return ApiError(500, "Failed to pause alerts", err)
  234. }
  235. var response models.AlertStateType = models.AlertStatePending
  236. pausedState := "un paused"
  237. if updateCmd.Paused {
  238. response = models.AlertStatePaused
  239. pausedState = "paused"
  240. }
  241. result := map[string]interface{}{
  242. "state": response,
  243. "message": "alerts " + pausedState,
  244. "alertsAffected": updateCmd.ResultCount,
  245. }
  246. return Json(200, result)
  247. }