forked from projectcalico/felix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
usagerep.go
203 lines (187 loc) · 5.98 KB
/
usagerep.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
// Copyright (c) 2016-2018 Tigera, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package usagerep
import (
"context"
"encoding/json"
"fmt"
"math/rand"
"net/http"
"net/url"
"time"
log "github.com/sirupsen/logrus"
"github.com/projectcalico/felix/buildinfo"
"github.com/projectcalico/felix/calc"
"github.com/projectcalico/felix/jitter"
)
const (
DefaultBaseURL = "https://usage.projectcalico.org/UsageCheck/calicoVersionCheck?"
)
func New(
initialDelay time.Duration,
interval time.Duration,
statsUpdateC <-chan calc.StatsUpdate,
configUpdateC <-chan map[string]string,
) *UsageReporter {
return &UsageReporter{
interval: interval,
statsUpdateC: statsUpdateC,
configUpdateC: configUpdateC,
InitialDelay: initialDelay,
BaseURL: DefaultBaseURL,
httpClient: http.Client{
// Short timeout to make sure we don't block on the request, leaving the channels
// starved for too long.
Timeout: 5 * time.Second,
},
}
}
type UsageReporter struct {
interval time.Duration
statsUpdateC <-chan calc.StatsUpdate
configUpdateC <-chan map[string]string
InitialDelay time.Duration
BaseURL string
httpClient http.Client
}
func (u *UsageReporter) PeriodicallyReportUsage(ctx context.Context) {
var stats calc.StatsUpdate
var config map[string]string
var receivedFirstStats bool
var tickerC <-chan time.Time
initialDelayStarted := false
initialDelayDone := make(chan struct{})
maybeStartInitialDelay := func() {
if !receivedFirstStats || config == nil || initialDelayStarted {
return
}
// To avoid thundering herd, inject some startup jitter.
initialDelay := u.calculateInitialDelay(stats.NumHosts)
go func() {
log.WithField("delay", initialDelay).Info("Waiting before first check-in")
time.Sleep(initialDelay)
close(initialDelayDone)
}()
initialDelayStarted = true
}
doReport := func() {
alpEnabled := (config["PolicySyncPathPrefix"] != "")
u.reportUsage(config["ClusterGUID"], config["ClusterType"], config["CalicoVersion"], alpEnabled, stats)
}
var ticker *jitter.Ticker
for {
select {
case stats = <-u.statsUpdateC:
log.WithField("stats", stats).Debug("Received stats update")
receivedFirstStats = true
maybeStartInitialDelay()
case config = <-u.configUpdateC:
log.WithField("config", config).Debug("Received config update")
maybeStartInitialDelay()
case <-initialDelayDone:
log.Info("Initial delay complete, doing first report")
doReport()
log.Info("First report done, starting ticker")
baseInterval := u.interval * 9 / 10
maxJitter := u.interval - baseInterval
ticker = jitter.NewTicker(baseInterval, maxJitter)
// Disable further kicks from this now-closed channel.
initialDelayDone = nil
// Enabled the main ticker loop.
tickerC = ticker.C
case <-tickerC:
log.Debug("Received tick")
doReport()
case <-ctx.Done():
log.Warn("Context stopped")
if ticker != nil {
ticker.Stop()
}
return
}
}
}
func (u *UsageReporter) calculateInitialDelay(numHosts int) time.Duration {
// Clamp numHosts so that we don't pass anything out-of-range to rand.Intn().
if numHosts <= 0 {
numHosts = 1
}
if numHosts > 10000 {
numHosts = 10000
}
initialJitter := time.Duration(rand.Intn(numHosts*1000)) * time.Millisecond
// To avoid spamming the server if we're in a cyclic restart, delay the first report by
// a few minutes.
initialDelay := u.InitialDelay + initialJitter
return initialDelay
}
func (u *UsageReporter) reportUsage(clusterGUID, clusterType, calicoVersion string, alpEnabled bool, stats calc.StatsUpdate) {
fullURL := u.calculateURL(clusterGUID, clusterType, calicoVersion, alpEnabled, stats)
resp, err := u.httpClient.Get(fullURL)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
log.WithError(err).Info("Failed to report usage/get deprecation warnings.")
return
}
jsonResp := map[string]interface{}{}
if err := json.NewDecoder(resp.Body).Decode(&jsonResp); err != nil {
log.WithError(err).Warn(
"Failed to decode report server response")
return
} else {
log.WithField("json", jsonResp).Debug("Response")
}
if warn, ok := jsonResp["usage_warning"]; ok {
log.Warnf("Usage warning: %v", warn)
}
}
func (u *UsageReporter) calculateURL(clusterGUID, clusterType, calicoVersion string, alpEnabled bool, stats calc.StatsUpdate) string {
if clusterType == "" {
clusterType = "unknown"
}
if calicoVersion == "" {
calicoVersion = "unknown"
}
if clusterGUID == "" {
clusterGUID = "baddecaf"
}
log.WithFields(log.Fields{
"clusterGUID": clusterGUID,
"clusterType": clusterType,
"calicoVersion": calicoVersion,
"alpEnabled": alpEnabled,
"stats": stats,
"version": buildinfo.GitVersion,
"gitRevision": buildinfo.GitRevision,
}).Info("Reporting cluster usage/checking for deprecation warnings.")
queryParams := url.Values{
"guid": {clusterGUID},
"type": {clusterType},
"cal_ver": {calicoVersion},
"alp": {fmt.Sprint(alpEnabled)},
"size": {fmt.Sprint(stats.NumHosts)},
"weps": {fmt.Sprint(stats.NumWorkloadEndpoints)},
"heps": {fmt.Sprint(stats.NumHostEndpoints)},
"version": {buildinfo.GitVersion},
"rev": {buildinfo.GitRevision},
"policies": {fmt.Sprint(stats.NumPolicies)},
"profiles": {fmt.Sprint(stats.NumProfiles)},
"alp_policies": {fmt.Sprint(stats.NumALPPolicies)},
}
fullURL := u.BaseURL + queryParams.Encode()
log.WithField("url", fullURL).Debug("Calculated URL.")
return fullURL
}