dashboard_snapshot.go 1.9 KB

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