dashboard.go 11 KB

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