Tool to help you manage your Grafana dashboards using Git.

poller.go 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. filesContents, err := repo.GetFilesContentsAtCommit(latestCommit)
  39. if err != nil {
  40. return
  41. }
  42. previousCommit := latestCommit
  43. previousFilesContents := filesContents
  44. for {
  45. if err = repo.Sync(true); err != nil {
  46. return
  47. }
  48. latestCommit, err = repo.GetLatestCommit()
  49. if err != nil {
  50. return
  51. }
  52. if previousCommit.Hash.String() != latestCommit.Hash.String() {
  53. logrus.WithFields(logrus.Fields{
  54. "previous_hash": previousCommit.Hash.String(),
  55. "new_hash": latestCommit.Hash.String(),
  56. }).Info("New commit(s) detected")
  57. filesContents, err = repo.GetFilesContentsAtCommit(latestCommit)
  58. if err != nil {
  59. return err
  60. }
  61. modified, removed, err := repo.GetModifiedAndRemovedFiles(previousCommit, latestCommit)
  62. if err != nil {
  63. return err
  64. }
  65. mergedContents := mergeContents(modified, removed, filesContents, previousFilesContents)
  66. common.PushFiles(modified, mergedContents, client)
  67. if delRemoved {
  68. common.DeleteDashboards(removed, mergedContents, client)
  69. }
  70. }
  71. previousCommit = latestCommit
  72. previousFilesContents = filesContents
  73. time.Sleep(time.Duration(cfg.Pusher.Config.Interval) * time.Second)
  74. }
  75. }
  76. func mergeContents(
  77. modified []string, removed []string,
  78. filesContents map[string][]byte, previousFilesContents map[string][]byte,
  79. ) (merged map[string][]byte) {
  80. merged = make(map[string][]byte)
  81. for _, modifiedFile := range modified {
  82. merged[modifiedFile] = filesContents[modifiedFile]
  83. }
  84. for _, removedFile := range removed {
  85. merged[removedFile] = previousFilesContents[removedFile]
  86. }
  87. return
  88. }