forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
quota_usage.go
292 lines (262 loc) · 8.27 KB
/
quota_usage.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
// Copyright 2017 Keybase Inc. All rights reserved.
// Use of this source code is governed by a BSD
// license that can be found in the LICENSE file.
package libkbfs
import (
"fmt"
"sync"
"time"
"github.com/keybase/client/go/kbfs/kbfsblock"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/pkg/errors"
"golang.org/x/net/context"
)
const (
// quotaServerTimeoutWhenCached defines how long we wait for the
// quota usage to return from the server, when we've already read
// it from the disk cache.
quotaServerTimeoutWhenCached = 500 * time.Millisecond
)
// ECQUCtxTagKey is the type for unique ECQU background operation IDs.
type ECQUCtxTagKey struct{}
// ECQUID is used in EventuallyConsistentQuotaUsage for only background RPCs.
// More specifically, when we need to spawn a background goroutine for
// GetUserQuotaInfo, a new context with this tag is created and used. This is
// also used as a prefix for the logger module name in
// EventuallyConsistentQuotaUsage.
const ECQUID = "ECQU"
type cachedQuotaUsage struct {
timestamp time.Time
usageBytes int64
archiveBytes int64
limitBytes int64
gitUsageBytes int64
gitArchiveBytes int64
gitLimitBytes int64
}
// EventuallyConsistentQuotaUsage keeps tracks of quota usage, in a way user of
// which can choose to accept stale data to reduce calls into block servers.
type EventuallyConsistentQuotaUsage struct {
config Config
log logger.Logger
tid keybase1.TeamID
fetcher *fetchDecider
mu sync.RWMutex
cached cachedQuotaUsage
bgFetch bool
}
// QuotaUsageLogModule makes a log module for a quota usage log.
func QuotaUsageLogModule(suffix string) string {
return fmt.Sprintf("%s - %s", ECQUID, suffix)
}
// NewEventuallyConsistentQuotaUsage creates a new
// EventuallyConsistentQuotaUsage object.
func NewEventuallyConsistentQuotaUsage(
config Config, log logger.Logger,
vlog *libkb.VDebugLog) *EventuallyConsistentQuotaUsage {
q := &EventuallyConsistentQuotaUsage{
config: config,
log: log,
}
q.fetcher = newFetchDecider(
q.log, vlog, q.getAndCache, ECQUCtxTagKey{}, ECQUID, q.config)
return q
}
// NewEventuallyConsistentTeamQuotaUsage creates a new
// EventuallyConsistentQuotaUsage object.
func NewEventuallyConsistentTeamQuotaUsage(
config Config, tid keybase1.TeamID,
log logger.Logger, vlog *libkb.VDebugLog) *EventuallyConsistentQuotaUsage {
q := NewEventuallyConsistentQuotaUsage(config, log, vlog)
q.tid = tid
return q
}
func (q *EventuallyConsistentQuotaUsage) getCached() cachedQuotaUsage {
q.mu.RLock()
defer q.mu.RUnlock()
return q.cached
}
func (q *EventuallyConsistentQuotaUsage) getID(
ctx context.Context) (keybase1.UserOrTeamID, error) {
if q.tid.IsNil() {
session, err := q.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return keybase1.UserOrTeamID(""), err
}
return session.UID.AsUserOrTeam(), nil
}
return q.tid.AsUserOrTeam(), nil
}
func (q *EventuallyConsistentQuotaUsage) cache(
ctx context.Context, quotaInfo *kbfsblock.QuotaInfo, doCacheToDisk bool) {
q.mu.Lock()
defer q.mu.Unlock()
q.cached.limitBytes = quotaInfo.Limit
q.cached.gitLimitBytes = quotaInfo.GitLimit
if quotaInfo.Total != nil {
q.cached.usageBytes = quotaInfo.Total.Bytes[kbfsblock.UsageWrite]
q.cached.archiveBytes = quotaInfo.Total.Bytes[kbfsblock.UsageArchive]
q.cached.gitUsageBytes = quotaInfo.Total.Bytes[kbfsblock.UsageGitWrite]
q.cached.gitArchiveBytes =
quotaInfo.Total.Bytes[kbfsblock.UsageGitArchive]
} else {
q.cached.usageBytes = 0
}
q.cached.timestamp = q.config.Clock().Now()
dqc := q.config.DiskQuotaCache()
if !doCacheToDisk || dqc == nil {
return
}
id, err := q.getID(ctx)
if err != nil {
q.log.CDebugf(ctx, "Can't get ID: %+v", err)
return
}
err = dqc.Put(ctx, id, *quotaInfo)
if err != nil {
q.log.CDebugf(ctx, "Can't cache quota for %s: %+v", id, err)
}
}
func (q *EventuallyConsistentQuotaUsage) fetch(ctx context.Context) (
quotaInfo *kbfsblock.QuotaInfo, err error) {
bserver := q.config.BlockServer()
for i := 0; bserver == nil; i++ {
// This is possible if a login event comes in during
// initialization.
if i == 0 {
q.log.CDebugf(ctx, "Waiting for bserver")
}
time.Sleep(100 * time.Millisecond)
bserver = q.config.BlockServer()
}
if q.tid.IsNil() {
return bserver.GetUserQuotaInfo(ctx)
}
return bserver.GetTeamQuotaInfo(ctx, q.tid)
}
func (q *EventuallyConsistentQuotaUsage) doBackgroundFetch() {
doFetch := func() bool {
q.mu.Lock()
defer q.mu.Unlock()
if q.bgFetch {
return false
}
q.bgFetch = true
return true
}()
if !doFetch {
return
}
defer func() {
q.mu.Lock()
defer q.mu.Unlock()
q.bgFetch = false
}()
ctx := CtxWithRandomIDReplayable(
context.Background(), ECQUCtxTagKey{}, ECQUID, q.log)
q.log.CDebugf(ctx, "Running background quota fetch, without a timeout")
quotaInfo, err := q.fetch(ctx)
if err != nil {
q.log.CDebugf(ctx, "Unable to fetch quota in background: %+v", err)
return
}
q.cache(ctx, quotaInfo, true)
}
func (q *EventuallyConsistentQuotaUsage) getAndCache(
ctx context.Context) (err error) {
defer func() {
q.log.CDebugf(ctx, "getAndCache: error=%v", err)
}()
// Try pulling the quota from the disk cache. If it exists, still
// try the servers, but give it a short timeout.
var quotaInfoFromCache *kbfsblock.QuotaInfo
id, err := q.getID(ctx)
if err != nil {
return err
}
getCtx := ctx
dqc := q.config.DiskQuotaCache()
if dqc != nil {
qi, err := dqc.Get(ctx, id)
if err == nil {
q.log.CDebugf(ctx, "Read quota for %s from disk cache", id)
quotaInfoFromCache = &qi
var cancel context.CancelFunc
getCtx, cancel = context.WithTimeout(
ctx, quotaServerTimeoutWhenCached)
defer cancel()
}
}
quotaInfo, err := q.fetch(getCtx)
doCacheToDisk := dqc != nil
switch err {
case nil:
case context.DeadlineExceeded:
go q.doBackgroundFetch()
if quotaInfoFromCache != nil {
q.log.CDebugf(ctx, "Can't contact server; using cached quota")
quotaInfo = quotaInfoFromCache
doCacheToDisk = false
} else {
return err
}
default:
return err
}
q.cache(ctx, quotaInfo, doCacheToDisk)
return nil
}
// Get returns KBFS bytes used and limit for user, for the current
// default block type. To help avoid having too frequent calls into
// bserver, caller can provide a positive tolerance, to accept stale
// LimitBytes and UsageBytes data. If tolerance is 0 or negative, this
// always makes a blocking RPC to bserver and return latest quota
// usage.
//
// 1) If the age of cached data is more than blockTolerance, a blocking RPC is
// issued and the function only returns after RPC finishes, with the newest
// data from RPC. The RPC causes cached data to be refreshed as well.
// 2) Otherwise, if the age of cached data is more than bgTolerance,
// a background RPC is spawned to refresh cached data, and the stale
// data is returned immediately.
// 3) Otherwise, the cached stale data is returned immediately.
func (q *EventuallyConsistentQuotaUsage) Get(
ctx context.Context, bgTolerance, blockTolerance time.Duration) (
timestamp time.Time, usageBytes, archiveBytes, limitBytes int64,
err error) {
c := q.getCached()
err = q.fetcher.Do(ctx, bgTolerance, blockTolerance, c.timestamp)
if err != nil {
return time.Time{}, -1, -1, -1, err
}
c = q.getCached()
switch q.config.DefaultBlockType() {
case keybase1.BlockType_DATA:
return c.timestamp, c.usageBytes, c.archiveBytes, c.limitBytes, nil
case keybase1.BlockType_GIT:
return c.timestamp, c.gitUsageBytes, c.gitArchiveBytes,
c.gitLimitBytes, nil
default:
return time.Time{}, -1, -1, -1, errors.Errorf(
"Unknown default block type: %d", q.config.DefaultBlockType())
}
}
// GetAllTypes is the same as Get, except it returns usage and limits
// for all block types.
func (q *EventuallyConsistentQuotaUsage) GetAllTypes(
ctx context.Context, bgTolerance, blockTolerance time.Duration) (
timestamp time.Time,
usageBytes, archiveBytes, limitBytes,
gitUsageBytes, gitArchiveBytes, gitLimitBytes int64, err error) {
c := q.getCached()
err = q.fetcher.Do(ctx, bgTolerance, blockTolerance, c.timestamp)
if err != nil {
return time.Time{}, -1, -1, -1, -1, -1, -1, err
}
c = q.getCached()
return c.timestamp,
c.usageBytes, c.archiveBytes, c.limitBytes,
c.gitUsageBytes, c.gitArchiveBytes, c.gitLimitBytes, nil
}