dashboard_snapshot.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. package api
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  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/components/simplejson"
  11. "github.com/grafana/grafana/pkg/metrics"
  12. m "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/services/guardian"
  14. "github.com/grafana/grafana/pkg/setting"
  15. "github.com/grafana/grafana/pkg/util"
  16. )
  17. var client = &http.Client{
  18. Timeout: time.Second * 5,
  19. Transport: &http.Transport{Proxy: http.ProxyFromEnvironment},
  20. }
  21. func GetSharingOptions(c *m.ReqContext) {
  22. c.JSON(200, util.DynMap{
  23. "externalSnapshotURL": setting.ExternalSnapshotUrl,
  24. "externalSnapshotName": setting.ExternalSnapshotName,
  25. "externalEnabled": setting.ExternalEnabled,
  26. })
  27. }
  28. type CreateExternalSnapshotResponse struct {
  29. Key string `json:"key"`
  30. DeleteKey string `json:"deleteKey"`
  31. Url string `json:"url"`
  32. DeleteUrl string `json:"deleteUrl"`
  33. }
  34. func createExternalDashboardSnapshot(cmd m.CreateDashboardSnapshotCommand) (*CreateExternalSnapshotResponse, error) {
  35. var createSnapshotResponse CreateExternalSnapshotResponse
  36. message := map[string]interface{}{
  37. "name": cmd.Name,
  38. "expires": cmd.Expires,
  39. "dashboard": cmd.Dashboard,
  40. }
  41. messageBytes, err := simplejson.NewFromAny(message).Encode()
  42. if err != nil {
  43. return nil, err
  44. }
  45. response, err := client.Post(setting.ExternalSnapshotUrl+"/api/snapshots", "application/json", bytes.NewBuffer(messageBytes))
  46. if response != nil {
  47. defer response.Body.Close()
  48. }
  49. if err != nil {
  50. return nil, err
  51. }
  52. if response.StatusCode != 200 {
  53. return nil, fmt.Errorf("Create external snapshot response status code %d", response.StatusCode)
  54. }
  55. if err := json.NewDecoder(response.Body).Decode(&createSnapshotResponse); err != nil {
  56. return nil, err
  57. }
  58. return &createSnapshotResponse, nil
  59. }
  60. // POST /api/snapshots
  61. func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotCommand) {
  62. if cmd.Name == "" {
  63. cmd.Name = "Unnamed snapshot"
  64. }
  65. var url string
  66. cmd.ExternalUrl = ""
  67. cmd.OrgId = c.OrgId
  68. cmd.UserId = c.UserId
  69. if cmd.External {
  70. if !setting.ExternalEnabled {
  71. c.JsonApiErr(403, "External dashboard creation is disabled", nil)
  72. return
  73. }
  74. response, err := createExternalDashboardSnapshot(cmd)
  75. if err != nil {
  76. c.JsonApiErr(500, "Failed to create external snaphost", err)
  77. return
  78. }
  79. url = response.Url
  80. cmd.Key = response.Key
  81. cmd.DeleteKey = response.DeleteKey
  82. cmd.ExternalUrl = response.Url
  83. cmd.ExternalDeleteUrl = response.DeleteUrl
  84. cmd.Dashboard = simplejson.New()
  85. metrics.M_Api_Dashboard_Snapshot_External.Inc()
  86. } else {
  87. cmd.Key = util.GetRandomString(32)
  88. cmd.DeleteKey = util.GetRandomString(32)
  89. url = setting.ToAbsUrl("dashboard/snapshot/" + cmd.Key)
  90. metrics.M_Api_Dashboard_Snapshot_Create.Inc()
  91. }
  92. if err := bus.Dispatch(&cmd); err != nil {
  93. c.JsonApiErr(500, "Failed to create snaphost", err)
  94. return
  95. }
  96. c.JSON(200, util.DynMap{
  97. "key": cmd.Key,
  98. "deleteKey": cmd.DeleteKey,
  99. "url": url,
  100. "deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey),
  101. })
  102. }
  103. // GET /api/snapshots/:key
  104. func GetDashboardSnapshot(c *m.ReqContext) {
  105. key := c.Params(":key")
  106. query := &m.GetDashboardSnapshotQuery{Key: key}
  107. err := bus.Dispatch(query)
  108. if err != nil {
  109. c.JsonApiErr(500, "Failed to get dashboard snapshot", err)
  110. return
  111. }
  112. snapshot := query.Result
  113. // expired snapshots should also be removed from db
  114. if snapshot.Expires.Before(time.Now()) {
  115. c.JsonApiErr(404, "Dashboard snapshot not found", err)
  116. return
  117. }
  118. dto := dtos.DashboardFullWithMeta{
  119. Dashboard: snapshot.Dashboard,
  120. Meta: dtos.DashboardMeta{
  121. Type: m.DashTypeSnapshot,
  122. IsSnapshot: true,
  123. Created: snapshot.Created,
  124. Expires: snapshot.Expires,
  125. },
  126. }
  127. metrics.M_Api_Dashboard_Snapshot_Get.Inc()
  128. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  129. c.JSON(200, dto)
  130. }
  131. // GET /api/snapshots-delete/:deleteKey
  132. func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response {
  133. key := c.Params(":deleteKey")
  134. query := &m.GetDashboardSnapshotQuery{DeleteKey: key}
  135. err := bus.Dispatch(query)
  136. if err != nil {
  137. return Error(500, "Failed to get dashboard snapshot", err)
  138. }
  139. cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
  140. if err := bus.Dispatch(cmd); err != nil {
  141. return Error(500, "Failed to delete dashboard snapshot", err)
  142. }
  143. return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."})
  144. }
  145. // DELETE /api/snapshots/:key
  146. func DeleteDashboardSnapshot(c *m.ReqContext) Response {
  147. key := c.Params(":key")
  148. query := &m.GetDashboardSnapshotQuery{Key: key}
  149. err := bus.Dispatch(query)
  150. if err != nil {
  151. return Error(500, "Failed to get dashboard snapshot", err)
  152. }
  153. if query.Result == nil {
  154. return Error(404, "Failed to get dashboard snapshot", nil)
  155. }
  156. dashboard := query.Result.Dashboard
  157. dashboardID := dashboard.Get("id").MustInt64()
  158. guardian := guardian.New(dashboardID, c.OrgId, c.SignedInUser)
  159. canEdit, err := guardian.CanEdit()
  160. if err != nil {
  161. return Error(500, "Error while checking permissions for snapshot", err)
  162. }
  163. if !canEdit && query.Result.UserId != c.SignedInUser.UserId {
  164. return Error(403, "Access denied to this snapshot", nil)
  165. }
  166. cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
  167. if err := bus.Dispatch(cmd); err != nil {
  168. return Error(500, "Failed to delete dashboard snapshot", err)
  169. }
  170. return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."})
  171. }
  172. // GET /api/dashboard/snapshots
  173. func SearchDashboardSnapshots(c *m.ReqContext) Response {
  174. query := c.Query("query")
  175. limit := c.QueryInt("limit")
  176. if limit == 0 {
  177. limit = 1000
  178. }
  179. searchQuery := m.GetDashboardSnapshotsQuery{
  180. Name: query,
  181. Limit: limit,
  182. OrgId: c.OrgId,
  183. SignedInUser: c.SignedInUser,
  184. }
  185. err := bus.Dispatch(&searchQuery)
  186. if err != nil {
  187. return Error(500, "Search failed", err)
  188. }
  189. dtos := make([]*m.DashboardSnapshotDTO, len(searchQuery.Result))
  190. for i, snapshot := range searchQuery.Result {
  191. dtos[i] = &m.DashboardSnapshotDTO{
  192. Id: snapshot.Id,
  193. Name: snapshot.Name,
  194. Key: snapshot.Key,
  195. OrgId: snapshot.OrgId,
  196. UserId: snapshot.UserId,
  197. External: snapshot.External,
  198. ExternalUrl: snapshot.ExternalUrl,
  199. Expires: snapshot.Expires,
  200. Created: snapshot.Created,
  201. Updated: snapshot.Updated,
  202. }
  203. }
  204. return JSON(200, dtos)
  205. }