alerting.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. package api
  2. import (
  3. "fmt"
  4. "github.com/grafana/grafana/pkg/api/dtos"
  5. "github.com/grafana/grafana/pkg/bus"
  6. m "github.com/grafana/grafana/pkg/models"
  7. "github.com/grafana/grafana/pkg/services/alerting"
  8. "github.com/grafana/grafana/pkg/services/guardian"
  9. )
  10. func ValidateOrgAlert(c *m.ReqContext) {
  11. id := c.ParamsInt64(":alertId")
  12. query := m.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 *m.ReqContext) Response {
  23. dashboardID := c.QueryInt64("dashboardId")
  24. if dashboardID == 0 {
  25. return ApiError(400, "Missing query parameter dashboardId", nil)
  26. }
  27. query := m.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 *m.ReqContext) Response {
  38. query := m.GetAlertsQuery{
  39. OrgId: c.OrgId,
  40. DashboardId: c.QueryInt64("dashboardId"),
  41. PanelId: c.QueryInt64("panelId"),
  42. Limit: c.QueryInt64("limit"),
  43. User: c.SignedInUser,
  44. }
  45. states := c.QueryStrings("state")
  46. if len(states) > 0 {
  47. query.State = states
  48. }
  49. if err := bus.Dispatch(&query); err != nil {
  50. return ApiError(500, "List alerts failed", err)
  51. }
  52. for _, alert := range query.Result {
  53. alert.Url = m.GetDashboardUrl(alert.DashboardUid, alert.DashboardSlug)
  54. }
  55. return Json(200, query.Result)
  56. }
  57. // POST /api/alerts/test
  58. func AlertTest(c *m.ReqContext, dto dtos.AlertTestCommand) Response {
  59. if _, idErr := dto.Dashboard.Get("id").Int64(); idErr != nil {
  60. return ApiError(400, "The dashboard needs to be saved at least once before you can test an alert rule", nil)
  61. }
  62. backendCmd := alerting.AlertTestCommand{
  63. OrgId: c.OrgId,
  64. Dashboard: dto.Dashboard,
  65. PanelId: dto.PanelId,
  66. }
  67. if err := bus.Dispatch(&backendCmd); err != nil {
  68. if validationErr, ok := err.(alerting.ValidationError); ok {
  69. return ApiError(422, validationErr.Error(), nil)
  70. }
  71. return ApiError(500, "Failed to test rule", err)
  72. }
  73. res := backendCmd.Result
  74. dtoRes := &dtos.AlertTestResult{
  75. Firing: res.Firing,
  76. ConditionEvals: res.ConditionEvals,
  77. State: res.Rule.State,
  78. }
  79. if res.Error != nil {
  80. dtoRes.Error = res.Error.Error()
  81. }
  82. for _, log := range res.Logs {
  83. dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
  84. }
  85. for _, match := range res.EvalMatches {
  86. dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
  87. }
  88. dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
  89. return Json(200, dtoRes)
  90. }
  91. // GET /api/alerts/:id
  92. func GetAlert(c *m.ReqContext) Response {
  93. id := c.ParamsInt64(":alertId")
  94. query := m.GetAlertByIdQuery{Id: id}
  95. if err := bus.Dispatch(&query); err != nil {
  96. return ApiError(500, "List alerts failed", err)
  97. }
  98. return Json(200, &query.Result)
  99. }
  100. func GetAlertNotifiers(c *m.ReqContext) Response {
  101. return Json(200, alerting.GetNotifiers())
  102. }
  103. func GetAlertNotifications(c *m.ReqContext) Response {
  104. query := &m.GetAllAlertNotificationsQuery{OrgId: c.OrgId}
  105. if err := bus.Dispatch(query); err != nil {
  106. return ApiError(500, "Failed to get alert notifications", err)
  107. }
  108. result := make([]*dtos.AlertNotification, 0)
  109. for _, notification := range query.Result {
  110. result = append(result, &dtos.AlertNotification{
  111. Id: notification.Id,
  112. Name: notification.Name,
  113. Type: notification.Type,
  114. IsDefault: notification.IsDefault,
  115. Created: notification.Created,
  116. Updated: notification.Updated,
  117. })
  118. }
  119. return Json(200, result)
  120. }
  121. func GetAlertNotificationByID(c *m.ReqContext) Response {
  122. query := &m.GetAlertNotificationsQuery{
  123. OrgId: c.OrgId,
  124. Id: c.ParamsInt64("notificationId"),
  125. }
  126. if err := bus.Dispatch(query); err != nil {
  127. return ApiError(500, "Failed to get alert notifications", err)
  128. }
  129. return Json(200, query.Result)
  130. }
  131. func CreateAlertNotification(c *m.ReqContext, cmd m.CreateAlertNotificationCommand) Response {
  132. cmd.OrgId = c.OrgId
  133. if err := bus.Dispatch(&cmd); err != nil {
  134. return ApiError(500, "Failed to create alert notification", err)
  135. }
  136. return Json(200, cmd.Result)
  137. }
  138. func UpdateAlertNotification(c *m.ReqContext, cmd m.UpdateAlertNotificationCommand) Response {
  139. cmd.OrgId = c.OrgId
  140. if err := bus.Dispatch(&cmd); err != nil {
  141. return ApiError(500, "Failed to update alert notification", err)
  142. }
  143. return Json(200, cmd.Result)
  144. }
  145. func DeleteAlertNotification(c *m.ReqContext) Response {
  146. cmd := m.DeleteAlertNotificationCommand{
  147. OrgId: c.OrgId,
  148. Id: c.ParamsInt64("notificationId"),
  149. }
  150. if err := bus.Dispatch(&cmd); err != nil {
  151. return ApiError(500, "Failed to delete alert notification", err)
  152. }
  153. return ApiSuccess("Notification deleted")
  154. }
  155. //POST /api/alert-notifications/test
  156. func NotificationTest(c *m.ReqContext, dto dtos.NotificationTestCommand) Response {
  157. cmd := &alerting.NotificationTestCommand{
  158. Name: dto.Name,
  159. Type: dto.Type,
  160. Settings: dto.Settings,
  161. }
  162. if err := bus.Dispatch(cmd); err != nil {
  163. if err == m.ErrSmtpNotEnabled {
  164. return ApiError(412, err.Error(), err)
  165. }
  166. return ApiError(500, "Failed to send alert notifications", err)
  167. }
  168. return ApiSuccess("Test notification sent")
  169. }
  170. //POST /api/alerts/:alertId/pause
  171. func PauseAlert(c *m.ReqContext, dto dtos.PauseAlertCommand) Response {
  172. alertId := c.ParamsInt64("alertId")
  173. query := m.GetAlertByIdQuery{Id: alertId}
  174. if err := bus.Dispatch(&query); err != nil {
  175. return ApiError(500, "Get Alert failed", err)
  176. }
  177. guardian := guardian.New(query.Result.DashboardId, c.OrgId, c.SignedInUser)
  178. if canEdit, err := guardian.CanEdit(); err != nil || !canEdit {
  179. if err != nil {
  180. return ApiError(500, "Error while checking permissions for Alert", err)
  181. }
  182. return ApiError(403, "Access denied to this dashboard and alert", nil)
  183. }
  184. cmd := m.PauseAlertCommand{
  185. OrgId: c.OrgId,
  186. AlertIds: []int64{alertId},
  187. Paused: dto.Paused,
  188. }
  189. if err := bus.Dispatch(&cmd); err != nil {
  190. return ApiError(500, "", err)
  191. }
  192. var response m.AlertStateType = m.AlertStatePending
  193. pausedState := "un-paused"
  194. if cmd.Paused {
  195. response = m.AlertStatePaused
  196. pausedState = "paused"
  197. }
  198. result := map[string]interface{}{
  199. "alertId": alertId,
  200. "state": response,
  201. "message": "Alert " + pausedState,
  202. }
  203. return Json(200, result)
  204. }
  205. //POST /api/admin/pause-all-alerts
  206. func PauseAllAlerts(c *m.ReqContext, dto dtos.PauseAllAlertsCommand) Response {
  207. updateCmd := m.PauseAllAlertCommand{
  208. Paused: dto.Paused,
  209. }
  210. if err := bus.Dispatch(&updateCmd); err != nil {
  211. return ApiError(500, "Failed to pause alerts", err)
  212. }
  213. var response m.AlertStateType = m.AlertStatePending
  214. pausedState := "un paused"
  215. if updateCmd.Paused {
  216. response = m.AlertStatePaused
  217. pausedState = "paused"
  218. }
  219. result := map[string]interface{}{
  220. "state": response,
  221. "message": "alerts " + pausedState,
  222. "alertsAffected": updateCmd.ResultCount,
  223. }
  224. return Json(200, result)
  225. }