Tool to help you manage your Grafana dashboards using Git.

webhook.go 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package main
  2. import (
  3. "io/ioutil"
  4. "strings"
  5. "config"
  6. "git"
  7. puller "puller"
  8. "gopkg.in/go-playground/webhooks.v3"
  9. "gopkg.in/go-playground/webhooks.v3/gitlab"
  10. )
  11. func SetupWebhook(cfg *config.Config) error {
  12. hook := gitlab.New(&gitlab.Config{
  13. Secret: cfg.Webhook.Secret,
  14. })
  15. hook.RegisterEvents(HandlePush, gitlab.PushEvents)
  16. return webhooks.Run(
  17. hook,
  18. cfg.Webhook.Interface+":"+cfg.Webhook.Port,
  19. cfg.Webhook.Path,
  20. )
  21. }
  22. func HandlePush(payload interface{}, header webhooks.Header) {
  23. var err error
  24. pl := payload.(gitlab.PushEventPayload)
  25. if _, err = git.Sync(cfg.Git); err != nil {
  26. panic(err)
  27. }
  28. for _, commit := range pl.Commits {
  29. // We don't want to process commits made by the puller
  30. if commit.Author.Email == cfg.Git.CommitsAuthor.Email {
  31. continue
  32. }
  33. for _, addedFile := range commit.Added {
  34. if err = pushFile(addedFile); err != nil {
  35. panic(err)
  36. }
  37. }
  38. for _, modifiedFile := range commit.Modified {
  39. if err = pushFile(modifiedFile); err != nil {
  40. panic(err)
  41. }
  42. }
  43. // TODO: Remove a dashboard when its file gets deleted?
  44. }
  45. // Grafana will auto-update the version number after we pushed the new
  46. // dashboards, so we use the puller mechanic to pull the updated numbers and
  47. // commit them in the git repo.
  48. if err = puller.PullGrafanaAndCommit(grafanaClient, cfg); err != nil {
  49. panic(err)
  50. }
  51. }
  52. func pushFile(filename string) error {
  53. filePath := cfg.Git.ClonePath + "/" + filename
  54. fileContent, err := ioutil.ReadFile(filePath)
  55. if err != nil {
  56. return err
  57. }
  58. // Remove the .json part
  59. slug := strings.Split(filename, ".json")[0]
  60. return grafanaClient.CreateOrUpdateDashboard(slug, fileContent)
  61. }