dashboard_snapshot.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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/infra/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 err != nil {
  47. return nil, err
  48. }
  49. defer response.Body.Close()
  50. if response.StatusCode != 200 {
  51. return nil, fmt.Errorf("Create external snapshot response status code %d", response.StatusCode)
  52. }
  53. if err := json.NewDecoder(response.Body).Decode(&createSnapshotResponse); err != nil {
  54. return nil, err
  55. }
  56. return &createSnapshotResponse, nil
  57. }
  58. // POST /api/snapshots
  59. func CreateDashboardSnapshot(c *m.ReqContext, cmd m.CreateDashboardSnapshotCommand) {
  60. if cmd.Name == "" {
  61. cmd.Name = "Unnamed snapshot"
  62. }
  63. var url string
  64. cmd.ExternalUrl = ""
  65. cmd.OrgId = c.OrgId
  66. cmd.UserId = c.UserId
  67. if cmd.External {
  68. if !setting.ExternalEnabled {
  69. c.JsonApiErr(403, "External dashboard creation is disabled", nil)
  70. return
  71. }
  72. response, err := createExternalDashboardSnapshot(cmd)
  73. if err != nil {
  74. c.JsonApiErr(500, "Failed to create external snaphost", err)
  75. return
  76. }
  77. url = response.Url
  78. cmd.Key = response.Key
  79. cmd.DeleteKey = response.DeleteKey
  80. cmd.ExternalUrl = response.Url
  81. cmd.ExternalDeleteUrl = response.DeleteUrl
  82. cmd.Dashboard = simplejson.New()
  83. metrics.M_Api_Dashboard_Snapshot_External.Inc()
  84. } else {
  85. if cmd.Key == "" {
  86. cmd.Key = util.GetRandomString(32)
  87. }
  88. if cmd.DeleteKey == "" {
  89. cmd.DeleteKey = util.GetRandomString(32)
  90. }
  91. url = setting.ToAbsUrl("dashboard/snapshot/" + cmd.Key)
  92. metrics.M_Api_Dashboard_Snapshot_Create.Inc()
  93. }
  94. if err := bus.Dispatch(&cmd); err != nil {
  95. c.JsonApiErr(500, "Failed to create snaphost", err)
  96. return
  97. }
  98. c.JSON(200, util.DynMap{
  99. "key": cmd.Key,
  100. "deleteKey": cmd.DeleteKey,
  101. "url": url,
  102. "deleteUrl": setting.ToAbsUrl("api/snapshots-delete/" + cmd.DeleteKey),
  103. })
  104. }
  105. // GET /api/snapshots/:key
  106. func GetDashboardSnapshot(c *m.ReqContext) {
  107. key := c.Params(":key")
  108. query := &m.GetDashboardSnapshotQuery{Key: key}
  109. err := bus.Dispatch(query)
  110. if err != nil {
  111. c.JsonApiErr(500, "Failed to get dashboard snapshot", err)
  112. return
  113. }
  114. snapshot := query.Result
  115. // expired snapshots should also be removed from db
  116. if snapshot.Expires.Before(time.Now()) {
  117. c.JsonApiErr(404, "Dashboard snapshot not found", err)
  118. return
  119. }
  120. dto := dtos.DashboardFullWithMeta{
  121. Dashboard: snapshot.Dashboard,
  122. Meta: dtos.DashboardMeta{
  123. Type: m.DashTypeSnapshot,
  124. IsSnapshot: true,
  125. Created: snapshot.Created,
  126. Expires: snapshot.Expires,
  127. },
  128. }
  129. metrics.M_Api_Dashboard_Snapshot_Get.Inc()
  130. c.Resp.Header().Set("Cache-Control", "public, max-age=3600")
  131. c.JSON(200, dto)
  132. }
  133. func deleteExternalDashboardSnapshot(externalUrl string) error {
  134. response, err := client.Get(externalUrl)
  135. if err != nil {
  136. return err
  137. }
  138. defer response.Body.Close()
  139. if response.StatusCode == 200 {
  140. return nil
  141. }
  142. // Gracefully ignore "snapshot not found" errors as they could have already
  143. // been removed either via the cleanup script or by request.
  144. if response.StatusCode == 500 {
  145. var respJson map[string]interface{}
  146. if err := json.NewDecoder(response.Body).Decode(&respJson); err != nil {
  147. return err
  148. }
  149. if respJson["message"] == "Failed to get dashboard snapshot" {
  150. return nil
  151. }
  152. }
  153. return fmt.Errorf("Unexpected response when deleting external snapshot. Status code: %d", response.StatusCode)
  154. }
  155. // GET /api/snapshots-delete/:deleteKey
  156. func DeleteDashboardSnapshotByDeleteKey(c *m.ReqContext) Response {
  157. key := c.Params(":deleteKey")
  158. query := &m.GetDashboardSnapshotQuery{DeleteKey: key}
  159. err := bus.Dispatch(query)
  160. if err != nil {
  161. return Error(500, "Failed to get dashboard snapshot", err)
  162. }
  163. if query.Result.External {
  164. err := deleteExternalDashboardSnapshot(query.Result.ExternalDeleteUrl)
  165. if err != nil {
  166. return Error(500, "Failed to delete external dashboard", err)
  167. }
  168. }
  169. cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
  170. if err := bus.Dispatch(cmd); err != nil {
  171. return Error(500, "Failed to delete dashboard snapshot", err)
  172. }
  173. return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."})
  174. }
  175. // DELETE /api/snapshots/:key
  176. func DeleteDashboardSnapshot(c *m.ReqContext) Response {
  177. key := c.Params(":key")
  178. query := &m.GetDashboardSnapshotQuery{Key: key}
  179. err := bus.Dispatch(query)
  180. if err != nil {
  181. return Error(500, "Failed to get dashboard snapshot", err)
  182. }
  183. if query.Result == nil {
  184. return Error(404, "Failed to get dashboard snapshot", nil)
  185. }
  186. dashboard := query.Result.Dashboard
  187. dashboardID := dashboard.Get("id").MustInt64()
  188. guardian := guardian.New(dashboardID, c.OrgId, c.SignedInUser)
  189. canEdit, err := guardian.CanEdit()
  190. if err != nil {
  191. return Error(500, "Error while checking permissions for snapshot", err)
  192. }
  193. if !canEdit && query.Result.UserId != c.SignedInUser.UserId {
  194. return Error(403, "Access denied to this snapshot", nil)
  195. }
  196. if query.Result.External {
  197. err := deleteExternalDashboardSnapshot(query.Result.ExternalDeleteUrl)
  198. if err != nil {
  199. return Error(500, "Failed to delete external dashboard", err)
  200. }
  201. }
  202. cmd := &m.DeleteDashboardSnapshotCommand{DeleteKey: query.Result.DeleteKey}
  203. if err := bus.Dispatch(cmd); err != nil {
  204. return Error(500, "Failed to delete dashboard snapshot", err)
  205. }
  206. return JSON(200, util.DynMap{"message": "Snapshot deleted. It might take an hour before it's cleared from any CDN caches."})
  207. }
  208. // GET /api/dashboard/snapshots
  209. func SearchDashboardSnapshots(c *m.ReqContext) Response {
  210. query := c.Query("query")
  211. limit := c.QueryInt("limit")
  212. if limit == 0 {
  213. limit = 1000
  214. }
  215. searchQuery := m.GetDashboardSnapshotsQuery{
  216. Name: query,
  217. Limit: limit,
  218. OrgId: c.OrgId,
  219. SignedInUser: c.SignedInUser,
  220. }
  221. err := bus.Dispatch(&searchQuery)
  222. if err != nil {
  223. return Error(500, "Search failed", err)
  224. }
  225. dtos := make([]*m.DashboardSnapshotDTO, len(searchQuery.Result))
  226. for i, snapshot := range searchQuery.Result {
  227. dtos[i] = &m.DashboardSnapshotDTO{
  228. Id: snapshot.Id,
  229. Name: snapshot.Name,
  230. Key: snapshot.Key,
  231. OrgId: snapshot.OrgId,
  232. UserId: snapshot.UserId,
  233. External: snapshot.External,
  234. ExternalUrl: snapshot.ExternalUrl,
  235. Expires: snapshot.Expires,
  236. Created: snapshot.Created,
  237. Updated: snapshot.Updated,
  238. }
  239. }
  240. return JSON(200, dtos)
  241. }