dashboard.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. package cmd
  2. import (
  3. "encoding/json"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "github.com/codegangsta/cli"
  8. "github.com/grafana/grafana/pkg/bus"
  9. "github.com/grafana/grafana/pkg/log"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/services/sqlstore"
  12. "github.com/grafana/grafana/pkg/setting"
  13. )
  14. var ImportJson = cli.Command{
  15. Name: "dashboard:import",
  16. Usage: "imports dashboards in JSON from a directory",
  17. Description: "Starts Grafana import process",
  18. Action: runImport,
  19. Flags: []cli.Flag{
  20. cli.StringFlag{
  21. Name: "dir",
  22. Usage: "path to folder containing json dashboards",
  23. },
  24. },
  25. }
  26. func runImport(c *cli.Context) {
  27. dir := c.String("dir")
  28. if len(dir) == 0 {
  29. log.ConsoleFatalf("Missing command flag --dir")
  30. }
  31. file, err := os.Stat(dir)
  32. if os.IsNotExist(err) {
  33. log.ConsoleFatalf("Directory does not exist: %v", dir)
  34. }
  35. if !file.IsDir() {
  36. log.ConsoleFatalf("%v is not a directory", dir)
  37. }
  38. if !c.Args().Present() {
  39. log.ConsoleFatal("Account name arg is required")
  40. }
  41. accountName := c.Args().First()
  42. setting.NewConfigContext()
  43. sqlstore.NewEngine()
  44. sqlstore.EnsureAdminUser()
  45. accountQuery := m.GetAccountByNameQuery{Name: accountName}
  46. if err := bus.Dispatch(&accountQuery); err != nil {
  47. log.ConsoleFatalf("Failed to find account", err)
  48. }
  49. accountId := accountQuery.Result.Id
  50. visitor := func(path string, f os.FileInfo, err error) error {
  51. if err != nil {
  52. return err
  53. }
  54. if f.IsDir() {
  55. return nil
  56. }
  57. if strings.HasSuffix(f.Name(), ".json") {
  58. if err := importDashboard(path, accountId); err != nil {
  59. log.ConsoleFatalf("Failed to import dashboard file: %v, err: %v", path, err)
  60. }
  61. }
  62. return nil
  63. }
  64. if err := filepath.Walk(dir, visitor); err != nil {
  65. log.ConsoleFatalf("Failed to scan dir for json files: %v", err)
  66. }
  67. }
  68. func importDashboard(path string, accountId int64) error {
  69. log.ConsoleInfof("Importing %v", path)
  70. reader, err := os.Open(path)
  71. if err != nil {
  72. return err
  73. }
  74. dash := m.NewDashboard("temp")
  75. jsonParser := json.NewDecoder(reader)
  76. if err := jsonParser.Decode(&dash.Data); err != nil {
  77. return err
  78. }
  79. dash.Data["id"] = nil
  80. cmd := m.SaveDashboardCommand{
  81. AccountId: accountId,
  82. Dashboard: dash.Data,
  83. }
  84. if err := bus.Dispatch(&cmd); err != nil {
  85. return err
  86. }
  87. return nil
  88. }