dashboard.go 14 KB

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