dashboard_snapshot.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "time"
  8. "github.com/grafana/grafana/pkg/api/dtos"
  9. "github.com/grafana/grafana/pkg/bus"
  10. "github.com/grafana/grafana/pkg/metrics"
  11. "github.com/grafana/grafana/pkg/middleware"
  12. m "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/setting"
  14. "github.com/grafana/grafana/pkg/util"
  15. )
  16. func CreateDashboardSnapshot(c *middleware.Context, cmd m.CreateDashboardSnapshotCommand) {
  17. if cmd.External {
  18. createExternalSnapshot(c, cmd)
  19. return
  20. }
  21. cmd.Key = util.GetRandomString(32)
  22. if err := bus.Dispatch(&cmd); err != nil {
  23. c.JsonApiErr(500, "Failed to create snaphost", err)
  24. return
  25. }
  26. metrics.M_Api_Dashboard_Snapshot_Create.Inc(1)
  27. c.JSON(200, util.DynMap{"key": cmd.Key, "url": setting.ToAbsUrl("/dashboard/snapshot")})
  28. }
  29. func createExternalSnapshot(c *middleware.Context, cmd m.CreateDashboardSnapshotCommand) {
  30. metrics.M_Api_Dashboard_Snapshot_External.Inc(1)
  31. cmd.External = false
  32. json, _ := json.Marshal(cmd)
  33. jsonData := bytes.NewBuffer(json)
  34. client := http.Client{Timeout: time.Duration(5 * time.Second)}
  35. resp, err := client.Post("http://snapshots-origin.raintank.io/api/snapshots", "application/json", jsonData)
  36. if err != nil {
  37. c.JsonApiErr(500, "Failed to publish external snapshot", err)
  38. return
  39. }
  40. c.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
  41. c.WriteHeader(resp.StatusCode)
  42. if resp.ContentLength > 0 {
  43. bytes, _ := ioutil.ReadAll(resp.Body)
  44. c.Write(bytes)
  45. }
  46. }
  47. func GetDashboardSnapshot(c *middleware.Context) {
  48. key := c.Params(":key")
  49. query := &m.GetDashboardSnapshotQuery{Key: key}
  50. err := bus.Dispatch(query)
  51. if err != nil {
  52. c.JsonApiErr(500, "Failed to get dashboard snapshot", err)
  53. return
  54. }
  55. dto := dtos.Dashboard{
  56. Model: query.Result.Dashboard,
  57. Meta: dtos.DashboardMeta{IsSnapshot: true},
  58. }
  59. metrics.M_Api_Dashboard_Snapshot_Get.Inc(1)
  60. c.Resp.Header().Set("Cache-Control", "public, max-age=31536000")
  61. c.JSON(200, dto)
  62. }