dashboard.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package api
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path"
  6. "strings"
  7. "github.com/grafana/grafana/pkg/api/dtos"
  8. "github.com/grafana/grafana/pkg/bus"
  9. "github.com/grafana/grafana/pkg/log"
  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/plugins"
  14. "github.com/grafana/grafana/pkg/services/search"
  15. "github.com/grafana/grafana/pkg/setting"
  16. "github.com/grafana/grafana/pkg/util"
  17. )
  18. func isDashboardStarredByUser(c *middleware.Context, dashId int64) (bool, error) {
  19. if !c.IsSignedIn {
  20. return false, nil
  21. }
  22. query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId}
  23. if err := bus.Dispatch(&query); err != nil {
  24. return false, err
  25. }
  26. return query.Result, nil
  27. }
  28. func GetDashboard(c *middleware.Context) {
  29. slug := strings.ToLower(c.Params(":slug"))
  30. query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
  31. err := bus.Dispatch(&query)
  32. if err != nil {
  33. c.JsonApiErr(404, "Dashboard not found", nil)
  34. return
  35. }
  36. isStarred, err := isDashboardStarredByUser(c, query.Result.Id)
  37. if err != nil {
  38. c.JsonApiErr(500, "Error while checking if dashboard was starred by user", err)
  39. return
  40. }
  41. dash := query.Result
  42. // Finding creator and last updater of the dashboard
  43. updater, creator := "Anonymous", "Anonymous"
  44. if dash.UpdatedBy > 0 {
  45. updater = getUserLogin(dash.UpdatedBy)
  46. }
  47. if dash.CreatedBy > 0 {
  48. creator = getUserLogin(dash.CreatedBy)
  49. }
  50. dto := dtos.DashboardFullWithMeta{
  51. Dashboard: dash.Data,
  52. Meta: dtos.DashboardMeta{
  53. IsStarred: isStarred,
  54. Slug: slug,
  55. Type: m.DashTypeDB,
  56. CanStar: c.IsSignedIn,
  57. CanSave: c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR,
  58. CanEdit: canEditDashboard(c.OrgRole),
  59. Created: dash.Created,
  60. Updated: dash.Updated,
  61. UpdatedBy: updater,
  62. CreatedBy: creator,
  63. Version: dash.Version,
  64. },
  65. }
  66. c.TimeRequest(metrics.M_Api_Dashboard_Get)
  67. c.JSON(200, dto)
  68. }
  69. func getUserLogin(userId int64) string {
  70. query := m.GetUserByIdQuery{Id: userId}
  71. err := bus.Dispatch(&query)
  72. if err != nil {
  73. return "Anonymous"
  74. } else {
  75. user := query.Result
  76. return user.Login
  77. }
  78. }
  79. func DeleteDashboard(c *middleware.Context) {
  80. slug := c.Params(":slug")
  81. query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
  82. if err := bus.Dispatch(&query); err != nil {
  83. c.JsonApiErr(404, "Dashboard not found", nil)
  84. return
  85. }
  86. cmd := m.DeleteDashboardCommand{Slug: slug, OrgId: c.OrgId}
  87. if err := bus.Dispatch(&cmd); err != nil {
  88. c.JsonApiErr(500, "Failed to delete dashboard", err)
  89. return
  90. }
  91. var resp = map[string]interface{}{"title": query.Result.Title}
  92. c.JSON(200, resp)
  93. }
  94. func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) Response {
  95. cmd.OrgId = c.OrgId
  96. if !c.IsSignedIn {
  97. cmd.UserId = -1
  98. } else {
  99. cmd.UserId = c.UserId
  100. }
  101. dash := cmd.GetDashboardModel()
  102. if dash.Id == 0 {
  103. limitReached, err := middleware.QuotaReached(c, "dashboard")
  104. if err != nil {
  105. return ApiError(500, "failed to get quota", err)
  106. }
  107. if limitReached {
  108. return ApiError(403, "Quota reached", nil)
  109. }
  110. }
  111. if !cmd.Overwrite {
  112. if autoUpdate, exists := dash.Data.CheckGet("autoUpdate"); exists {
  113. message := "Dashboard marked as auto updated."
  114. if pluginId, err := autoUpdate.Get("pluginId").String(); err == nil {
  115. if pluginDef, ok := plugins.Plugins[pluginId]; ok {
  116. message = "Dashboard updated automatically when plugin " + pluginDef.Name + " is updated."
  117. }
  118. }
  119. return Json(412, util.DynMap{"status": "auto-update-dashboard", "message": message})
  120. }
  121. }
  122. err := bus.Dispatch(&cmd)
  123. if err != nil {
  124. if err == m.ErrDashboardWithSameNameExists {
  125. return Json(412, util.DynMap{"status": "name-exists", "message": err.Error()})
  126. }
  127. if err == m.ErrDashboardVersionMismatch {
  128. return Json(412, util.DynMap{"status": "version-mismatch", "message": err.Error()})
  129. }
  130. if err == m.ErrDashboardNotFound {
  131. return Json(404, util.DynMap{"status": "not-found", "message": err.Error()})
  132. }
  133. return ApiError(500, "Failed to save dashboard", err)
  134. }
  135. c.TimeRequest(metrics.M_Api_Dashboard_Save)
  136. return Json(200, util.DynMap{"status": "success", "slug": cmd.Result.Slug, "version": cmd.Result.Version})
  137. }
  138. func canEditDashboard(role m.RoleType) bool {
  139. return role == m.ROLE_ADMIN || role == m.ROLE_EDITOR || role == m.ROLE_READ_ONLY_EDITOR
  140. }
  141. func GetHomeDashboard(c *middleware.Context) Response {
  142. prefsQuery := m.GetPreferencesWithDefaultsQuery{OrgId: c.OrgId, UserId: c.UserId}
  143. if err := bus.Dispatch(&prefsQuery); err != nil {
  144. return ApiError(500, "Failed to get preferences", err)
  145. }
  146. if prefsQuery.Result.HomeDashboardId != 0 {
  147. slugQuery := m.GetDashboardSlugByIdQuery{Id: prefsQuery.Result.HomeDashboardId}
  148. err := bus.Dispatch(&slugQuery)
  149. if err == nil {
  150. dashRedirect := dtos.DashboardRedirect{RedirectUri: "db/" + slugQuery.Result}
  151. return Json(200, &dashRedirect)
  152. } else {
  153. log.Warn("Failed to get slug from database, %s", err.Error())
  154. }
  155. }
  156. filePath := path.Join(setting.StaticRootPath, "dashboards/home.json")
  157. file, err := os.Open(filePath)
  158. if err != nil {
  159. return ApiError(500, "Failed to load home dashboard", err)
  160. }
  161. dash := dtos.DashboardFullWithMeta{}
  162. dash.Meta.IsHome = true
  163. dash.Meta.CanEdit = canEditDashboard(c.OrgRole)
  164. jsonParser := json.NewDecoder(file)
  165. if err := jsonParser.Decode(&dash.Dashboard); err != nil {
  166. return ApiError(500, "Failed to load home dashboard", err)
  167. }
  168. return Json(200, &dash)
  169. }
  170. func GetDashboardFromJsonFile(c *middleware.Context) {
  171. file := c.Params(":file")
  172. dashboard := search.GetDashboardFromJsonIndex(file)
  173. if dashboard == nil {
  174. c.JsonApiErr(404, "Dashboard not found", nil)
  175. return
  176. }
  177. dash := dtos.DashboardFullWithMeta{Dashboard: dashboard.Data}
  178. dash.Meta.Type = m.DashTypeJson
  179. dash.Meta.CanEdit = canEditDashboard(c.OrgRole)
  180. c.JSON(200, &dash)
  181. }
  182. func GetDashboardTags(c *middleware.Context) {
  183. query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
  184. err := bus.Dispatch(&query)
  185. if err != nil {
  186. c.JsonApiErr(500, "Failed to get tags from database", err)
  187. return
  188. }
  189. c.JSON(200, query.Result)
  190. }