dashboard.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. package api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "os"
  7. "path"
  8. "strconv"
  9. "strings"
  10. "github.com/grafana/grafana/pkg/api/dtos"
  11. "github.com/grafana/grafana/pkg/bus"
  12. "github.com/grafana/grafana/pkg/components/dashdiffs"
  13. "github.com/grafana/grafana/pkg/components/simplejson"
  14. "github.com/grafana/grafana/pkg/log"
  15. "github.com/grafana/grafana/pkg/metrics"
  16. "github.com/grafana/grafana/pkg/middleware"
  17. m "github.com/grafana/grafana/pkg/models"
  18. "github.com/grafana/grafana/pkg/plugins"
  19. "github.com/grafana/grafana/pkg/services/alerting"
  20. "github.com/grafana/grafana/pkg/services/search"
  21. "github.com/grafana/grafana/pkg/setting"
  22. "github.com/grafana/grafana/pkg/util"
  23. )
  24. func isDashboardStarredByUser(c *middleware.Context, dashId int64) (bool, error) {
  25. if !c.IsSignedIn {
  26. return false, nil
  27. }
  28. query := m.IsStarredByUserQuery{UserId: c.UserId, DashboardId: dashId}
  29. if err := bus.Dispatch(&query); err != nil {
  30. return false, err
  31. }
  32. return query.Result, nil
  33. }
  34. func GetDashboard(c *middleware.Context) {
  35. slug := strings.ToLower(c.Params(":slug"))
  36. query := m.GetDashboardQuery{Slug: slug, OrgId: c.OrgId}
  37. err := bus.Dispatch(&query)
  38. if err != nil {
  39. c.JsonApiErr(404, "Dashboard not found", nil)
  40. return
  41. }
  42. isStarred, err := isDashboardStarredByUser(c, query.Result.Id)
  43. if err != nil {
  44. c.JsonApiErr(500, "Error while checking if dashboard was starred by user", err)
  45. return
  46. }
  47. dash := query.Result
  48. // Finding creator and last updater of the dashboard
  49. updater, creator := "Anonymous", "Anonymous"
  50. if dash.UpdatedBy > 0 {
  51. updater = getUserLogin(dash.UpdatedBy)
  52. }
  53. if dash.CreatedBy > 0 {
  54. creator = getUserLogin(dash.CreatedBy)
  55. }
  56. // make sure db version is in sync with json model version
  57. dash.Data.Set("version", dash.Version)
  58. dto := dtos.DashboardFullWithMeta{
  59. Dashboard: dash.Data,
  60. Meta: dtos.DashboardMeta{
  61. IsStarred: isStarred,
  62. Slug: slug,
  63. Type: m.DashTypeDB,
  64. CanStar: c.IsSignedIn,
  65. CanSave: c.OrgRole == m.ROLE_ADMIN || c.OrgRole == m.ROLE_EDITOR,
  66. CanEdit: canEditDashboard(c.OrgRole),
  67. Created: dash.Created,
  68. Updated: dash.Updated,
  69. UpdatedBy: updater,
  70. CreatedBy: creator,
  71. Version: dash.Version,
  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. func getDashboardVersionDiffOptions(c *middleware.Context, diffType dashdiffs.DiffType) (*dashdiffs.Options, error) {
  274. dashId := c.ParamsInt64(":dashboardId")
  275. if dashId == 0 {
  276. return nil, errors.New("Missing dashboardId")
  277. }
  278. versionStrings := strings.Split(c.Params(":versions"), "...")
  279. if len(versionStrings) != 2 {
  280. return nil, fmt.Errorf("bad format: urls should be in the format /versions/0...1")
  281. }
  282. BaseVersion, err := strconv.Atoi(versionStrings[0])
  283. if err != nil {
  284. return nil, fmt.Errorf("bad format: first argument is not of type int")
  285. }
  286. newVersion, err := strconv.Atoi(versionStrings[1])
  287. if err != nil {
  288. return nil, fmt.Errorf("bad format: second argument is not of type int")
  289. }
  290. options := &dashdiffs.Options{}
  291. options.DashboardId = dashId
  292. options.OrgId = c.OrgId
  293. options.BaseVersion = BaseVersion
  294. options.NewVersion = newVersion
  295. options.DiffType = diffType
  296. return options, nil
  297. }
  298. // CompareDashboardVersions compares dashboards the way the GitHub API does.
  299. func CompareDashboardVersions(c *middleware.Context) Response {
  300. options, err := getDashboardVersionDiffOptions(c, dashdiffs.DiffDelta)
  301. if err != nil {
  302. return ApiError(500, err.Error(), err)
  303. }
  304. result, err := dashdiffs.GetVersionDiff(options)
  305. if err != nil {
  306. return ApiError(500, "Unable to compute diff", err)
  307. }
  308. // here the output is already JSON, so we need to unmarshal it into a
  309. // map before marshaling the entire response
  310. deltaMap := make(map[string]interface{})
  311. err = json.Unmarshal(result.Delta, &deltaMap)
  312. if err != nil {
  313. return ApiError(500, err.Error(), err)
  314. }
  315. return Json(200, util.DynMap{
  316. "meta": util.DynMap{
  317. "baseVersion": options.BaseVersion,
  318. "newVersion": options.NewVersion,
  319. },
  320. "delta": deltaMap,
  321. })
  322. }
  323. // CompareDashboardVersionsJSON compares dashboards the way the GitHub API does,
  324. // returning a human-readable JSON diff.
  325. func CompareDashboardVersionsJSON(c *middleware.Context) Response {
  326. options, err := getDashboardVersionDiffOptions(c, dashdiffs.DiffJSON)
  327. if err != nil {
  328. return ApiError(500, err.Error(), err)
  329. }
  330. result, err := dashdiffs.GetVersionDiff(options)
  331. if err != nil {
  332. return ApiError(500, err.Error(), err)
  333. }
  334. return Respond(200, result.Delta).Header("Content-Type", "text/html")
  335. }
  336. // CompareDashboardVersionsBasic compares dashboards the way the GitHub API does,
  337. // returning a human-readable diff.
  338. func CompareDashboardVersionsBasic(c *middleware.Context) Response {
  339. options, err := getDashboardVersionDiffOptions(c, dashdiffs.DiffBasic)
  340. if err != nil {
  341. return ApiError(500, err.Error(), err)
  342. }
  343. result, err := dashdiffs.GetVersionDiff(options)
  344. if err != nil {
  345. return ApiError(500, err.Error(), err)
  346. }
  347. return Respond(200, result.Delta).Header("Content-Type", "text/html")
  348. }
  349. // RestoreDashboardVersion restores a dashboard to the given version.
  350. func RestoreDashboardVersion(c *middleware.Context, apiCmd dtos.RestoreDashboardVersionCommand) Response {
  351. dashboardId := c.ParamsInt64(":dashboardId")
  352. dashQuery := m.GetDashboardQuery{Id: dashboardId, OrgId: c.OrgId}
  353. if err := bus.Dispatch(&dashQuery); err != nil {
  354. return ApiError(404, "Dashboard not found", nil)
  355. }
  356. versionQuery := m.GetDashboardVersionQuery{DashboardId: dashboardId, Version: apiCmd.Version, OrgId: c.OrgId}
  357. if err := bus.Dispatch(&versionQuery); err != nil {
  358. return ApiError(404, "Dashboard version not found", nil)
  359. }
  360. dashboard := dashQuery.Result
  361. version := versionQuery.Result
  362. saveCmd := m.SaveDashboardCommand{}
  363. saveCmd.RestoredFrom = version.Version
  364. saveCmd.OrgId = c.OrgId
  365. saveCmd.UserId = c.UserId
  366. saveCmd.Dashboard = version.Data
  367. saveCmd.Dashboard.Set("version", dashboard.Version)
  368. saveCmd.Message = fmt.Sprintf("Restored from version %d", version.Version)
  369. return PostDashboard(c, saveCmd)
  370. }
  371. func GetDashboardTags(c *middleware.Context) {
  372. query := m.GetDashboardTagsQuery{OrgId: c.OrgId}
  373. err := bus.Dispatch(&query)
  374. if err != nil {
  375. c.JsonApiErr(500, "Failed to get tags from database", err)
  376. return
  377. }
  378. c.JSON(200, query.Result)
  379. }