dashboard.go 14 KB

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