Tool to help you manage your Grafana dashboards using Git.

webhook.go 1.6KB

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