This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
/
bg_identifier.go
349 lines (302 loc) · 8.6 KB
/
bg_identifier.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
343
344
345
346
347
348
349
package engine
import (
"container/heap"
"errors"
"fmt"
"sync"
"time"
"github.com/keybase/client/go/libkb"
keybase1 "github.com/keybase/client/go/protocol/keybase1"
)
type bgiUser struct {
uid keybase1.UID
nextRun time.Time
lastError error // the last error we encountered
// The index is needed by update and is maintained by the heap.Interface methods.
index int // The index of the item in the heap.
}
// A PriorityQueue implements heap.Interface and holds bgiUsers
type priorityQueue []*bgiUser
var _ heap.Interface = (*priorityQueue)(nil)
func (pq priorityQueue) Len() int { return len(pq) }
func (pq priorityQueue) Less(i, j int) bool {
// The goal is for Pop() to give us the event
// that needs to happen first. Thus, use `Before`
// (and not `After`) here.
return pq[i].nextRun.Before(pq[j].nextRun)
}
func (pq priorityQueue) Swap(i, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].index = i
pq[j].index = j
}
func (pq *priorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*bgiUser)
item.index = n
*pq = append(*pq, item)
}
func (pq *priorityQueue) Pop() interface{} {
old := *pq
n := len(old)
item := old[n-1]
item.index = -1 // for safety
*pq = old[0 : n-1]
return item
}
var errDeleted = errors.New("job deleted")
var errEmpty = errors.New("queue empty")
type IdentifyJob struct {
uid keybase1.UID
err error // this error
lastError error // the error from the last run of the loop
}
func NewIdentifyJob(uid keybase1.UID, err, lastError error) IdentifyJob {
return IdentifyJob{
uid: uid,
err: err,
lastError: lastError,
}
}
func (ij IdentifyJob) ErrorChanged() bool {
return (ij.err == nil) != (ij.lastError == nil)
}
func (ij IdentifyJob) UID() keybase1.UID { return ij.uid }
func (ij IdentifyJob) ThisError() error { return ij.err }
func (ij IdentifyJob) LastError() error { return ij.lastError }
type BackgroundIdentifierTestArgs struct {
identify2TestArgs *Identify2WithUIDTestArgs
}
type BackgroundIdentifier struct {
libkb.Contextified
sync.Mutex
queue priorityQueue
members map[keybase1.UID]bool
addCh chan struct{}
snooperCh chan<- IdentifyJob
untilCh chan struct{}
testArgs *BackgroundIdentifierTestArgs
settings BackgroundIdentifierSettings
}
var _ (Engine2) = (*BackgroundIdentifier)(nil)
type BackgroundIdentifierSettings struct {
Enabled bool // = true
WaitClean time.Duration // = 4 * time.Hour
WaitHardFailure time.Duration // = 90 * time.Minute
WaitSoftFailure time.Duration // = 10 * time.Minute
DelaySlot time.Duration // = 30 * time.Second
}
var BackgroundIdentifierDefaultSettings = BackgroundIdentifierSettings{
Enabled: true,
WaitClean: 4 * time.Hour,
WaitHardFailure: 90 * time.Minute,
WaitSoftFailure: 10 * time.Minute,
DelaySlot: 3 * time.Minute,
}
func NewBackgroundIdentifier(g *libkb.GlobalContext, untilCh chan struct{}) *BackgroundIdentifier {
ret := &BackgroundIdentifier{
Contextified: libkb.NewContextified(g),
members: make(map[keybase1.UID]bool),
addCh: make(chan struct{}),
untilCh: untilCh,
settings: BackgroundIdentifierDefaultSettings,
}
heap.Init(&ret.queue)
return ret
}
// GetPrereqs returns the engine prereqs.
func (b *BackgroundIdentifier) Prereqs() Prereqs {
return Prereqs{}
}
func (b *BackgroundIdentifier) Name() string {
return "BackgroundIdentifier"
}
func (b *BackgroundIdentifier) RequiredUIs() []libkb.UIKind {
return nil
}
func (b *BackgroundIdentifier) SubConsumers() []libkb.UIConsumer {
return []libkb.UIConsumer{
&Identify2WithUID{
arg: &keybase1.Identify2Arg{IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_GUI},
},
}
}
// A snooper channel wants to know what's going on and will be notified accordingly.
func (b *BackgroundIdentifier) SetSnooperChannel(ch chan<- IdentifyJob) {
b.snooperCh = ch
}
func (b *BackgroundIdentifier) Add(u keybase1.UID) bool {
b.Lock()
defer b.Unlock()
present, found := b.members[u]
if present {
return false
}
// It might already have been in the queue, but slated for removal,
// then just added back at the last minute.
if !found {
heap.Push(&b.queue, &bgiUser{uid: u})
}
b.members[u] = true
go func() {
b.addCh <- struct{}{}
}()
return true
}
func (b *BackgroundIdentifier) Remove(u keybase1.UID) {
b.Lock()
defer b.Unlock()
b.members[u] = false
}
func (b *BackgroundIdentifier) waitUntil() time.Time {
b.Lock()
defer b.Unlock()
now := b.G().Clock().Now()
if len(b.queue) == 0 {
return now.Add(time.Hour)
}
lowest := b.queue[0]
return lowest.nextRun
}
func (b *BackgroundIdentifier) Run(m libkb.MetaContext) (err error) {
fn := "BackgroundIdentifier#Run"
defer m.CTrace(fn, func() error { return err })()
// Mark all identifies with background identifier tag / context.
netContext := libkb.WithLogTag(m.Ctx(), "BG")
if !b.settings.Enabled {
m.CDebugf("%s: Bailing out since BackgroundIdentifier isn't enabled", fn)
return nil
}
keepGoing := true
for keepGoing {
waitUntil := b.waitUntil()
if waitUntil.IsZero() {
m.CDebugf("%s: not waiting, got an immediate identifiee", fn)
} else {
m.CDebugf("%s: waiting %s", fn, waitUntil.Sub(b.G().Clock().Now()))
}
select {
case <-b.untilCh:
keepGoing = false
case <-b.addCh:
m.CDebugf("| early wake up due to new addition")
continue
case <-b.G().Clock().AfterTime(waitUntil):
m.CDebugf("| running next after wait")
// Reset the netContext every time through the loop, so we don't
// endlessly accumulate WithValues
m = m.WithCtx(netContext)
b.runNext(m)
}
}
return nil
}
func (b *BackgroundIdentifier) popOne() (user *bgiUser, err error) {
b.Lock()
defer b.Unlock()
if len(b.queue) == 0 {
return nil, errEmpty
}
next := heap.Pop(&b.queue).(*bgiUser)
if !b.members[next.uid] {
delete(b.members, next.uid)
return nil, errDeleted
}
return next, nil
}
func (b *BackgroundIdentifier) popNext() (user *bgiUser, err error) {
for {
user, err := b.popOne()
if user != nil {
return user, nil
}
if err == errDeleted {
continue
}
return nil, err
}
}
func (b *BackgroundIdentifier) requeue(u *bgiUser) {
b.Lock()
defer b.Unlock()
heap.Push(&b.queue, u)
}
func (b *BackgroundIdentifier) errorToRetryDuration(e error) time.Duration {
switch {
case e == nil:
return b.settings.WaitClean
case e == errBackgroundIdentifierBadProofsSoft:
return b.settings.WaitSoftFailure
default:
return b.settings.WaitHardFailure
}
}
var errBackgroundIdentifierBadKeys = errors.New("BG identify error: bad keys")
var errBackgroundIdentifierBadProofsHard = errors.New("BG identify error: bad proofs (hard failure)")
var errBackgroundIdentifierBadProofsSoft = errors.New("BG identify error: bad proofs (soft failure)")
func trackBreaksToError(b *keybase1.IdentifyTrackBreaks) error {
if b == nil {
return nil
}
if len(b.Keys) > 0 {
return errBackgroundIdentifierBadKeys
}
var err error
for _, p := range b.Proofs {
if !p.Lcr.BreaksTracking {
continue
}
if p.Lcr.ProofResult.Status >= keybase1.ProofStatus_BASE_HARD_ERROR {
return errBackgroundIdentifierBadProofsHard
}
err = errBackgroundIdentifierBadProofsSoft
}
return err
}
func (b *BackgroundIdentifier) runNext(m libkb.MetaContext) error {
user, err := b.popNext()
if err != nil {
return nil
}
if user == nil {
panic("should never get an empty user without an error")
}
tmp := b.runOne(m, user.uid)
waitTime := b.errorToRetryDuration(tmp)
user.nextRun = b.G().Clock().Now().Add(waitTime)
lastError := user.lastError
user.lastError = tmp
m.CDebugf("requeuing %s for %s (until %s)", user.uid, waitTime, user.nextRun)
b.requeue(user)
// We should only say we're done with this user after we've requeued him.
// Otherwise there could be races -- the Advance() call of a tester might
// slip in in before the call to b.G().Clock().Now() above.
if b.snooperCh != nil {
b.snooperCh <- IdentifyJob{user.uid, tmp, lastError}
}
if d := b.settings.DelaySlot; d != 0 {
m.CDebugf("BackgroundIdentifier sleeping for %s", d)
b.G().Clock().Sleep(d)
}
return nil
}
func (b *BackgroundIdentifier) runOne(m libkb.MetaContext, u keybase1.UID) (err error) {
defer m.CTrace(fmt.Sprintf("BackgroundIdentifier#runOne(%s)", u), func() error { return err })()
arg := keybase1.Identify2Arg{
Uid: u,
Reason: keybase1.IdentifyReason{
Type: keybase1.IdentifyReasonType_BACKGROUND,
},
AlwaysBlock: true,
IdentifyBehavior: keybase1.TLFIdentifyBehavior_CHAT_GUI,
}
eng := NewIdentify2WithUID(b.G(), &arg)
if b.testArgs != nil {
eng.testArgs = b.testArgs.identify2TestArgs
}
err = RunEngine2(m, eng)
if err == nil {
err = trackBreaksToError(eng.Result().TrackBreaks)
}
return err
}