forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
127 lines (109 loc) · 2.49 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
// Sends anonymous reports to InfluxData
package reporting
import (
"runtime"
"sync"
"time"
"github.com/influxdata/kapacitor/server/vars"
client "github.com/influxdata/usage-client/v1"
)
const reportingInterval = time.Hour * 12
type Diagnostic interface {
Error(msg string, err error)
}
// Sends anonymous usage information every 12 hours.
type Service struct {
tags client.Tags
client *client.Client
info vars.Infoer
statsTicker *time.Ticker
usageTicker *time.Ticker
closing chan struct{}
diag Diagnostic
wg sync.WaitGroup
}
func NewService(c Config, info vars.Infoer, d Diagnostic) *Service {
client := client.New("")
client.URL = c.URL
return &Service{
client: client,
info: info,
diag: d,
}
}
func (s *Service) Open() error {
if s.closing == nil {
s.closing = make(chan struct{})
}
// Populate anonymous tags
s.tags = make(client.Tags)
s.tags["version"] = s.info.Version()
s.tags["arch"] = runtime.GOARCH
s.tags["os"] = runtime.GOOS
// Send report on startup
s.wg.Add(1)
go func() {
defer s.wg.Done()
err := s.sendUsageReport()
if err != nil {
s.diag.Error("error while sending usage report on startup", err)
}
}()
// Send periodic anonymous usage stats
s.usageTicker = time.NewTicker(reportingInterval)
s.wg.Add(1)
go func() {
defer s.wg.Done()
s.usage()
}()
return nil
}
func (s *Service) Close() error {
if s.usageTicker != nil {
s.usageTicker.Stop()
}
if s.statsTicker != nil {
s.statsTicker.Stop()
}
if s.closing != nil {
close(s.closing)
}
s.wg.Wait()
return nil
}
func (s *Service) usage() {
for {
select {
case <-s.closing:
return
case <-s.usageTicker.C:
err := s.sendUsageReport()
if err != nil {
s.diag.Error("error while sending usage report", err)
}
}
}
}
// Send anonymous usage report.
func (s *Service) sendUsageReport() error {
data := client.UsageData{
Tags: s.tags,
Values: make(client.Values),
}
// Add values
data.Values[vars.ClusterIDVarName] = s.info.ClusterID().String()
data.Values[vars.ServerIDVarName] = s.info.ServerID().String()
data.Values[vars.NumTasksVarName] = s.info.NumTasks()
data.Values[vars.NumEnabledTasksVarName] = s.info.NumEnabledTasks()
data.Values[vars.NumSubscriptionsVarName] = s.info.NumSubscriptions()
data.Values[vars.UptimeVarName] = s.info.Uptime().Seconds()
usage := client.Usage{
Product: s.info.Product(),
Data: []client.UsageData{data},
}
resp, err := s.client.Save(usage)
if resp != nil {
resp.Body.Close()
}
return err
}