dashboard.go 11 KB

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