annotations.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package api
  2. import (
  3. "github.com/grafana/grafana/pkg/api/dtos"
  4. "github.com/grafana/grafana/pkg/middleware"
  5. "github.com/grafana/grafana/pkg/services/annotations"
  6. )
  7. func GetAnnotations(c *middleware.Context) Response {
  8. query := &annotations.ItemQuery{
  9. From: c.QueryInt64("from") / 1000,
  10. To: c.QueryInt64("to") / 1000,
  11. Type: annotations.ItemType(c.Query("type")),
  12. OrgId: c.OrgId,
  13. AlertId: c.QueryInt64("alertId"),
  14. DashboardId: c.QueryInt64("dashboardId"),
  15. PanelId: c.QueryInt64("panelId"),
  16. Limit: c.QueryInt64("limit"),
  17. NewState: c.QueryStrings("newState"),
  18. }
  19. repo := annotations.GetRepository()
  20. items, err := repo.Find(query)
  21. if err != nil {
  22. return ApiError(500, "Failed to get annotations", err)
  23. }
  24. result := make([]dtos.Annotation, 0)
  25. for _, item := range items {
  26. result = append(result, dtos.Annotation{
  27. AlertId: item.AlertId,
  28. Time: item.Epoch * 1000,
  29. Data: item.Data,
  30. NewState: item.NewState,
  31. PrevState: item.PrevState,
  32. Text: item.Text,
  33. Metric: item.Metric,
  34. Title: item.Title,
  35. PanelId: item.PanelId,
  36. RegionId: item.RegionId,
  37. })
  38. }
  39. return Json(200, result)
  40. }
  41. func PostAnnotation(c *middleware.Context, cmd dtos.PostAnnotationsCmd) Response {
  42. repo := annotations.GetRepository()
  43. item := annotations.Item{
  44. OrgId: c.OrgId,
  45. DashboardId: cmd.DashboardId,
  46. PanelId: cmd.PanelId,
  47. Epoch: cmd.Time / 1000,
  48. Title: cmd.Title,
  49. Text: cmd.Text,
  50. CategoryId: cmd.CategoryId,
  51. NewState: cmd.FillColor,
  52. Type: annotations.EventType,
  53. }
  54. if err := repo.Save(&item); err != nil {
  55. return ApiError(500, "Failed to save annotation", err)
  56. }
  57. // handle regions
  58. if cmd.IsRegion {
  59. item.RegionId = item.Id
  60. if err := repo.Update(&item); err != nil {
  61. return ApiError(500, "Failed set regionId on annotation", err)
  62. }
  63. item.Id = 0
  64. item.Epoch = cmd.TimeEnd
  65. if err := repo.Save(&item); err != nil {
  66. return ApiError(500, "Failed save annotation for region end time", err)
  67. }
  68. }
  69. return ApiSuccess("Annotation added")
  70. }
  71. func DeleteAnnotations(c *middleware.Context, cmd dtos.DeleteAnnotationsCmd) Response {
  72. repo := annotations.GetRepository()
  73. err := repo.Delete(&annotations.DeleteParams{
  74. AlertId: cmd.PanelId,
  75. DashboardId: cmd.DashboardId,
  76. PanelId: cmd.PanelId,
  77. })
  78. if err != nil {
  79. return ApiError(500, "Failed to delete annotations", err)
  80. }
  81. return ApiSuccess("Annotations deleted")
  82. }