forked from grafana/grafana
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdynamic.go
342 lines (303 loc) · 10.8 KB
/
dynamic.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package angulardetectorsprovider
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"sync"
"time"
"github.com/grafana/grafana/pkg/plugins/log"
"github.com/grafana/grafana/pkg/plugins/manager/loader/angular/angulardetector"
"github.com/grafana/grafana/pkg/registry"
"github.com/grafana/grafana/pkg/services/pluginsintegration/angularpatternsstore"
"github.com/grafana/grafana/pkg/setting"
)
var errNotModified = errors.New("not modified")
// Intervals that passes between background job runs.
// Can be overwritten in tests.
var (
backgroundJobIntervalOnPrem = time.Hour * 24
backgroundJobIntervalCloud = time.Hour * 1
)
// Dynamic is an angulardetector.DetectorsProvider that calls GCOM to get Angular detection patterns,
// converts them to detectors and caches them for all future calls.
// It also provides a background service that will periodically refresh the patterns from GCOM.
type Dynamic struct {
log log.Logger
httpClient http.Client
baseURL string
disabled bool
// store is the underlying angular patterns store used as a cache.
store angularpatternsstore.Service
// detectors contains the cached angular detectors, which are created from the remote angular patterns.
// mux should be acquired before reading from/writing to this field.
detectors []angulardetector.AngularDetector
// mux is the mutex used to read/write the cached detectors in a concurrency-safe way.
mux sync.RWMutex
// backgroundJobInterval is the interval that passes between background job runs.
backgroundJobInterval time.Duration
}
func ProvideDynamic(cfg *setting.Cfg, store angularpatternsstore.Service) (*Dynamic, error) {
backgroundJobInterval := backgroundJobIntervalOnPrem
if cfg.StackID != "" {
// Use a shorter interval for cloud.
// (in cloud, cfg.StackID is always set).
backgroundJobInterval = backgroundJobIntervalCloud
}
d := &Dynamic{
log: log.New("plugin.angulardetectorsprovider.dynamic"),
store: store,
httpClient: makeHttpClient(),
baseURL: cfg.GrafanaComAPIURL,
backgroundJobInterval: backgroundJobInterval,
// Disable the background service if the user has opted out of plugin updates.
// (useful for air-gapped installations)
disabled: !cfg.CheckForPluginUpdates,
}
d.log.Debug("Providing dynamic angular detection patterns", "baseURL", d.baseURL, "interval", d.backgroundJobInterval)
// Perform the initial restore from db
st := time.Now()
d.log.Debug("Restoring cache")
d.mux.Lock()
if err := d.setDetectorsFromCache(context.Background()); err != nil {
d.log.Warn("Cache restore failed", "error", err)
} else {
d.log.Info("Restored cache from database", "duration", time.Since(st))
}
d.mux.Unlock()
return d, nil
}
// patternsToDetectors converts a slice of gcomPattern into a slice of angulardetector.AngularDetector, by calling
// angularDetector() on each gcomPattern.
func (d *Dynamic) patternsToDetectors(patterns GCOMPatterns) ([]angulardetector.AngularDetector, error) {
var finalErr error
detectors := make([]angulardetector.AngularDetector, 0, len(patterns))
for _, pattern := range patterns {
ad, err := pattern.angularDetector()
if err != nil {
// Fail silently in case of an errUnknownPatternType.
// This allows us to introduce new pattern types without breaking old Grafana versions
if errors.Is(err, errUnknownPatternType) {
d.log.Debug("Unknown angular pattern", "name", pattern.Name, "type", pattern.Type, "error", err)
continue
}
// Other error, do not ignore it
finalErr = errors.Join(finalErr, err)
}
detectors = append(detectors, ad)
}
if finalErr != nil {
return nil, finalErr
}
return detectors, nil
}
type GCOMResponse struct {
Patterns GCOMPatterns
ETag string
}
// fetch fetches the angular patterns from GCOM and returns them as GCOMPatterns.
// Call detectors() on the returned value to get the corresponding detectors.
// If etag is not empty, it will be sent as If-None-Match header.
// If the response status code is 304, it returns errNotModified.
func (d *Dynamic) fetch(ctx context.Context, etag string) (GCOMResponse, error) {
st := time.Now()
reqURL, err := url.JoinPath(d.baseURL, gcomAngularPatternsPath)
if err != nil {
return GCOMResponse{}, fmt.Errorf("url joinpath: %w", err)
}
d.log.Debug("Fetching dynamic angular detection patterns", "url", reqURL)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
if err != nil {
return GCOMResponse{}, fmt.Errorf("new request with context: %w", err)
}
if etag != "" {
req.Header.Add("If-None-Match", etag)
}
var r GCOMResponse
resp, err := d.httpClient.Do(req)
if err != nil {
return GCOMResponse{}, fmt.Errorf("http do: %w", err)
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
d.log.Error("Response body close error", "error", err)
}
}()
if resp.StatusCode == http.StatusNotModified {
return GCOMResponse{}, errNotModified
}
if resp.StatusCode/100 != 2 {
return GCOMResponse{}, fmt.Errorf("bad status code: %d", resp.StatusCode)
}
if err := json.NewDecoder(resp.Body).Decode(&r.Patterns); err != nil {
return GCOMResponse{}, fmt.Errorf("json decode: %w", err)
}
r.ETag = resp.Header.Get("ETag")
d.log.Debug("Fetched dynamic angular detection patterns", "patterns", len(r.Patterns), "duration", time.Since(st))
return r, nil
}
// updateDetectors fetches the patterns from GCOM, converts them to detectors,
// stores the patterns in the database and update the cached detectors.
func (d *Dynamic) updateDetectors(ctx context.Context, etag string) error {
// Fetch patterns from GCOM
d.mux.Lock()
defer d.mux.Unlock()
resp, err := d.fetch(ctx, etag)
switch {
case err == nil:
break
case errors.Is(err, errNotModified):
// If patterns did not change, update the last updated anyways,
// so we don't keep trying to fetch them, but update the in-memory
// detectors from the previously stored value.
d.log.Debug("Not modified, skipping update")
if err := d.store.SetLastUpdated(ctx); err != nil {
return fmt.Errorf("set last updated: %w", err)
}
// Update in-memory detectors, by reading current value in the kvstore
if err := d.setDetectorsFromCache(ctx); err != nil {
return fmt.Errorf("set detectors from cache: %w", err)
}
return nil
default:
return fmt.Errorf("fetch: %w", err)
}
// Convert the patterns to detectors
newDetectors, err := d.patternsToDetectors(resp.Patterns)
if err != nil {
return fmt.Errorf("patterns convert to detectors: %w", err)
}
// Update store only if the patterns can be converted to detectors
if err := d.store.Set(ctx, resp.Patterns); err != nil {
return fmt.Errorf("store set: %w", err)
}
if err := d.store.SetETag(ctx, resp.ETag); err != nil {
return fmt.Errorf("store set etag: %w", err)
}
// Update cached detectors
d.detectors = newDetectors
return nil
}
// setDetectorsFromCache sets the in-memory detectors from the patterns in the store.
// The caller must Lock d.mux before calling this function.
func (d *Dynamic) setDetectorsFromCache(ctx context.Context) error {
var cachedPatterns GCOMPatterns
rawCached, ok, err := d.store.Get(ctx)
if !ok {
// No cached value found, do not alter in-memory detectors
return nil
}
if err != nil {
return fmt.Errorf("get cached value: %w", err)
}
// Try to unmarshal, convert to detectors and set local cache
if err := json.Unmarshal([]byte(rawCached), &cachedPatterns); err != nil {
return fmt.Errorf("json unmarshal: %w", err)
}
cachedDetectors, err := d.patternsToDetectors(cachedPatterns)
if err != nil {
return fmt.Errorf("convert to detectors: %w", err)
}
d.detectors = cachedDetectors
return nil
}
// randomSkew returns a random time.Duration between 0 and maxSkew.
// This can be added to d.backgroundJobInterval to skew it by a random amount.
func (d *Dynamic) randomSkew(maxSkew time.Duration) time.Duration {
return time.Duration(rand.Float64() * float64(maxSkew))
}
// Run is the function implementing the background service and updates the detectors periodically.
func (d *Dynamic) Run(ctx context.Context) error {
d.log.Debug("Started background service")
// Determine when next run is, and check if we should run immediately
lastUpdate, err := d.store.GetLastUpdated(ctx)
if err != nil {
return fmt.Errorf("get last updated: %w", err)
}
// Offset the background job interval a bit to skew GCOM calls from all instances,
// so GCOM is not overwhelmed with lots of requests all at the same time.
// Important when lots of HG instances restart at the same time.
skew := d.randomSkew(d.backgroundJobInterval / 4)
d.backgroundJobInterval += skew
d.log.Debug(
"Applied background job skew",
"skew", d.backgroundJobInterval, "interval", d.backgroundJobInterval,
)
nextRunUntil := time.Until(lastUpdate.Add(d.backgroundJobInterval))
ticker := time.NewTicker(d.backgroundJobInterval)
defer ticker.Stop()
var tick <-chan time.Time
if nextRunUntil <= 0 {
// Do first run immediately
firstTick := make(chan time.Time, 1)
tick = firstTick
firstTick <- time.Now()
} else {
// Do first run after a certain amount of time
ticker.Reset(nextRunUntil)
tick = ticker.C
}
// Keep running periodically
for {
select {
case <-tick:
st := time.Now()
d.log.Debug("Updating patterns")
etag, ok, err := d.store.GetETag(context.Background())
if err != nil {
d.log.Error("Error while getting etag", "error", err)
}
// Ensure etag is empty if we don't have a value
if !ok {
etag = ""
}
if err := d.updateDetectors(context.Background(), etag); err != nil {
d.log.Error("Error while updating detectors", "error", err)
}
d.log.Info("Patterns update finished", "duration", time.Since(st))
// Restore default ticker if we run with a shorter interval the first time
ticker.Reset(d.backgroundJobInterval)
tick = ticker.C
case <-ctx.Done():
return ctx.Err()
}
}
}
// IsDisabled returns whether the dynamic detectors provider background service is disabled.
func (d *Dynamic) IsDisabled() bool {
return d.disabled
}
// ProvideDetectors returns the cached detectors. It returns an empty slice if there's no value.
func (d *Dynamic) ProvideDetectors(_ context.Context) []angulardetector.AngularDetector {
d.mux.RLock()
r := d.detectors
d.mux.RUnlock()
return r
}
// Same configuration as pkg/plugins/repo/client.go
func makeHttpClient() http.Client {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
return http.Client{
Timeout: 10 * time.Second,
Transport: tr,
}
}
// static checks
var (
_ registry.BackgroundService = (*Dynamic)(nil)
_ registry.CanBeDisabled = (*Dynamic)(nil)
)