Tool to help you manage your Grafana dashboards using Git.

poller.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package poller
  2. import (
  3. "time"
  4. "config"
  5. "git"
  6. "grafana"
  7. "pusher/common"
  8. "github.com/sirupsen/logrus"
  9. )
  10. func Setup(cfg *config.Config, client *grafana.Client, delRemoved bool) error {
  11. r, needsSync, err := git.NewRepository(cfg.Git)
  12. if err != nil {
  13. return err
  14. }
  15. if needsSync {
  16. if err = r.Sync(false); err != nil {
  17. return err
  18. }
  19. }
  20. errs := make(chan error, 1)
  21. go func() {
  22. if err = poller(cfg, r, client, delRemoved); err != nil {
  23. errs <- err
  24. return
  25. }
  26. }()
  27. err = <-errs
  28. return err
  29. }
  30. func poller(
  31. cfg *config.Config, repo *git.Repository, client *grafana.Client,
  32. delRemoved bool,
  33. ) (err error) {
  34. latestCommit, err := repo.GetLatestCommit()
  35. if err != nil {
  36. return
  37. }
  38. previousCommit := latestCommit
  39. for {
  40. addedOrModified := make([]string, 0)
  41. removed := make([]string, 0)
  42. if err = repo.Sync(true); err != nil {
  43. return
  44. }
  45. latestCommit, err = repo.GetLatestCommit()
  46. if err != nil {
  47. return
  48. }
  49. if previousCommit.Hash.String() != latestCommit.Hash.String() {
  50. lineCounts, err := git.GetFilesLineCountsAtCommit(previousCommit)
  51. if err != nil {
  52. return err
  53. }
  54. deltas, err := repo.LineCountsDeltasIgnoreManagerCommits(previousCommit, latestCommit)
  55. if err != nil {
  56. return err
  57. }
  58. for file, delta := range deltas {
  59. if delta == 0 {
  60. continue
  61. }
  62. if delta > 0 {
  63. addedOrModified = append(addedOrModified, file)
  64. } else if delta < 0 {
  65. if -delta < lineCounts[file] {
  66. addedOrModified = append(addedOrModified, file)
  67. } else {
  68. removed = append(removed, file)
  69. }
  70. }
  71. }
  72. }
  73. filesToPush := make(map[string][]byte)
  74. for _, filename := range addedOrModified {
  75. if err = common.PrepareForPush(filename, &filesToPush, cfg); err != nil {
  76. return err
  77. }
  78. }
  79. common.PushFiles(filesToPush, client)
  80. if delRemoved {
  81. for _, removedFile := range removed {
  82. if err = common.DeleteDashboard(
  83. removedFile, client, cfg,
  84. ); err != nil {
  85. logrus.WithFields(logrus.Fields{
  86. "error": err,
  87. "filename": removedFile,
  88. }).Error("Failed to delete the dashboard")
  89. }
  90. }
  91. }
  92. previousCommit = latestCommit
  93. time.Sleep(time.Duration(cfg.Pusher.Config.Interval) * time.Second)
  94. }
  95. }