alerting.go 8.1 KB

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