dashboard.go 14 KB

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