dashboard_snapshot.go 7.5 KB

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