config_reader.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package dashboards
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/grafana/grafana/pkg/log"
  9. yaml "gopkg.in/yaml.v2"
  10. )
  11. type configReader struct {
  12. path string
  13. log log.Logger
  14. }
  15. func (cr *configReader) parseConfigs(file os.FileInfo) ([]*DashboardsAsConfig, error) {
  16. filename, _ := filepath.Abs(filepath.Join(cr.path, file.Name()))
  17. yamlFile, err := ioutil.ReadFile(filename)
  18. if err != nil {
  19. return nil, err
  20. }
  21. apiVersion := &ConfigVersion{ApiVersion: 0}
  22. yaml.Unmarshal(yamlFile, &apiVersion)
  23. if apiVersion.ApiVersion > 0 {
  24. v1 := &DashboardAsConfigV1{}
  25. err := yaml.Unmarshal(yamlFile, &v1)
  26. if err != nil {
  27. return nil, err
  28. }
  29. if v1 != nil {
  30. return v1.mapToDashboardAsConfig(), nil
  31. }
  32. } else {
  33. var v0 []*DashboardsAsConfigV0
  34. err := yaml.Unmarshal(yamlFile, &v0)
  35. if err != nil {
  36. return nil, err
  37. }
  38. if v0 != nil {
  39. cr.log.Warn("[Deprecated] the dashboard provisioning config is outdated. please upgrade", "filename", filename)
  40. return mapV0ToDashboardAsConfig(v0), nil
  41. }
  42. }
  43. return []*DashboardsAsConfig{}, nil
  44. }
  45. func (cr *configReader) readConfig() ([]*DashboardsAsConfig, error) {
  46. var dashboards []*DashboardsAsConfig
  47. files, err := ioutil.ReadDir(cr.path)
  48. if err != nil {
  49. cr.log.Error("can't read dashboard provisioning files from directory", "path", cr.path)
  50. return dashboards, nil
  51. }
  52. for _, file := range files {
  53. if !strings.HasSuffix(file.Name(), ".yaml") && !strings.HasSuffix(file.Name(), ".yml") {
  54. continue
  55. }
  56. parsedDashboards, err := cr.parseConfigs(file)
  57. if err != nil {
  58. return nil, fmt.Errorf("could not parse provisioning config file: %s error: %v", file.Name(), err)
  59. }
  60. if len(parsedDashboards) > 0 {
  61. dashboards = append(dashboards, parsedDashboards...)
  62. }
  63. }
  64. for i := range dashboards {
  65. if dashboards[i].OrgId == 0 {
  66. dashboards[i].OrgId = 1
  67. }
  68. if dashboards[i].UpdateIntervalSeconds == 0 {
  69. dashboards[i].UpdateIntervalSeconds = 10
  70. }
  71. }
  72. return dashboards, nil
  73. }