dashboard.go 11 KB

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