annotations.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. Type: string(item.Type),
  38. })
  39. }
  40. return Json(200, result)
  41. }
  42. func PostAnnotation(c *middleware.Context, cmd dtos.PostAnnotationsCmd) Response {
  43. repo := annotations.GetRepository()
  44. item := annotations.Item{
  45. OrgId: c.OrgId,
  46. DashboardId: cmd.DashboardId,
  47. PanelId: cmd.PanelId,
  48. Epoch: cmd.Time / 1000,
  49. Title: cmd.Title,
  50. Text: cmd.Text,
  51. CategoryId: cmd.CategoryId,
  52. NewState: cmd.FillColor,
  53. Type: annotations.EventType,
  54. }
  55. if err := repo.Save(&item); err != nil {
  56. return ApiError(500, "Failed to save annotation", err)
  57. }
  58. // handle regions
  59. if cmd.IsRegion {
  60. item.RegionId = item.Id
  61. if err := repo.Update(&item); err != nil {
  62. return ApiError(500, "Failed set regionId on annotation", err)
  63. }
  64. item.Id = 0
  65. item.Epoch = cmd.TimeEnd
  66. if err := repo.Save(&item); err != nil {
  67. return ApiError(500, "Failed save annotation for region end time", err)
  68. }
  69. }
  70. return ApiSuccess("Annotation added")
  71. }
  72. func DeleteAnnotations(c *middleware.Context, cmd dtos.DeleteAnnotationsCmd) Response {
  73. repo := annotations.GetRepository()
  74. err := repo.Delete(&annotations.DeleteParams{
  75. AlertId: cmd.PanelId,
  76. DashboardId: cmd.DashboardId,
  77. PanelId: cmd.PanelId,
  78. })
  79. if err != nil {
  80. return ApiError(500, "Failed to delete annotations", err)
  81. }
  82. return ApiSuccess("Annotations deleted")
  83. }