forked from akash-network/provider
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprovider_attributes.go
453 lines (381 loc) · 10.9 KB
/
provider_attributes.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package bidengine
import (
"context"
"errors"
"regexp"
"sync"
"time"
"github.com/boz/go-lifecycle"
"github.com/akash-network/node/pubsub"
"github.com/akash-network/provider/session"
atypes "github.com/akash-network/akash-api/go/node/audit/v1beta3"
ptypes "github.com/akash-network/akash-api/go/node/provider/v1beta3"
types "github.com/akash-network/akash-api/go/node/types/v1beta3"
)
const (
attrFetchRetryPeriod = 5 * time.Second
attrReqTimeout = 5 * time.Second
)
var (
errShuttingDown = errors.New("provider attribute signature service is shutting down")
invalidProviderPattern = regexp.MustCompile("^.*invalid provider: address not found.*$")
)
type attrRequest struct {
successCh chan<- types.Attributes
errCh chan<- error
}
type auditedAttrRequest struct {
auditor string
successCh chan<- []atypes.Provider
errCh chan<- error
}
type providerAttrEntry struct {
providerAttr []atypes.Provider
at time.Time
}
type auditedAttrResult struct {
auditor string
providerAttr []atypes.Provider
err error
}
type ProviderAttrSignatureService interface {
GetAuditorAttributeSignatures(auditor string) ([]atypes.Provider, error)
GetAttributes() (types.Attributes, error)
}
type providerAttrSignatureService struct {
providerAddr string
lc lifecycle.Lifecycle
requests chan auditedAttrRequest
reqAttr chan attrRequest
currAttr chan types.Attributes
fetchAttr chan struct{}
pushAttr chan struct{}
fetchInProgress chan struct{}
newAttr chan types.Attributes
errFetchAttr chan error
session session.Session
fetchCh chan auditedAttrResult
data map[string]providerAttrEntry
inProgress map[string]struct{}
pending map[string][]auditedAttrRequest
wg sync.WaitGroup
sub pubsub.Subscriber
ttl time.Duration
attr types.Attributes
}
func newProviderAttrSignatureService(s session.Session, bus pubsub.Bus) (*providerAttrSignatureService, error) {
return newProviderAttrSignatureServiceInternal(s, bus, 18*time.Hour)
}
func newProviderAttrSignatureServiceInternal(s session.Session, bus pubsub.Bus, ttl time.Duration) (*providerAttrSignatureService, error) {
subscriber, err := bus.Subscribe()
if err != nil {
return nil, err
}
retval := &providerAttrSignatureService{
providerAddr: s.Provider().Owner,
lc: lifecycle.New(),
session: s,
requests: make(chan auditedAttrRequest),
fetchCh: make(chan auditedAttrResult),
data: make(map[string]providerAttrEntry),
pending: make(map[string][]auditedAttrRequest),
inProgress: make(map[string]struct{}),
reqAttr: make(chan attrRequest, 1),
currAttr: make(chan types.Attributes, 1),
fetchAttr: make(chan struct{}, 1),
pushAttr: make(chan struct{}, 1),
fetchInProgress: make(chan struct{}, 1),
newAttr: make(chan types.Attributes),
errFetchAttr: make(chan error, 1),
sub: subscriber,
ttl: ttl,
}
go retval.run()
return retval, nil
}
func (pass *providerAttrSignatureService) run() {
defer pass.sub.Close()
defer pass.lc.ShutdownCompleted()
ctx, cancel := context.WithCancel(context.Background())
pass.fetchAttributes()
loop:
for {
select {
case ev := <-pass.sub.Events():
pass.handleEvent(ev)
case <-pass.lc.ShutdownRequest():
pass.lc.ShutdownInitiated(nil)
break loop
case request := <-pass.requests:
start := pass.addRequest(request)
if start {
pass.maybeStart(ctx, request.auditor)
}
case result := <-pass.fetchCh:
if result.err != nil {
pass.failAllPending(result.auditor, result.err)
} else {
pass.completeAllPending(result.auditor, result.providerAttr)
}
delete(pass.pending, result.auditor)
case <-pass.fetchAttr:
pass.tryFetchAttributes(ctx)
case req := <-pass.reqAttr:
pass.processAttrReq(ctx, req)
case <-pass.pushAttr:
select {
case pass.currAttr <- pass.attr:
default:
}
case attr := <-pass.newAttr:
// todo fetch current cluster storage inventory
pass.attr = attr
pass.pushCurrAttributes()
case <-pass.errFetchAttr:
// if attributes fetch fails give it retry within reasonable timeout
time.AfterFunc(attrFetchRetryPeriod, func() {
pass.fetchAttributes()
})
}
}
cancel()
pass.wg.Wait()
}
func (pass *providerAttrSignatureService) purgeAuditor(auditor string) {
delete(pass.data, auditor)
}
func (pass *providerAttrSignatureService) fetchAttributes() {
select {
case pass.fetchAttr <- struct{}{}:
default:
return
}
}
func (pass *providerAttrSignatureService) pushCurrAttributes() {
select {
case pass.pushAttr <- struct{}{}:
default:
}
}
func (pass *providerAttrSignatureService) handleEvent(ev pubsub.Event) {
switch ev := ev.(type) {
case atypes.EventTrustedAuditorCreated:
if ev.Owner.String() == pass.providerAddr {
pass.purgeAuditor(ev.Auditor.String())
}
case atypes.EventTrustedAuditorDeleted:
if ev.Owner.String() == pass.providerAddr {
pass.purgeAuditor(ev.Auditor.String())
}
case ptypes.EventProviderUpdated:
if ev.Owner.String() == pass.providerAddr {
pass.fetchAttributes()
}
default:
// Ignore the event, we don't need it
}
}
func (pass *providerAttrSignatureService) failAllPending(auditor string, err error) {
pendingForAuditor := pass.pending[auditor]
for _, req := range pendingForAuditor {
req.errCh <- err
}
delete(pass.pending, auditor)
}
func (pass *providerAttrSignatureService) completeAllPending(auditor string, result []atypes.Provider) {
pendingForAuditor := pass.pending[auditor]
delete(pass.pending, auditor)
// Store in cache for later usage
pass.data[auditor] = providerAttrEntry{
providerAttr: result,
at: time.Now(),
}
// Fill all requests
for _, req := range pendingForAuditor {
req.successCh <- result
}
pass.trimCache()
}
func providerAttrSize(entries []atypes.Provider) int {
size := 0
for _, x := range entries {
size += len(x.Attributes)
}
return size
}
func (pass *providerAttrSignatureService) trimCache() {
const maxEntries = 50000
toDelete := make([]string, 0, 4)
now := time.Now()
size := 0
for auditor, entry := range pass.data {
elapsed := now.Sub(entry.at)
expired := elapsed > pass.ttl
if expired {
toDelete = append(toDelete, auditor)
} else {
size += providerAttrSize(entry.providerAttr)
}
}
// Remove expired entries
for _, auditor := range toDelete {
delete(pass.data, auditor)
}
toDelete = nil
// Check if size is larger than what is wanted
if size > maxEntries {
pass.session.Log().Info("provider attr. cache size too large, pruning", "size", size)
} else {
return
}
// Remove approx. half of the stored values
const target = maxEntries / 2
size = 0
// Map iteration order in golang is random
for auditor, entry := range pass.data {
size += providerAttrSize(entry.providerAttr)
toDelete = append(toDelete, auditor)
if size >= target {
break
}
}
// Delete entries to get the size back down
for _, auditor := range toDelete {
delete(pass.data, auditor)
}
}
func (pass *providerAttrSignatureService) maybeStart(ctx context.Context, auditor string) {
// Check that request exists
if pendingForAuditor := pass.pending[auditor]; len(pendingForAuditor) == 0 {
return
}
// Check that request is not in flight
_, exists := pass.inProgress[auditor]
if exists {
return
}
pass.wg.Add(1)
go func() {
defer pass.wg.Done()
pass.fetchCh <- pass.fetch(ctx, auditor)
}()
}
func (pass *providerAttrSignatureService) fetch(ctx context.Context, auditor string) auditedAttrResult {
req := &atypes.QueryProviderAuditorRequest{
Owner: pass.providerAddr,
Auditor: auditor,
}
pass.session.Log().Info("fetching provider auditor attributes", "auditor", req.Auditor, "provider", req.Owner)
result, err := pass.session.Client().Query().ProviderAuditorAttributes(ctx, req)
if err != nil {
// Error type is always "errors.fundamental" so use pattern matching here
if invalidProviderPattern.MatchString(err.Error()) {
return auditedAttrResult{auditor: auditor} // No data
}
return auditedAttrResult{auditor: auditor, err: err}
}
value := result.GetProviders()
pass.session.Log().Info("got auditor attributes", "auditor", auditor, "size", providerAttrSize(value))
return auditedAttrResult{
auditor: auditor,
providerAttr: value,
}
}
func (pass *providerAttrSignatureService) addRequest(request auditedAttrRequest) bool {
entry, present := pass.data[request.auditor]
if present { // Cached value is present
elapsed := time.Since(entry.at) // Check if it is too old
if elapsed < pass.ttl {
request.successCh <- entry.providerAttr
pass.session.Log().Debug("reused auditor attributes", "auditor", request.auditor, "elapsed", elapsed)
return false
}
}
pendingList := pass.pending[request.auditor]
pendingList = append(pendingList, request)
pass.pending[request.auditor] = pendingList
return true
}
func (pass *providerAttrSignatureService) GetAuditorAttributeSignatures(auditor string) ([]atypes.Provider, error) {
successCh := make(chan []atypes.Provider, 1)
errCh := make(chan error, 1)
req := auditedAttrRequest{
auditor: auditor,
successCh: successCh,
errCh: errCh,
}
select {
case pass.requests <- req:
case <-pass.lc.ShuttingDown():
return nil, errShuttingDown
}
select {
case <-pass.lc.ShuttingDown():
return nil, errShuttingDown
case err := <-errCh:
return nil, err
case result := <-successCh:
return result, nil
}
}
func (pass *providerAttrSignatureService) GetAttributes() (types.Attributes, error) {
successCh := make(chan types.Attributes, 1)
errCh := make(chan error, 1)
req := attrRequest{
successCh: successCh,
errCh: errCh,
}
select {
case pass.reqAttr <- req:
case <-pass.lc.ShuttingDown():
return nil, errShuttingDown
}
select {
case <-pass.lc.ShuttingDown():
return nil, errShuttingDown
case err := <-errCh:
return nil, err
case result := <-successCh:
return result, nil
}
}
func (pass *providerAttrSignatureService) tryFetchAttributes(ctx context.Context) {
select {
case pass.fetchInProgress <- struct{}{}:
go func() {
var err error
defer func() {
<-pass.fetchInProgress
if err != nil {
pass.errFetchAttr <- err
}
}()
var result *ptypes.QueryProviderResponse
req := &ptypes.QueryProviderRequest{
Owner: pass.providerAddr,
}
result, err = pass.session.Client().Query().Provider(ctx, req)
if err != nil {
pass.session.Log().Error("fetching provider attributes", "provider", req.Owner)
return
}
pass.session.Log().Info("fetched provider attributes", "provider", req.Owner)
pass.newAttr <- result.Provider.Attributes
}()
default:
return
}
}
func (pass *providerAttrSignatureService) processAttrReq(ctx context.Context, req attrRequest) {
go func() {
ctx, cancel := context.WithTimeout(ctx, attrReqTimeout)
defer cancel()
select {
case <-ctx.Done():
req.errCh <- ctx.Err()
case attr := <-pass.currAttr:
req.successCh <- attr
pass.pushCurrAttributes()
}
}()
}