dashboard.go 11 KB

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