-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
cache.go
332 lines (306 loc) · 8.46 KB
/
cache.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
// Copyright 2020 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"time"
"github.com/google/syzkaller/pkg/hash"
"github.com/google/syzkaller/pkg/image"
"google.golang.org/appengine/v2"
"google.golang.org/appengine/v2/log"
"google.golang.org/appengine/v2/memcache"
)
type Cached struct {
MissingBackports int
Total CachedBugStats
Subsystems map[string]CachedBugStats
NoSubsystem CachedBugStats
}
type CachedBugStats struct {
Open int
Fixed int
Invalid int
}
func CacheGet(c context.Context, r *http.Request, ns string) (*Cached, error) {
accessLevel := accessLevel(c, r)
v := new(Cached)
_, err := memcache.Gob.Get(c, cacheKey(ns, accessLevel), v)
if err != nil && err != memcache.ErrCacheMiss {
return nil, err
}
if err == nil {
return v, nil
}
bugs, _, err := loadNamespaceBugs(c, ns)
if err != nil {
return nil, err
}
backports, err := loadAllBackports(c)
if err != nil {
return nil, err
}
return buildAndStoreCached(c, bugs, backports, ns, accessLevel)
}
var cacheAccessLevels = []AccessLevel{AccessPublic, AccessUser, AccessAdmin}
// cacheUpdate updates memcache every hour (called by cron.yaml).
// Cache update is slow and we don't want to slow down user requests.
func cacheUpdate(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
backports, err := loadAllBackports(c)
if err != nil {
log.Errorf(c, "failed load backports: %v", err)
return
}
for ns := range getConfig(c).Namespaces {
bugs, _, err := loadNamespaceBugs(c, ns)
if err != nil {
log.Errorf(c, "failed load ns=%v bugs: %v", ns, err)
continue
}
for _, accessLevel := range cacheAccessLevels {
_, err := buildAndStoreCached(c, bugs, backports, ns, accessLevel)
if err != nil {
log.Errorf(c, "failed to build cached for ns=%v access=%v: %v", ns, accessLevel, err)
continue
}
}
}
}
func buildAndStoreCached(c context.Context, bugs []*Bug, backports []*rawBackport,
ns string, accessLevel AccessLevel) (*Cached, error) {
v := &Cached{
Subsystems: make(map[string]CachedBugStats),
}
for _, bug := range bugs {
if bug.Status == BugStatusOpen && accessLevel < bug.sanitizeAccess(c, accessLevel) {
continue
}
v.Total.Record(bug)
subsystems := bug.LabelValues(SubsystemLabel)
for _, label := range subsystems {
stats := v.Subsystems[label.Value]
stats.Record(bug)
v.Subsystems[label.Value] = stats
}
if len(subsystems) == 0 {
v.NoSubsystem.Record(bug)
}
}
for _, backport := range backports {
outgoing := stringInList(backport.FromNs, ns)
for _, bug := range backport.Bugs {
if accessLevel < bug.sanitizeAccess(c, accessLevel) {
continue
}
if bug.Namespace == ns || outgoing {
v.MissingBackports++
}
}
}
item := &memcache.Item{
Key: cacheKey(ns, accessLevel),
Object: v,
Expiration: 4 * time.Hour, // supposed to be updated by cron every hour
}
if err := memcache.Gob.Set(c, item); err != nil {
return nil, err
}
return v, nil
}
func (c *CachedBugStats) Record(bug *Bug) {
switch bug.Status {
case BugStatusOpen:
if len(bug.Commits) == 0 {
c.Open++
} else {
c.Fixed++
}
case BugStatusFixed:
c.Fixed++
case BugStatusInvalid:
c.Invalid++
}
}
func cacheKey(ns string, accessLevel AccessLevel) string {
return fmt.Sprintf("%v-%v", ns, accessLevel)
}
func CachedBugGroups(c context.Context, ns string, accessLevel AccessLevel) ([]*uiBugGroup, error) {
item, err := memcache.Get(c, cachedBugGroupsKey(ns, accessLevel))
if err == memcache.ErrCacheMiss {
return nil, nil
}
if err != nil {
return nil, err
}
jsonData, destructor := image.MustDecompress(item.Value)
defer destructor()
var ret []*uiBugGroup
err = json.Unmarshal(jsonData, &ret)
return ret, err
}
func cachedBugGroupsKey(ns string, accessLevel AccessLevel) string {
return fmt.Sprintf("%v-%v-bug-groups", ns, accessLevel)
}
// minuteCacheUpdate updates memcache every minute (called by cron.yaml).
func handleMinuteCacheUpdate(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
for ns, nsConfig := range getConfig(c).Namespaces {
if !nsConfig.CacheUIPages {
continue
}
err := minuteCacheNsUpdate(c, ns)
if err != nil {
http.Error(w, fmt.Sprintf("bug groups cache update for %s failed: %v", ns, err),
http.StatusInternalServerError)
return
}
}
}
func minuteCacheNsUpdate(c context.Context, ns string) error {
bugs, err := loadVisibleBugs(c, ns, nil)
if err != nil {
return err
}
managers, err := managerList(c, ns)
if err != nil {
return err
}
for _, accessLevel := range cacheAccessLevels {
groups, err := prepareBugGroups(c, bugs, managers, accessLevel, ns)
if err != nil {
return fmt.Errorf("failed to fetch groups: %w", err)
}
encoded, err := json.Marshal(groups)
if err != nil {
return fmt.Errorf("failed to marshal: %w", err)
}
item := &memcache.Item{
Key: cachedBugGroupsKey(ns, accessLevel),
// The resulting blob can be quite big, so let's compress.
Value: image.Compress(encoded),
Expiration: 2 * time.Minute, // supposed to be updated by cron every minute
}
if err := memcache.Set(c, item); err != nil {
return err
}
}
return nil
}
func CachedManagerList(c context.Context, ns string) ([]string, error) {
return cachedObjectList(c,
fmt.Sprintf("%s-managers-list", ns),
time.Minute,
func(c context.Context) ([]string, error) {
return managerList(c, ns)
},
)
}
func CachedUIManagers(c context.Context, accessLevel AccessLevel, ns string,
filter *userBugFilter) ([]*uiManager, error) {
return cachedObjectList(c,
fmt.Sprintf("%s-%v-%v-ui-managers", ns, accessLevel, filter.Hash()),
5*time.Minute,
func(c context.Context) ([]*uiManager, error) {
return loadManagers(c, accessLevel, ns, filter)
},
)
}
func cachedObjectList[T any](c context.Context, key string, period time.Duration,
load func(context.Context) ([]T, error)) ([]T, error) {
// Check if the object is in cache.
var obj []T
_, err := memcache.Gob.Get(c, key, &obj)
if err == nil {
return obj, nil
} else if err != memcache.ErrCacheMiss {
return nil, err
}
// Load the object.
obj, err = load(c)
if err != nil {
return nil, err
}
item := &memcache.Item{
Key: key,
Object: obj,
Expiration: period,
}
if err := memcache.Gob.Set(c, item); err != nil {
return nil, err
}
return obj, nil
}
type RequesterInfo struct {
Requests []time.Time
}
func (ri *RequesterInfo) Record(now time.Time, cfg ThrottleConfig) bool {
var newRequests []time.Time
for _, req := range ri.Requests {
if now.Sub(req) >= cfg.Window {
continue
}
newRequests = append(newRequests, req)
}
newRequests = append(newRequests, now)
sort.Slice(ri.Requests, func(i, j int) bool { return ri.Requests[i].Before(ri.Requests[j]) })
// Don't store more than needed.
if len(newRequests) > cfg.Limit+1 {
newRequests = newRequests[len(newRequests)-(cfg.Limit+1):]
}
ri.Requests = newRequests
// Check that we satisfy the conditions.
return len(newRequests) <= cfg.Limit
}
var ErrThrottleTooManyRetries = errors.New("all attempts to record request failed")
func ThrottleRequest(c context.Context, requesterID string) (bool, error) {
cfg := getConfig(c).Throttle
if cfg.Empty() || requesterID == "" {
// No sense to query memcached.
return true, nil
}
key := fmt.Sprintf("requester-%s", hash.String([]byte(requesterID)))
const attempts = 5
for i := 0; i < attempts; i++ {
var obj RequesterInfo
item, err := memcache.Gob.Get(c, key, &obj)
if err == memcache.ErrCacheMiss {
ok := obj.Record(timeNow(c), cfg)
err = memcache.Gob.Add(c, &memcache.Item{
Key: key,
Object: obj,
Expiration: cfg.Window,
})
if err == memcache.ErrNotStored {
// Conflict with another instance. Retry.
continue
}
return ok, err
} else if err != nil {
return false, err
}
// Update the existing object.
ok := obj.Record(timeNow(c), cfg)
item.Expiration = cfg.Window
item.Object = obj
err = memcache.Gob.CompareAndSwap(c, item)
if err == memcache.ErrCASConflict {
if ok {
// Only retry if we approved the query.
// If we denied and there was a concurrent write
// to the same object, it could have only denied
// the query as well.
// Our save won't change anything.
continue
}
} else if err != nil {
return false, err
}
return ok, nil
}
return false, ErrThrottleTooManyRetries
}