dashboard.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. )
  12. var ImportDashboard = cli.Command{
  13. Name: "dashboards:import",
  14. Usage: "imports dashboards in JSON from a directory",
  15. Description: "Starts Grafana import process",
  16. Action: runImport,
  17. Flags: []cli.Flag{
  18. cli.StringFlag{
  19. Name: "dir",
  20. Usage: "path to folder containing json dashboards",
  21. },
  22. },
  23. }
  24. func runImport(c *cli.Context) {
  25. dir := c.String("dir")
  26. if len(dir) == 0 {
  27. log.ConsoleFatalf("Missing command flag --dir")
  28. }
  29. file, err := os.Stat(dir)
  30. if os.IsNotExist(err) {
  31. log.ConsoleFatalf("Directory does not exist: %v", dir)
  32. }
  33. if !file.IsDir() {
  34. log.ConsoleFatalf("%v is not a directory", dir)
  35. }
  36. if !c.Args().Present() {
  37. log.ConsoleFatal("Organization name arg is required")
  38. }
  39. orgName := c.Args().First()
  40. initRuntime(c)
  41. orgQuery := m.GetOrgByNameQuery{Name: orgName}
  42. if err := bus.Dispatch(&orgQuery); err != nil {
  43. log.ConsoleFatalf("Failed to find account", err)
  44. }
  45. orgId := orgQuery.Result.Id
  46. visitor := func(path string, f os.FileInfo, err error) error {
  47. if err != nil {
  48. return err
  49. }
  50. if f.IsDir() {
  51. return nil
  52. }
  53. if strings.HasSuffix(f.Name(), ".json") {
  54. if err := importDashboard(path, orgId); err != nil {
  55. log.ConsoleFatalf("Failed to import dashboard file: %v, err: %v", path, err)
  56. }
  57. }
  58. return nil
  59. }
  60. if err := filepath.Walk(dir, visitor); err != nil {
  61. log.ConsoleFatalf("Failed to scan dir for json files: %v", err)
  62. }
  63. }
  64. func importDashboard(path string, orgId int64) error {
  65. log.ConsoleInfof("Importing %v", path)
  66. reader, err := os.Open(path)
  67. if err != nil {
  68. return err
  69. }
  70. defer reader.Close()
  71. dash := m.NewDashboard("temp")
  72. jsonParser := json.NewDecoder(reader)
  73. if err := jsonParser.Decode(&dash.Data); err != nil {
  74. return err
  75. }
  76. dash.Data["id"] = nil
  77. cmd := m.SaveDashboardCommand{
  78. OrgId: orgId,
  79. Dashboard: dash.Data,
  80. }
  81. if err := bus.Dispatch(&cmd); err != nil {
  82. return err
  83. }
  84. return nil
  85. }