report_usage.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. UsageStats.Each(func(name string, i interface{}) {
  32. switch metric := i.(type) {
  33. case Counter:
  34. if metric.Count() > 0 {
  35. metrics[name+".count"] = metric.Count()
  36. metric.Clear()
  37. }
  38. }
  39. })
  40. statsQuery := m.GetSystemStatsQuery{}
  41. if err := bus.Dispatch(&statsQuery); err != nil {
  42. log.Error(3, "Failed to get system stats", err)
  43. return
  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. metrics["stats.playlist.count"] = statsQuery.Result.PlaylistCount
  49. dsStats := m.GetDataSourceStatsQuery{}
  50. if err := bus.Dispatch(&dsStats); err != nil {
  51. log.Error(3, "Failed to get datasource stats", err)
  52. return
  53. }
  54. // send counters for each data source
  55. // but ignore any custom data sources
  56. // as sending that name could be sensitive information
  57. dsOtherCount := 0
  58. for _, dsStat := range dsStats.Result {
  59. if m.IsKnownDataSourcePlugin(dsStat.Type) {
  60. metrics["stats.ds."+dsStat.Type+".count"] = dsStat.Count
  61. } else {
  62. dsOtherCount += dsStat.Count
  63. }
  64. }
  65. metrics["stats.ds.other.count"] = dsOtherCount
  66. out, _ := json.MarshalIndent(report, "", " ")
  67. data := bytes.NewBuffer(out)
  68. client := http.Client{Timeout: time.Duration(5 * time.Second)}
  69. go client.Post("https://stats.grafana.org/grafana-usage-report", "application/json", data)
  70. }