alerting.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "github.com/grafana/grafana/pkg/services/annotations"
  10. )
  11. func ValidateOrgAlert(c *middleware.Context) {
  12. id := c.ParamsInt64(":alertId")
  13. query := models.GetAlertByIdQuery{Id: id}
  14. if err := bus.Dispatch(&query); err != nil {
  15. c.JsonApiErr(404, "Alert not found", nil)
  16. return
  17. }
  18. if c.OrgId != query.Result.OrgId {
  19. c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
  20. return
  21. }
  22. }
  23. // GET /api/alerts/rules/
  24. func GetAlerts(c *middleware.Context) Response {
  25. query := models.GetAlertsQuery{
  26. OrgId: c.OrgId,
  27. State: c.QueryStrings("state"),
  28. DashboardId: c.QueryInt64("dashboardId"),
  29. PanelId: c.QueryInt64("panelId"),
  30. }
  31. if err := bus.Dispatch(&query); err != nil {
  32. return ApiError(500, "List alerts failed", err)
  33. }
  34. dashboardIds := make([]int64, 0)
  35. alertDTOs := make([]*dtos.AlertRule, 0)
  36. for _, alert := range query.Result {
  37. dashboardIds = append(dashboardIds, alert.DashboardId)
  38. alertDTOs = append(alertDTOs, &dtos.AlertRule{
  39. Id: alert.Id,
  40. DashboardId: alert.DashboardId,
  41. PanelId: alert.PanelId,
  42. Name: alert.Name,
  43. Message: alert.Message,
  44. State: alert.State,
  45. Severity: alert.Severity,
  46. EvalDate: alert.EvalDate,
  47. NewStateDate: alert.NewStateDate,
  48. ExecutionError: alert.ExecutionError,
  49. })
  50. }
  51. dashboardsQuery := models.GetDashboardsQuery{
  52. DashboardIds: dashboardIds,
  53. }
  54. if len(alertDTOs) > 0 {
  55. if err := bus.Dispatch(&dashboardsQuery); err != nil {
  56. return ApiError(500, "List alerts failed", err)
  57. }
  58. }
  59. //TODO: should be possible to speed this up with lookup table
  60. for _, alert := range alertDTOs {
  61. for _, dash := range dashboardsQuery.Result {
  62. if alert.DashboardId == dash.Id {
  63. alert.DashbboardUri = "db/" + dash.Slug
  64. }
  65. }
  66. }
  67. return Json(200, alertDTOs)
  68. }
  69. // POST /api/alerts/test
  70. func AlertTest(c *middleware.Context, dto dtos.AlertTestCommand) Response {
  71. backendCmd := alerting.AlertTestCommand{
  72. OrgId: c.OrgId,
  73. Dashboard: dto.Dashboard,
  74. PanelId: dto.PanelId,
  75. }
  76. if err := bus.Dispatch(&backendCmd); err != nil {
  77. if validationErr, ok := err.(alerting.ValidationError); ok {
  78. return ApiError(422, validationErr.Error(), nil)
  79. }
  80. return ApiError(500, "Failed to test rule", err)
  81. }
  82. res := backendCmd.Result
  83. dtoRes := &dtos.AlertTestResult{
  84. Firing: res.Firing,
  85. }
  86. if res.Error != nil {
  87. dtoRes.Error = res.Error.Error()
  88. }
  89. for _, log := range res.Logs {
  90. dtoRes.Logs = append(dtoRes.Logs, &dtos.AlertTestResultLog{Message: log.Message, Data: log.Data})
  91. }
  92. for _, match := range res.EvalMatches {
  93. dtoRes.EvalMatches = append(dtoRes.EvalMatches, &dtos.EvalMatch{Metric: match.Metric, Value: match.Value})
  94. }
  95. dtoRes.TimeMs = fmt.Sprintf("%1.3fms", res.GetDurationMs())
  96. return Json(200, dtoRes)
  97. }
  98. // GET /api/alerts/:id
  99. func GetAlert(c *middleware.Context) Response {
  100. id := c.ParamsInt64(":alertId")
  101. query := models.GetAlertByIdQuery{Id: id}
  102. if err := bus.Dispatch(&query); err != nil {
  103. return ApiError(500, "List alerts failed", err)
  104. }
  105. return Json(200, &query.Result)
  106. }
  107. // DEL /api/alerts/:id
  108. func DelAlert(c *middleware.Context) Response {
  109. alertId := c.ParamsInt64(":alertId")
  110. if alertId == 0 {
  111. return ApiError(401, "Failed to parse alertid", nil)
  112. }
  113. cmd := models.DeleteAlertCommand{AlertId: alertId}
  114. if err := bus.Dispatch(&cmd); err != nil {
  115. return ApiError(500, "Failed to delete alert", err)
  116. }
  117. var resp = map[string]interface{}{"alertId": alertId}
  118. return Json(200, resp)
  119. }
  120. func GetAlertNotifications(c *middleware.Context) Response {
  121. query := &models.GetAlertNotificationsQuery{OrgId: c.OrgId}
  122. if err := bus.Dispatch(query); err != nil {
  123. return ApiError(500, "Failed to get alert notifications", err)
  124. }
  125. var result []dtos.AlertNotification
  126. for _, notification := range query.Result {
  127. result = append(result, dtos.AlertNotification{
  128. Id: notification.Id,
  129. Name: notification.Name,
  130. Type: notification.Type,
  131. IsDefault: notification.IsDefault,
  132. Created: notification.Created,
  133. Updated: notification.Updated,
  134. })
  135. }
  136. return Json(200, result)
  137. }
  138. func GetAlertNotificationById(c *middleware.Context) Response {
  139. query := &models.GetAlertNotificationsQuery{
  140. OrgId: c.OrgId,
  141. Id: c.ParamsInt64("notificationId"),
  142. }
  143. if err := bus.Dispatch(query); err != nil {
  144. return ApiError(500, "Failed to get alert notifications", err)
  145. }
  146. return Json(200, query.Result[0])
  147. }
  148. func CreateAlertNotification(c *middleware.Context, cmd models.CreateAlertNotificationCommand) Response {
  149. cmd.OrgId = c.OrgId
  150. if err := bus.Dispatch(&cmd); err != nil {
  151. return ApiError(500, "Failed to create alert notification", err)
  152. }
  153. return Json(200, cmd.Result)
  154. }
  155. func UpdateAlertNotification(c *middleware.Context, cmd models.UpdateAlertNotificationCommand) Response {
  156. cmd.OrgId = c.OrgId
  157. if err := bus.Dispatch(&cmd); err != nil {
  158. return ApiError(500, "Failed to update alert notification", err)
  159. }
  160. return Json(200, cmd.Result)
  161. }
  162. func DeleteAlertNotification(c *middleware.Context) Response {
  163. cmd := models.DeleteAlertNotificationCommand{
  164. OrgId: c.OrgId,
  165. Id: c.ParamsInt64("notificationId"),
  166. }
  167. if err := bus.Dispatch(&cmd); err != nil {
  168. return ApiError(500, "Failed to delete alert notification", err)
  169. }
  170. return ApiSuccess("Notification deleted")
  171. }
  172. //POST /api/alert-notifications/test
  173. func NotificationTest(c *middleware.Context, dto dtos.NotificationTestCommand) Response {
  174. cmd := &alerting.NotificationTestCommand{
  175. Name: dto.Name,
  176. Type: dto.Type,
  177. Severity: dto.Severity,
  178. Settings: dto.Settings,
  179. }
  180. if err := bus.Dispatch(cmd); err != nil {
  181. return ApiError(500, "Failed to send alert notifications", err)
  182. }
  183. return ApiSuccess("Test notification sent")
  184. }
  185. func GetAlertHistory(c *middleware.Context) Response {
  186. alertId, err := getAlertIdForRequest(c)
  187. if err != nil {
  188. return ApiError(400, "Invalid request", err)
  189. }
  190. query := &annotations.ItemQuery{
  191. AlertId: alertId,
  192. Type: annotations.AlertType,
  193. OrgId: c.OrgId,
  194. Limit: c.QueryInt64("limit"),
  195. }
  196. repo := annotations.GetRepository()
  197. items, err := repo.Find(query)
  198. if err != nil {
  199. return ApiError(500, "Failed to get history for alert", err)
  200. }
  201. var result []dtos.AlertHistory
  202. for _, item := range items {
  203. result = append(result, dtos.AlertHistory{
  204. AlertId: item.AlertId,
  205. Timestamp: item.Timestamp,
  206. Data: item.Data,
  207. NewState: item.NewState,
  208. Text: item.Text,
  209. Metric: item.Metric,
  210. Title: item.Title,
  211. })
  212. }
  213. return Json(200, result)
  214. }
  215. func getAlertIdForRequest(c *middleware.Context) (int64, error) {
  216. alertId := c.QueryInt64("alertId")
  217. panelId := c.QueryInt64("panelId")
  218. dashboardId := c.QueryInt64("dashboardId")
  219. if alertId == 0 && dashboardId == 0 && panelId == 0 {
  220. return 0, fmt.Errorf("Missing alertId or dashboardId and panelId")
  221. }
  222. if alertId == 0 {
  223. //fetch alertId
  224. query := models.GetAlertsQuery{
  225. OrgId: c.OrgId,
  226. DashboardId: dashboardId,
  227. PanelId: panelId,
  228. }
  229. if err := bus.Dispatch(&query); err != nil {
  230. return 0, err
  231. }
  232. if len(query.Result) != 1 {
  233. return 0, fmt.Errorf("PanelId is not unique on dashboard")
  234. }
  235. alertId = query.Result[0].Id
  236. }
  237. return alertId, nil
  238. }