dashboard.go 13 KB

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