dashboard.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path"
  7. "strings"
  8. "github.com/grafana/grafana/pkg/services/dashboards"
  9. "github.com/grafana/grafana/pkg/api/dtos"
  10. "github.com/grafana/grafana/pkg/bus"
  11. "github.com/grafana/grafana/pkg/components/dashdiffs"
  12. "github.com/grafana/grafana/pkg/components/simplejson"
  13. "github.com/grafana/grafana/pkg/log"
  14. "github.com/grafana/grafana/pkg/metrics"
  15. "github.com/grafana/grafana/pkg/middleware"
  16. m "github.com/grafana/grafana/pkg/models"
  17. "github.com/grafana/grafana/pkg/plugins"
  18. "github.com/grafana/grafana/pkg/setting"
  19. "github.com/grafana/grafana/pkg/util"
  20. )
  21. func isDashboardStarredByUser(c *middleware.Context, dashId int64) (bool, error) {
  22. if !c.IsSignedIn {
  23. return false, nil
  24. }
  25. query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId}
  26. if err := bus.Dispatch(&query); err != nil {
  27. return false, err
  28. }
  29. return query.Result, nil
  30. }
  31. func GetDashboard(c *middleware.Context) {
  32. slug := strings.ToLower(c.Params(":slug"))
  33. query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
  34. err := bus.Dispatch(&query)
  35. if err != nil {
  36. c.JsonApiErr(404, "Dashboard not found", nil)
  37. return
  38. }
  39. isStarred, err := isDashboardStarredByUser(c, query.Result.Id)
  40. if err != nil {
  41. c.JsonApiErr(500, "Error while checking if dashboard was starred by user", err)
  42. return
  43. }
  44. dash := query.Result
  45. // Finding creator and last updater of the dashboard
  46. updater, creator := "Anonymous", "Anonymous"
  47. if dash.UpdatedBy > 0 {
  48. updater = getUserLogin(dash.UpdatedBy)
  49. }
  50. if dash.CreatedBy > 0 {
  51. creator = getUserLogin(dash.CreatedBy)
  52. }
  53. // make sure db version is in sync with json model version
  54. dash.Data.Set("version", dash.Version)
  55. dto := dtos.DashboardFullWithMeta{
  56. Dashboard: dash.Data,
  57. Meta: dtos.DashboardMeta{
  58. IsStarred: isStarred,
  59. Slug: slug,
  60. Type: m.DashTypeDB,
  61. CanStar: c.IsSignedIn,
  62. CanSave: c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR,
  63. CanEdit: canEditDashboard(c.OrgRole),
  64. Created: dash.Created,
  65. Updated: dash.Updated,
  66. UpdatedBy: updater,
  67. CreatedBy: creator,
  68. Version: dash.Version,
  69. },
  70. }
  71. // TODO(ben): copy this performance metrics logic for the new API endpoints added
  72. c.TimeRequest(metrics.M_Api_Dashboard_Get)
  73. c.JSON(200, dto)
  74. }
  75. func getUserLogin(userId int64) string {
  76. query := m.GetUserByIdQuery{Id: userId}
  77. err := bus.Dispatch(&query)
  78. if err != nil {
  79. return "Anonymous"
  80. } else {
  81. user := query.Result
  82. return user.Login
  83. }
  84. }
  85. func DeleteDashboard(c *middleware.Context) {
  86. slug := c.Params(":slug")
  87. query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
  88. if err := bus.Dispatch(&query); err != nil {
  89. c.JsonApiErr(404, "Dashboard not found", nil)
  90. return
  91. }
  92. cmd := m.DeleteDashboardCommand{Slug: slug, OrgId: c.OrgId}
  93. if err := bus.Dispatch(&cmd); err != nil {
  94. c.JsonApiErr(500, "Failed to delete dashboard", err)
  95. return
  96. }
  97. var resp = map[string]interface{}{"title": query.Result.Title}
  98. c.JSON(200, resp)
  99. }
  100. func PostDashboard(c *middleware.Context, cmd m.SaveDashboardCommand) Response {
  101. cmd.OrgId = c.OrgId
  102. cmd.UserId = c.UserId
  103. dash := cmd.GetDashboardModel()
  104. if dash.Id == 0 {
  105. limitReached, err := middleware.QuotaReached(c, "dashboard")
  106. if err != nil {
  107. return ApiError(500, "failed to get quota", err)
  108. }
  109. if limitReached {
  110. return ApiError(403, "Quota reached", nil)
  111. }
  112. }
  113. dashItem := &dashboards.SaveDashboardItem{
  114. Dashboard: dash,
  115. Message: cmd.Message,
  116. OrgId: c.OrgId,
  117. UserId: c.UserId,
  118. Overwrite: cmd.Overwrite,
  119. }
  120. dashboard, err := dashboards.GetRepository().SaveDashboard(dashItem)
  121. if err == m.ErrDashboardTitleEmpty {
  122. return ApiError(400, m.ErrDashboardTitleEmpty.Error(), nil)
  123. }
  124. if err == m.ErrDashboardContainsInvalidAlertData {
  125. return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
  126. }
  127. if err != nil {
  128. if err == m.ErrDashboardWithSameNameExists {
  129. return Json(412, util.DynMap{"status": "name-exists", "message": err.Error()})
  130. }
  131. if err == m.ErrDashboardVersionMismatch {
  132. return Json(412, util.DynMap{"status": "version-mismatch", "message": err.Error()})
  133. }
  134. if pluginErr, ok := err.(m.UpdatePluginDashboardError); ok {
  135. message := "The dashboard belongs to plugin " + pluginErr.PluginId + "."
  136. // look up plugin name
  137. if pluginDef, exist := plugins.Plugins[pluginErr.PluginId]; exist {
  138. message = "The dashboard belongs to plugin " + pluginDef.Name + "."
  139. }
  140. return Json(412, util.DynMap{"status": "plugin-dashboard", "message": message})
  141. }
  142. if err == m.ErrDashboardNotFound {
  143. return Json(404, util.DynMap{"status": "not-found", "message": err.Error()})
  144. }
  145. return ApiError(500, "Failed to save dashboard", err)
  146. }
  147. if err == m.ErrDashboardFailedToUpdateAlertData {
  148. return ApiError(500, "Invalid alert data. Cannot save dashboard", err)
  149. }
  150. c.TimeRequest(metrics.M_Api_Dashboard_Save)
  151. return Json(200, util.DynMap{"status": "success", "slug": dashboard.Slug, "version": dashboard.Version})
  152. }
  153. func canEditDashboard(role m.RoleType) bool {
  154. return role == m.ROLE_ADMIN || role == m.ROLE_EDITOR || setting.ViewersCanEdit
  155. }
  156. func GetHomeDashboard(c *middleware.Context) Response {
  157. prefsQuery := m.GetPreferencesWithDefaultsQuery{OrgId: c.OrgId, UserId: c.UserId}
  158. if err := bus.Dispatch(&prefsQuery); err != nil {
  159. return ApiError(500, "Failed to get preferences", err)
  160. }
  161. if prefsQuery.Result.HomeDashboardId != 0 {
  162. slugQuery := m.GetDashboardSlugByIdQuery{Id: prefsQuery.Result.HomeDashboardId}
  163. err := bus.Dispatch(&slugQuery)
  164. if err == nil {
  165. dashRedirect := dtos.DashboardRedirect{RedirectUri: "db/" + slugQuery.Result}
  166. return Json(200, &dashRedirect)
  167. } else {
  168. log.Warn("Failed to get slug from database, %s", err.Error())
  169. }
  170. }
  171. filePath := path.Join(setting.StaticRootPath, "dashboards/home.json")
  172. file, err := os.Open(filePath)
  173. if err != nil {
  174. return ApiError(500, "Failed to load home dashboard", err)
  175. }
  176. dash := dtos.DashboardFullWithMeta{}
  177. dash.Meta.IsHome = true
  178. dash.Meta.CanEdit = canEditDashboard(c.OrgRole)
  179. jsonParser := json.NewDecoder(file)
  180. if err := jsonParser.Decode(&dash.Dashboard); err != nil {
  181. return ApiError(500, "Failed to load home dashboard", err)
  182. }
  183. if c.HasUserRole(m.ROLE_ADMIN) && !c.HasHelpFlag(m.HelpFlagGettingStartedPanelDismissed) {
  184. addGettingStartedPanelToHomeDashboard(dash.Dashboard)
  185. }
  186. return Json(200, &dash)
  187. }
  188. func addGettingStartedPanelToHomeDashboard(dash *simplejson.Json) {
  189. rows := dash.Get("rows").MustArray()
  190. row := simplejson.NewFromAny(rows[0])
  191. newpanel := simplejson.NewFromAny(map[string]interface{}{
  192. "type": "gettingstarted",
  193. "id": 123123,
  194. "span": 12,
  195. })
  196. panels := row.Get("panels").MustArray()
  197. panels = append(panels, newpanel)
  198. row.Set("panels", panels)
  199. }
  200. // GetDashboardVersions returns all dashboard versions as JSON
  201. func GetDashboardVersions(c *middleware.Context) Response {
  202. dashboardId := c.ParamsInt64(":dashboardId")
  203. limit := c.QueryInt("limit")
  204. start := c.QueryInt("start")
  205. if limit == 0 {
  206. limit = 1000
  207. }
  208. query := m.GetDashboardVersionsQuery{
  209. OrgId: c.OrgId,
  210. DashboardId: dashboardId,
  211. Limit: limit,
  212. Start: start,
  213. }
  214. if err := bus.Dispatch(&query); err != nil {
  215. return ApiError(404, fmt.Sprintf("No versions found for dashboardId %d", dashboardId), err)
  216. }
  217. for _, version := range query.Result {
  218. if version.RestoredFrom == version.Version {
  219. version.Message = "Initial save (created by migration)"
  220. continue
  221. }
  222. if version.RestoredFrom > 0 {
  223. version.Message = fmt.Sprintf("Restored from version %d", version.RestoredFrom)
  224. continue
  225. }
  226. if version.ParentVersion == 0 {
  227. version.Message = "Initial save"
  228. }
  229. }
  230. return Json(200, query.Result)
  231. }
  232. // GetDashboardVersion returns the dashboard version with the given ID.
  233. func GetDashboardVersion(c *middleware.Context) Response {
  234. dashboardId := c.ParamsInt64(":dashboardId")
  235. version := c.ParamsInt(":id")
  236. query := m.GetDashboardVersionQuery{
  237. OrgId: c.OrgId,
  238. DashboardId: dashboardId,
  239. Version: version,
  240. }
  241. if err := bus.Dispatch(&query); err != nil {
  242. return ApiError(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", version, dashboardId), err)
  243. }
  244. creator := "Anonymous"
  245. if query.Result.CreatedBy > 0 {
  246. creator = getUserLogin(query.Result.CreatedBy)
  247. }
  248. dashVersionMeta := &m.DashboardVersionMeta{
  249. DashboardVersion: *query.Result,
  250. CreatedBy: creator,
  251. }
  252. return Json(200, dashVersionMeta)
  253. }
  254. // POST /api/dashboards/calculate-diff performs diffs on two dashboards
  255. func CalculateDashboardDiff(c *middleware.Context, apiOptions dtos.CalculateDiffOptions) Response {
  256. options := dashdiffs.Options{
  257. OrgId: c.OrgId,
  258. DiffType: dashdiffs.ParseDiffType(apiOptions.DiffType),
  259. Base: dashdiffs.DiffTarget{
  260. DashboardId: apiOptions.Base.DashboardId,
  261. Version: apiOptions.Base.Version,
  262. UnsavedDashboard: apiOptions.Base.UnsavedDashboard,
  263. },
  264. New: dashdiffs.DiffTarget{
  265. DashboardId: apiOptions.New.DashboardId,
  266. Version: apiOptions.New.Version,
  267. UnsavedDashboard: apiOptions.New.UnsavedDashboard,
  268. },
  269. }
  270. result, err := dashdiffs.CalculateDiff(&options)
  271. if err != nil {
  272. if err == m.ErrDashboardVersionNotFound {
  273. return ApiError(404, "Dashboard version not found", err)
  274. }
  275. return ApiError(500, "Unable to compute diff", err)
  276. }
  277. if options.DiffType == dashdiffs.DiffDelta {
  278. return Respond(200, result.Delta).Header("Content-Type", "application/json")
  279. } else {
  280. return Respond(200, result.Delta).Header("Content-Type", "text/html")
  281. }
  282. }
  283. // RestoreDashboardVersion restores a dashboard to the given version.
  284. func RestoreDashboardVersion(c *middleware.Context, apiCmd dtos.RestoreDashboardVersionCommand) Response {
  285. dashboardId := c.ParamsInt64(":dashboardId")
  286. dashQuery := m.GetDashboardQuery{Id: dashboardId, OrgId: c.OrgId}
  287. if err := bus.Dispatch(&dashQuery); err != nil {
  288. return ApiError(404, "Dashboard not found", nil)
  289. }
  290. versionQuery := m.GetDashboardVersionQuery{DashboardId: dashboardId, Version: apiCmd.Version, OrgId: c.OrgId}
  291. if err := bus.Dispatch(&versionQuery); err != nil {
  292. return ApiError(404, "Dashboard version not found", nil)
  293. }
  294. dashboard := dashQuery.Result
  295. version := versionQuery.Result
  296. saveCmd := m.SaveDashboardCommand{}
  297. saveCmd.RestoredFrom = version.Version
  298. saveCmd.OrgId = c.OrgId
  299. saveCmd.UserId = c.UserId
  300. saveCmd.Dashboard = version.Data
  301. saveCmd.Dashboard.Set("version", dashboard.Version)
  302. saveCmd.Message = fmt.Sprintf("Restored from version %d", version.Version)
  303. return PostDashboard(c, saveCmd)
  304. }
  305. func GetDashboardTags(c *middleware.Context) {
  306. query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
  307. err := bus.Dispatch(&query)
  308. if err != nil {
  309. c.JsonApiErr(500, "Failed to get tags from database", err)
  310. return
  311. }
  312. c.JSON(200, query.Result)
  313. }