file_reader.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package dashboards
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/grafana/grafana/pkg/services/dashboards"
  10. "github.com/grafana/grafana/pkg/bus"
  11. "github.com/grafana/grafana/pkg/components/simplejson"
  12. "github.com/grafana/grafana/pkg/log"
  13. "github.com/grafana/grafana/pkg/models"
  14. gocache "github.com/patrickmn/go-cache"
  15. )
  16. type fileReader struct {
  17. Cfg *DashboardsAsConfig
  18. Path string
  19. log log.Logger
  20. dashboardRepo dashboards.Repository
  21. cache *gocache.Cache
  22. }
  23. func NewDashboardFileReader(cfg *DashboardsAsConfig, log log.Logger) (*fileReader, error) {
  24. path, ok := cfg.Options["folder"].(string)
  25. if !ok {
  26. return nil, fmt.Errorf("Failed to load dashboards. folder param is not a string")
  27. }
  28. if _, err := os.Stat(path); os.IsNotExist(err) {
  29. log.Error("Cannot read directory", "error", err)
  30. }
  31. return &fileReader{
  32. Cfg: cfg,
  33. Path: path,
  34. log: log,
  35. dashboardRepo: dashboards.GetRepository(),
  36. cache: gocache.New(5*time.Minute, 30*time.Minute),
  37. }, nil
  38. }
  39. func (fr *fileReader) addCache(key string, json *dashboards.SaveDashboardItem) {
  40. fr.cache.Add(key, json, time.Minute*10)
  41. }
  42. func (fr *fileReader) getCache(key string) (*dashboards.SaveDashboardItem, bool) {
  43. obj, exist := fr.cache.Get(key)
  44. if !exist {
  45. return nil, exist
  46. }
  47. dash, ok := obj.(*dashboards.SaveDashboardItem)
  48. if !ok {
  49. return nil, ok
  50. }
  51. return dash, ok
  52. }
  53. func (fr *fileReader) ReadAndListen(ctx context.Context) error {
  54. ticker := time.NewTicker(time.Second * 5)
  55. if err := fr.walkFolder(); err != nil {
  56. fr.log.Error("failed to search for dashboards", "error", err)
  57. }
  58. for {
  59. select {
  60. case <-ticker.C:
  61. fr.walkFolder()
  62. case <-ctx.Done():
  63. return nil
  64. }
  65. }
  66. }
  67. func (fr *fileReader) walkFolder() error {
  68. if _, err := os.Stat(fr.Path); err != nil {
  69. if os.IsNotExist(err) {
  70. return err
  71. }
  72. }
  73. return filepath.Walk(fr.Path, func(path string, fileInfo os.FileInfo, err error) error {
  74. if err != nil {
  75. return err
  76. }
  77. if fileInfo.IsDir() {
  78. if strings.HasPrefix(fileInfo.Name(), ".") {
  79. return filepath.SkipDir
  80. }
  81. return nil
  82. }
  83. if !strings.HasSuffix(fileInfo.Name(), ".json") {
  84. return nil
  85. }
  86. cachedDashboard, exist := fr.getCache(path)
  87. if exist && cachedDashboard.UpdatedAt == fileInfo.ModTime() {
  88. return nil
  89. }
  90. dash, err := fr.readDashboardFromFile(path)
  91. if err != nil {
  92. fr.log.Error("failed to load dashboard from ", "file", path, "error", err)
  93. return nil
  94. }
  95. cmd := &models.GetDashboardQuery{Slug: dash.Dashboard.Slug}
  96. err = bus.Dispatch(cmd)
  97. // if we dont have the dashboard in the db, save it!
  98. if err == models.ErrDashboardNotFound {
  99. fr.log.Debug("saving new dashboard", "file", path)
  100. _, err = fr.dashboardRepo.SaveDashboard(dash)
  101. return err
  102. }
  103. if err != nil {
  104. fr.log.Error("failed to query for dashboard", "slug", dash.Dashboard.Slug, "error", err)
  105. return nil
  106. }
  107. // break if db version is newer then fil version
  108. if cmd.Result.Updated.Unix() >= fileInfo.ModTime().Unix() {
  109. return nil
  110. }
  111. fr.log.Debug("loading dashboard from disk into database.", "file", path)
  112. _, err = fr.dashboardRepo.SaveDashboard(dash)
  113. return err
  114. })
  115. }
  116. func (fr *fileReader) readDashboardFromFile(path string) (*dashboards.SaveDashboardItem, error) {
  117. reader, err := os.Open(path)
  118. if err != nil {
  119. return nil, err
  120. }
  121. defer reader.Close()
  122. data, err := simplejson.NewFromReader(reader)
  123. if err != nil {
  124. return nil, err
  125. }
  126. stat, err := os.Stat(path)
  127. if err != nil {
  128. return nil, err
  129. }
  130. dash, err := createDashboardJson(data, stat.ModTime(), fr.Cfg)
  131. if err != nil {
  132. return nil, err
  133. }
  134. fr.addCache(path, dash)
  135. return dash, nil
  136. }