forked from cockroachdb/cockroach
/
updates.go
282 lines (246 loc) · 8.52 KB
/
updates.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright 2016 The Cockroach Authors.
//
// 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 server
import (
"bytes"
"encoding/json"
"io"
"math/rand"
"net/http"
"net/url"
"strconv"
"time"
"golang.org/x/net/context"
"github.com/cockroachdb/cockroach/build"
"github.com/cockroachdb/cockroach/keys"
"github.com/cockroachdb/cockroach/roachpb"
"github.com/cockroachdb/cockroach/util/log"
"github.com/cockroachdb/cockroach/util/timeutil"
)
const baseUpdatesURL = `https://register.cockroachdb.com/api/clusters/updates`
const baseReportingURL = `https://register.cockroachdb.com/api/report`
const updateCheckFrequency = time.Hour * 24
const updateCheckJitterSeconds = 120
const updateCheckRetryFrequency = time.Hour
const optinKey = serverUIDataKeyPrefix + "optin-reporting"
type versionInfo struct {
Version string `json:"version"`
Details string `json:"details"`
}
type reportingInfo struct {
Node nodeInfo `json:"node"`
Stores []storeInfo `json:"stores"`
}
type nodeInfo struct {
NodeID roachpb.NodeID `json:"node_id"`
Bytes int `json:"bytes"`
KeyCount int `json:"key_count"`
RangeCount int `json:"range_count"`
}
type storeInfo struct {
NodeID roachpb.NodeID `json:"node_id"`
StoreID roachpb.StoreID `json:"store_id"`
Bytes int `json:"bytes"`
KeyCount int `json:"key_count"`
RangeCount int `json:"range_count"`
}
// SetupReportingURLs parses the phone-home for version updates URL and should be
// called before server starts except in tests.
func (s *Server) SetupReportingURLs() error {
var err error
s.parsedUpdatesURL, err = url.Parse(baseUpdatesURL)
if err != nil {
return err
}
s.parsedReportingURL, err = url.Parse(baseReportingURL)
if err != nil {
return err
}
return nil
}
func (s *Server) periodicallyCheckForUpdates() {
s.stopper.RunWorker(func() {
startup := timeutil.Now()
for {
// `maybeCheckForUpdates` and `maybeReportUsage` both return the
// duration until they should next be checked.
// Wait for the shorter of the durations returned by the two checks.
wait := s.maybeCheckForUpdates()
if reportWait := s.maybeReportUsage(timeutil.Since(startup)); reportWait < wait {
wait = reportWait
}
jitter := rand.Intn(updateCheckJitterSeconds) - updateCheckJitterSeconds/2
wait = wait + (time.Duration(jitter) * time.Second)
select {
case <-s.stopper.ShouldDrain():
return
case <-time.After(wait):
}
}
})
}
// Determines if it is time to check for updates and does so if it is.
// Returns a duration indicating when to make the next call to this method.
func (s *Server) maybeCheckForUpdates() time.Duration {
return s.maybeRunPeriodicCheck("updates check", keys.UpdateCheckCluster, s.checkForUpdates)
}
// If the time is greater than the timestamp stored at `key`, run `f`.
// Before running `f`, the timestamp is updated forward by a small amount via
// a compare-and-swap to ensure at-most-one concurrent execution. After `f`
// executes the timestamp is set to the next execution time.
// Returns how long until `f` should be run next (i.e. when this method should
// be called again).
func (s *Server) maybeRunPeriodicCheck(op string, key roachpb.Key, f func()) time.Duration {
resp, err := s.db.Get(key)
if err != nil {
log.Infof("Error reading %s time: %v", op, err)
return updateCheckRetryFrequency
}
// We should early returned below if either the next check time is in the
// future or if the atomic compare-and-set of that time failed (which
// would happen if two nodes tried at the same time).
if resp.Exists() {
whenToCheck, pErr := resp.Value.GetTime()
if pErr != nil {
log.Warningf("Error decoding %s time: %v", op, err)
return updateCheckRetryFrequency
} else if delay := whenToCheck.Sub(timeutil.Now()); delay > 0 {
return delay
}
nextRetry := whenToCheck.Add(updateCheckRetryFrequency)
if err := s.db.CPut(key, nextRetry, whenToCheck); err != nil {
if log.V(2) {
log.Infof("Could not set next version check time (maybe another node checked?)", err)
}
return updateCheckRetryFrequency
}
} else {
log.Infof("No previous %s time.", op)
nextRetry := timeutil.Now().Add(updateCheckRetryFrequency)
// CPut with `nil` prev value to assert that no other node has checked.
if err := s.db.CPut(key, nextRetry, nil); err != nil {
if log.V(2) {
log.Infof("Could not set %s time (maybe another node checked?): %v", op, err)
}
return updateCheckRetryFrequency
}
}
f()
if err := s.db.Put(key, timeutil.Now().Add(updateCheckFrequency)); err != nil {
log.Infof("Error updating %s time: %v", op, err)
}
return updateCheckFrequency
}
func (s *Server) checkForUpdates() {
// Don't phone home in tests (SetupReportingURLs is called in cli/start.go).
if s.parsedUpdatesURL == nil {
return
}
q := s.parsedUpdatesURL.Query()
q.Set("version", build.GetInfo().Tag)
q.Set("uuid", s.node.ClusterID.String())
s.parsedUpdatesURL.RawQuery = q.Encode()
res, err := http.Get(s.parsedUpdatesURL.String())
if err != nil {
// This is probably going to be relatively common in production
// environments where network access is usually curtailed.
if log.V(2) {
log.Warning("Error checking for updates: ", err)
}
return
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
r := struct {
Details []versionInfo `json:"details"`
}{}
err = decoder.Decode(&r)
if err != nil && err != io.EOF {
log.Warning("Error decoding updates info: ", err)
return
}
for _, v := range r.Details {
log.Info("A new version is available: %s\n\t%s", v.Version, v.Details)
}
}
func (s *Server) usageReportingEnabled() bool {
// Grab the optin value from the database.
var ctx context.Context
req := &GetUIDataRequest{Keys: []string{optinKey}}
resp, err := s.admin.GetUIData(ctx, req)
if err != nil {
log.Warning(err)
return false
}
val, ok := resp.KeyValues[optinKey]
if !ok {
// Key wasn't found, so we opt out by default.
return false
}
optin, err := strconv.ParseBool(string(val.Value))
if err != nil {
log.Warningf("could not parse optin value (%q): %v", val.Value, err)
return false
}
return optin
}
func (s *Server) maybeReportUsage(running time.Duration) time.Duration {
if running < updateCheckRetryFrequency {
// On first check, we decline to report usage as metrics may not yet
// be stable, so instead we request re-evaluation after a retry delay.
return updateCheckRetryFrequency - running
}
if !s.usageReportingEnabled() {
return updateCheckFrequency
}
return s.maybeRunPeriodicCheck("metrics reporting", keys.NodeLastUsageReportKey(int32(s.node.Descriptor.NodeID)), s.reportUsage)
}
func (s *Server) getReportingInfo() reportingInfo {
n := s.node.recorder.GetStatusSummary()
summary := nodeInfo{NodeID: s.node.Descriptor.NodeID}
stores := make([]storeInfo, len(n.StoreStatuses))
for i, r := range n.StoreStatuses {
stores[i].NodeID = r.Desc.Node.NodeID
stores[i].StoreID = r.Desc.StoreID
stores[i].KeyCount = int(r.Metrics["keycount"])
summary.KeyCount += stores[i].KeyCount
stores[i].RangeCount = int(r.Metrics["replicas"])
summary.RangeCount += stores[i].RangeCount
bytes := int(r.Metrics["sysbytes"] + r.Metrics["intentbytes"] + r.Metrics["valbytes"] + r.Metrics["keybytes"])
stores[i].Bytes = bytes
summary.Bytes += bytes
}
return reportingInfo{summary, stores}
}
func (s *Server) reportUsage() {
// Don't phone home in tests (SetupReportingURLs is called in cli/start.go).
if s.parsedReportingURL == nil {
return
}
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(s.getReportingInfo()); err != nil {
log.Warning(err)
return
}
q := s.parsedReportingURL.Query()
q.Set("version", build.GetInfo().Tag)
q.Set("uuid", s.node.ClusterID.String())
s.parsedReportingURL.RawQuery = q.Encode()
_, err := http.Post(s.parsedReportingURL.String(), "application/json", b)
if err != nil && log.V(2) {
// This is probably going to be relatively common in production
// environments where network access is usually curtailed.
log.Warning("Error checking reporting node usage metrics: ", err)
}
}