report_usage.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package metrics
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "net/http"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/bus"
  9. "github.com/grafana/grafana/pkg/log"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/setting"
  12. )
  13. func StartUsageReportLoop() chan struct{} {
  14. M_Instance_Start.Inc(1)
  15. ticker := time.NewTicker(time.Hour * 24)
  16. for {
  17. select {
  18. case <-ticker.C:
  19. sendUsageStats()
  20. }
  21. }
  22. }
  23. func sendUsageStats() {
  24. log.Trace("Sending anonymous usage stats to stats.grafana.org")
  25. version := strings.Replace(setting.BuildVersion, ".", "_", -1)
  26. metrics := map[string]interface{}{}
  27. report := map[string]interface{}{
  28. "version": version,
  29. "metrics": metrics,
  30. }
  31. statsQuery := m.GetSystemStatsQuery{}
  32. if err := bus.Dispatch(&statsQuery); err != nil {
  33. log.Error(3, "Failed to get system stats", err)
  34. return
  35. }
  36. UsageStats.Each(func(name string, i interface{}) {
  37. switch metric := i.(type) {
  38. case Counter:
  39. if metric.Count() > 0 {
  40. metrics[name+".count"] = metric.Count()
  41. metric.Clear()
  42. }
  43. }
  44. })
  45. metrics["stats.dashboards.count"] = statsQuery.Result.DashboardCount
  46. metrics["stats.users.count"] = statsQuery.Result.UserCount
  47. metrics["stats.orgs.count"] = statsQuery.Result.OrgCount
  48. out, _ := json.Marshal(report)
  49. data := bytes.NewBuffer(out)
  50. client := http.Client{Timeout: time.Duration(5 * time.Second)}
  51. go client.Post("https://stats.grafana.org/grafana-usage-report", "application/json", data)
  52. }