alerting.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. EvalDate: alert.EvalDate,
  63. NewStateDate: alert.NewStateDate,
  64. ExecutionError: alert.ExecutionError,
  65. })
  66. }
  67. dashboardsQuery := models.GetDashboardsQuery{
  68. DashboardIds: dashboardIds,
  69. }
  70. if len(alertDTOs) > 0 {
  71. if err := bus.Dispatch(&dashboardsQuery); err != nil {
  72. return ApiError(500, "List alerts failed", err)
  73. }
  74. }
  75. //TODO: should be possible to speed this up with lookup table
  76. for _, alert := range alertDTOs {
  77. for _, dash := range dashboardsQuery.Result {
  78. if alert.DashboardId == dash.Id {
  79. alert.DashbboardUri = "db/" + dash.Slug
  80. }
  81. }
  82. }
  83. return Json(200, alertDTOs)
  84. }
  85. // POST /api/alerts/test
  86. func AlertTest(c *middleware.Context, dto dtos.AlertTestCommand) Response {
  87. if _, idErr := dto.Dashboard.Get("id").Int64(); idErr != nil {
  88. return ApiError(400, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
  89. }
  90. backendCmd := alerting.AlertTestCommand{
  91. OrgId: c.OrgId,
  92. Dashboard: dto.Dashboard,
  93. PanelId: dto.PanelId,
  94. }
  95. if err := bus.Dispatch(&backendCmd); err != nil {
  96. if validationErr, ok := err.(alerting.ValidationError); ok {
  97. return ApiError(422, validationErr.Error(), nil)
  98. }
  99. return ApiError(500, "Failed to test rule", err)
  100. }
  101. res := backendCmd.Result
  102. dtoRes := &dtos.AlertTestResult{
  103. Firing: res.Firing,
  104. ConditionEvals: res.ConditionEvals,
  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 GetAlertNotifications(c *middleware.Context) Response {
  141. query := &models.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
  142. if err := bus.Dispatch(query); err != nil {
  143. return ApiError(500, "Failed to get alert notifications", err)
  144. }
  145. result := make([]*dtos.AlertNotification, 0)
  146. for _, notification := range query.Result {
  147. result = append(result, &dtos.AlertNotification{
  148. Id: notification.Id,
  149. Name: notification.Name,
  150. Type: notification.Type,
  151. IsDefault: notification.IsDefault,
  152. Created: notification.Created,
  153. Updated: notification.Updated,
  154. })
  155. }
  156. return Json(200, result)
  157. }
  158. func GetAlertNotificationById(c *middleware.Context) Response {
  159. query := &models.GetAlertNotificationsQuery{
  160. OrgId: c.OrgId,
  161. Id: c.ParamsInt64("notificationId"),
  162. }
  163. if err := bus.Dispatch(query); err != nil {
  164. return ApiError(500, "Failed to get alert notifications", err)
  165. }
  166. return Json(200, query.Result)
  167. }
  168. func CreateAlertNotification(c *middleware.Context, cmd models.CreateAlertNotificationCommand) Response {
  169. cmd.OrgId = c.OrgId
  170. if err := bus.Dispatch(&cmd); err != nil {
  171. return ApiError(500, "Failed to create alert notification", err)
  172. }
  173. return Json(200, cmd.Result)
  174. }
  175. func UpdateAlertNotification(c *middleware.Context, cmd models.UpdateAlertNotificationCommand) Response {
  176. cmd.OrgId = c.OrgId
  177. if err := bus.Dispatch(&cmd); err != nil {
  178. return ApiError(500, "Failed to update alert notification", err)
  179. }
  180. return Json(200, cmd.Result)
  181. }
  182. func DeleteAlertNotification(c *middleware.Context) Response {
  183. cmd := models.DeleteAlertNotificationCommand{
  184. OrgId: c.OrgId,
  185. Id: c.ParamsInt64("notificationId"),
  186. }
  187. if err := bus.Dispatch(&cmd); err != nil {
  188. return ApiError(500, "Failed to delete alert notification", err)
  189. }
  190. return ApiSuccess("Notification deleted")
  191. }
  192. //POST /api/alert-notifications/test
  193. func NotificationTest(c *middleware.Context, dto dtos.NotificationTestCommand) Response {
  194. cmd := &alerting.NotificationTestCommand{
  195. Name: dto.Name,
  196. Type: dto.Type,
  197. Settings: dto.Settings,
  198. }
  199. if err := bus.Dispatch(cmd); err != nil {
  200. return ApiError(500, "Failed to send alert notifications", err)
  201. }
  202. return ApiSuccess("Test notification sent")
  203. }
  204. //POST /api/alerts/:alertId/pause
  205. func PauseAlert(c *middleware.Context, dto dtos.PauseAlertCommand) Response {
  206. alertId := c.ParamsInt64("alertId")
  207. cmd := models.PauseAlertCommand{
  208. OrgId: c.OrgId,
  209. AlertIds: []int64{alertId},
  210. Paused: dto.Paused,
  211. }
  212. if err := bus.Dispatch(&cmd); err != nil {
  213. return ApiError(500, "", err)
  214. }
  215. var response models.AlertStateType = models.AlertStatePending
  216. pausedState := "un paused"
  217. if cmd.Paused {
  218. response = models.AlertStatePaused
  219. pausedState = "paused"
  220. }
  221. result := map[string]interface{}{
  222. "alertId": alertId,
  223. "state": response,
  224. "message": "alert " + pausedState,
  225. }
  226. return Json(200, result)
  227. }
  228. //POST /api/admin/pause-all-alerts
  229. func PauseAllAlerts(c *middleware.Context, dto dtos.PauseAllAlertsCommand) Response {
  230. updateCmd := models.PauseAllAlertCommand{
  231. Paused: dto.Paused,
  232. }
  233. if err := bus.Dispatch(&updateCmd); err != nil {
  234. return ApiError(500, "Failed to pause alerts", err)
  235. }
  236. var response models.AlertStateType = models.AlertStatePending
  237. pausedState := "un paused"
  238. if updateCmd.Paused {
  239. response = models.AlertStatePaused
  240. pausedState = "paused"
  241. }
  242. result := map[string]interface{}{
  243. "state": response,
  244. "message": "alert " + pausedState,
  245. "alertsAffected": updateCmd.ResultCount,
  246. }
  247. return Json(200, result)
  248. }