forked from application-research/estuary
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreplication.go
3295 lines (2739 loc) · 86.2 KB
/
replication.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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"container/heap"
"context"
"fmt"
"github.com/google/uuid"
"math/rand"
"sort"
"sync"
"time"
"github.com/application-research/estuary/config"
drpc "github.com/application-research/estuary/drpc"
"github.com/application-research/estuary/node"
"github.com/application-research/estuary/pinner"
util "github.com/application-research/estuary/util"
dagsplit "github.com/application-research/estuary/util/dagsplit"
"github.com/application-research/filclient"
"github.com/filecoin-project/boost/transport/httptransport"
"github.com/filecoin-project/go-address"
cborutil "github.com/filecoin-project/go-cbor-util"
datatransfer "github.com/filecoin-project/go-data-transfer"
"github.com/filecoin-project/go-fil-markets/storagemarket"
"github.com/filecoin-project/go-fil-markets/storagemarket/network"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/specs-actors/v6/actors/builtin/market"
lru "github.com/hashicorp/golang-lru"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-blockservice"
"github.com/ipfs/go-cid"
blockstore "github.com/ipfs/go-ipfs-blockstore"
batched "github.com/ipfs/go-ipfs-provider/batched"
cbor "github.com/ipfs/go-ipld-cbor"
ipld "github.com/ipfs/go-ipld-format"
"github.com/ipfs/go-merkledag"
"github.com/ipfs/go-metrics-interface"
"github.com/ipfs/go-unixfs"
"github.com/labstack/echo/v4"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/pkg/errors"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/xerrors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const defaultContentSizeLimit = 34_000_000_000
// Making default deal duration be three weeks less than the maximum to ensure
// miners who start their deals early dont run into issues
const dealDuration = 1555200 - (2880 * 21)
type ContentManager struct {
DB *gorm.DB
Api api.Gateway
FilClient *filclient.FilClient
Provider *batched.BatchProvidingSystem
Node *node.Node
Host host.Host
tracer trace.Tracer
Blockstore node.EstuaryBlockstore
Tracker *TrackingBlockstore
NotifyBlockstore *node.NotifyBlockstore
ToCheck chan uint
queueMgr *queueManager
retrLk sync.Mutex
retrievalsInProgress map[uint]*util.RetrievalProgress
contentLk sync.RWMutex
contentSizeLimit int64
// Some fields for miner reputation management
minerLk sync.Mutex
sortedMiners []address.Address
rawData []*minerDealStats
lastComputed time.Time
// deal bucketing stuff
bucketLk sync.Mutex
buckets map[uint][]*contentStagingZone
// some behavior flags
FailDealOnTransferFailure bool
dealDisabledLk sync.Mutex
isDealMakingDisabled bool
contentAddingDisabled bool
localContentAddingDisabled bool
Replication int
hostname string
pinJobs map[uint]*pinner.PinningOperation
pinLk sync.Mutex
pinMgr *pinner.PinManager
shuttlesLk sync.Mutex
shuttles map[string]*ShuttleConnection
remoteTransferStatus *lru.ARCCache
inflightCids map[cid.Cid]uint
inflightCidsLk sync.Mutex
VerifiedDeal bool
}
func (cm *ContentManager) isInflight(c cid.Cid) bool {
cm.inflightCidsLk.Lock()
defer cm.inflightCidsLk.Unlock()
v, ok := cm.inflightCids[c]
return ok && v > 0
}
// 90% of the unpadded data size for a 4GB piece
// the 10% gap is to accommodate car file packing overhead, can probably do this better
var individualDealThreshold = (abi.PaddedPieceSize(4<<30).Unpadded() * 9) / 10
var stagingZoneSizeLimit = (abi.PaddedPieceSize(16<<30).Unpadded() * 9) / 10
type contentStagingZone struct {
ZoneOpened time.Time `json:"zoneOpened"`
EarliestContent time.Time `json:"earliestContent"`
CloseTime time.Time `json:"closeTime"`
Contents []Content `json:"contents"`
MinSize int64 `json:"minSize"`
MaxSize int64 `json:"maxSize"`
MaxItems int `json:"maxItems"`
CurSize int64 `json:"curSize"`
User uint `json:"user"`
ContID uint `json:"contentID"`
Location string `json:"location"`
lk sync.Mutex
}
func (cb *contentStagingZone) DeepCopy() *contentStagingZone {
cb.lk.Lock()
defer cb.lk.Unlock()
cb2 := &contentStagingZone{
ZoneOpened: cb.ZoneOpened,
EarliestContent: cb.EarliestContent,
CloseTime: cb.CloseTime,
Contents: make([]Content, len(cb.Contents)),
MinSize: cb.MinSize,
MaxSize: cb.MaxSize,
MaxItems: cb.MaxItems,
CurSize: cb.CurSize,
User: cb.User,
ContID: cb.ContID,
Location: cb.Location,
}
copy(cb2.Contents, cb.Contents)
return cb2
}
func (cm *ContentManager) newContentStagingZone(user uint, loc string) (*contentStagingZone, error) {
content := &Content{
Size: 0,
Name: "aggregate",
Active: false,
Pinning: true,
UserID: user,
Replication: cm.Replication,
Aggregate: true,
Location: loc,
}
if err := cm.DB.Create(content).Error; err != nil {
return nil, err
}
return &contentStagingZone{
ZoneOpened: time.Now(),
CloseTime: time.Now().Add(maxStagingZoneLifetime),
MinSize: int64(stagingZoneSizeLimit - (1 << 30)),
MaxSize: int64(stagingZoneSizeLimit),
MaxItems: maxBucketItems,
User: user,
ContID: content.ID,
Location: content.Location,
}, nil
}
// amount of time a staging zone will remain open before we aggregate it into a piece of content
const maxStagingZoneLifetime = time.Hour * 8
// maximum amount of time a piece of content will go without either being aggregated or having a deal made for it
const maxContentAge = time.Hour * 24 * 7
// staging zones will remain open for at least this long after the last piece of content is added to them (unless they are full)
const stagingZoneKeepalive = time.Minute * 40
const minDealSize = 256 << 20
const maxBucketItems = 10000
func (cb *contentStagingZone) isReady() bool {
if cb.CurSize < minDealSize {
return false
}
// if its above the size requirement, go right ahead
if cb.CurSize > cb.MinSize {
return true
}
if time.Now().After(cb.CloseTime) {
return true
}
if time.Since(cb.EarliestContent) > maxContentAge {
return true
}
if len(cb.Contents) >= cb.MaxItems {
return true
}
return false
}
func (cb *contentStagingZone) hasRoomForContent(c Content) bool {
cb.lk.Lock()
defer cb.lk.Unlock()
if len(cb.Contents) >= cb.MaxItems {
return false
}
return cb.CurSize+c.Size <= cb.MaxSize
}
func (cm *ContentManager) tryAddContent(cb *contentStagingZone, c Content) (bool, error) {
cb.lk.Lock()
defer cb.lk.Unlock()
if cb.CurSize+c.Size > cb.MaxSize {
return false, nil
}
if len(cb.Contents) >= cb.MaxItems {
return false, nil
}
if err := cm.DB.Model(Content{}).
Where("id = ?", c.ID).
UpdateColumn("aggregated_in", cb.ContID).Error; err != nil {
return false, err
}
if len(cb.Contents) == 0 || c.CreatedAt.Before(cb.EarliestContent) {
cb.EarliestContent = c.CreatedAt
}
cb.Contents = append(cb.Contents, c)
cb.CurSize += c.Size
nowPlus := time.Now().Add(stagingZoneKeepalive)
if cb.CloseTime.Before(nowPlus) {
cb.CloseTime = nowPlus
}
return true, nil
}
func (cb *contentStagingZone) hasContent(c Content) bool {
cb.lk.Lock()
defer cb.lk.Unlock()
for _, cont := range cb.Contents {
if cont.ID == c.ID {
return true
}
}
return false
}
func NewContentManager(db *gorm.DB, api api.Gateway, fc *filclient.FilClient, tbs *TrackingBlockstore, nbs *node.NotifyBlockstore, prov *batched.BatchProvidingSystem, pinmgr *pinner.PinManager, nd *node.Node, cfg *config.Estuary) (*ContentManager, error) {
cache, err := lru.NewARC(50000)
if err != nil {
return nil, err
}
var stages []Content
if err := db.Find(&stages, "not active and pinning and aggregate").Error; err != nil {
return nil, err
}
zones := make(map[uint][]*contentStagingZone)
for _, c := range stages {
z := &contentStagingZone{
ZoneOpened: c.CreatedAt,
CloseTime: c.CreatedAt.Add(maxStagingZoneLifetime),
MinSize: int64(stagingZoneSizeLimit - (1 << 30)),
MaxSize: int64(stagingZoneSizeLimit),
MaxItems: maxBucketItems,
User: c.UserID,
ContID: c.ID,
Location: c.Location,
}
minClose := time.Now().Add(stagingZoneKeepalive)
if z.CloseTime.Before(minClose) {
z.CloseTime = minClose
}
var inzone []Content
if err := db.Find(&inzone, "aggregated_in = ?", c.ID).Error; err != nil {
return nil, err
}
z.Contents = inzone
for _, zc := range inzone {
// TODO: do some sanity checking that we havent messed up and added
// too many items to this staging zone
z.CurSize += zc.Size
}
zones[c.UserID] = append(zones[c.UserID], z)
}
cm := &ContentManager{
Provider: prov,
DB: db,
Api: api,
FilClient: fc,
Blockstore: tbs.Under().(node.EstuaryBlockstore),
Host: nd.Host,
Node: nd,
NotifyBlockstore: nbs,
Tracker: tbs,
ToCheck: make(chan uint, 100000),
retrievalsInProgress: make(map[uint]*util.RetrievalProgress),
buckets: zones,
pinJobs: make(map[uint]*pinner.PinningOperation),
pinMgr: pinmgr,
remoteTransferStatus: cache,
shuttles: make(map[string]*ShuttleConnection),
contentSizeLimit: defaultContentSizeLimit,
hostname: cfg.Hostname,
inflightCids: make(map[cid.Cid]uint),
FailDealOnTransferFailure: cfg.DealConfig.FailOnTransferFailure,
isDealMakingDisabled: cfg.DealConfig.Disable,
contentAddingDisabled: cfg.ContentConfig.DisableGlobalAdding,
localContentAddingDisabled: cfg.ContentConfig.DisableLocalAdding,
VerifiedDeal: cfg.DealConfig.Verified,
Replication: cfg.Replication,
tracer: otel.Tracer("replicator"),
}
qm := newQueueManager(func(c uint) {
cm.ToCheck <- c
})
cm.queueMgr = qm
return cm, nil
}
func (cm *ContentManager) ContentWatcher() {
if err := cm.startup(); err != nil {
log.Errorf("failed to recheck existing content: %s", err)
}
timer := time.NewTimer(time.Minute * 5)
for {
select {
case c := <-cm.ToCheck:
var content Content
if err := cm.DB.First(&content, "id = ?", c).Error; err != nil {
log.Errorf("finding content %d in database: %s", c, err)
continue
}
log.Infof("checking content: %d", content.ID)
err := cm.ensureStorage(context.TODO(), content, func(dur time.Duration) {
cm.queueMgr.add(content.ID, dur)
})
if err != nil {
log.Errorf("failed to ensure replication of content %d: %s", content.ID, err)
cm.queueMgr.add(content.ID, time.Minute*5)
}
case <-timer.C:
log.Infow("content check queue", "length", len(cm.queueMgr.queue.elems), "nextEvent", cm.queueMgr.nextEvent)
/*
if err := cm.queueAllContent(); err != nil {
log.Errorf("rechecking content: %s", err)
continue
}
*/
buckets := cm.popReadyStagingZone()
for _, b := range buckets {
if err := cm.aggregateContent(context.TODO(), b); err != nil {
log.Errorf("content aggregation failed (bucket %d): %s", b.ContID, err)
continue
}
}
timer.Reset(time.Minute * 5)
}
}
}
type queueEntry struct {
content uint
checkTime time.Time
}
type entryQueue struct {
elems []*queueEntry
}
func (eq *entryQueue) Len() int {
return len(eq.elems)
}
func (eq *entryQueue) Less(i, j int) bool {
return eq.elems[i].checkTime.Before(eq.elems[j].checkTime)
}
func (eq *entryQueue) Swap(i, j int) {
eq.elems[i], eq.elems[j] = eq.elems[j], eq.elems[i]
}
func (eq *entryQueue) Push(e interface{}) {
eq.elems = append(eq.elems, e.(*queueEntry))
}
func (eq *entryQueue) Pop() interface{} {
out := eq.elems[len(eq.elems)-1]
eq.elems = eq.elems[:len(eq.elems)-1]
return out
}
func (eq *entryQueue) PopEntry() *queueEntry {
return heap.Pop(eq).(*queueEntry)
}
type queueManager struct {
queue *entryQueue
cb func(uint)
qlk sync.Mutex
nextEvent time.Time
evtTimer *time.Timer
qsizeMetr metrics.Gauge
qnextMetr metrics.Gauge
}
func newQueueManager(cb func(c uint)) *queueManager {
metCtx := metrics.CtxScope(context.Background(), "content_manager")
qsizeMetr := metrics.NewCtx(metCtx, "queue_size", "number of items in the replicator queue").Gauge()
qnextMetr := metrics.NewCtx(metCtx, "queue_next", "next event time for queue").Gauge()
qm := &queueManager{
queue: new(entryQueue),
cb: cb,
qsizeMetr: qsizeMetr,
qnextMetr: qnextMetr,
}
heap.Init(qm.queue)
return qm
}
func (qm *queueManager) add(content uint, wait time.Duration) {
qm.qlk.Lock()
defer qm.qlk.Unlock()
at := time.Now().Add(wait)
heap.Push(qm.queue, &queueEntry{
content: content,
checkTime: at,
})
qm.qsizeMetr.Add(1)
if qm.nextEvent.IsZero() || at.Before(qm.nextEvent) {
qm.nextEvent = at
qm.qnextMetr.Set(float64(at.Unix()))
if qm.evtTimer != nil {
qm.evtTimer.Reset(wait)
} else {
qm.evtTimer = time.AfterFunc(wait, func() {
qm.processQueue()
})
}
}
}
func (qm *queueManager) processQueue() {
qm.qlk.Lock()
defer qm.qlk.Unlock()
for qm.queue.Len() > 0 {
qe := qm.queue.PopEntry()
if time.Now().After(qe.checkTime) {
qm.qsizeMetr.Add(-1)
go qm.cb(qe.content)
} else {
heap.Push(qm.queue, qe)
qm.nextEvent = qe.checkTime
qm.qnextMetr.Set(float64(qe.checkTime.Unix()))
qm.evtTimer.Reset(qe.checkTime.Sub(time.Now()))
return
}
}
qm.nextEvent = time.Time{}
}
func (cm *ContentManager) currentLocationForContent(c uint) (string, error) {
var cont Content
if err := cm.DB.First(&cont, "id = ?", c).Error; err != nil {
return "", err
}
return cont.Location, nil
}
func (cm *ContentManager) stagedContentByLocation(ctx context.Context, b *contentStagingZone) (map[string][]Content, error) {
out := make(map[string][]Content)
for _, c := range b.Contents {
loc, err := cm.currentLocationForContent(c.ID)
if err != nil {
return nil, err
}
out[loc] = append(out[loc], c)
}
return out, nil
}
func (cm *ContentManager) consolidateStagedContent(ctx context.Context, b *contentStagingZone) error {
var primary string
var curMax int64
dataByLoc := make(map[string]int64)
contentByLoc := make(map[string][]Content)
for _, c := range b.Contents {
loc, err := cm.currentLocationForContent(c.ID)
if err != nil {
return err
}
contentByLoc[loc] = append(contentByLoc[loc], c)
ntot := dataByLoc[loc] + c.Size
dataByLoc[loc] = ntot
// temp: dont ever migrate content back to primary instance for aggregation, always prefer elsewhere
if ntot > curMax && loc != "local" {
curMax = ntot
primary = loc
}
}
// okay, move everything to 'primary'
var toMove []Content
for loc, conts := range contentByLoc {
if loc != primary {
toMove = append(toMove, conts...)
}
}
log.Infow("consolidating content to single location for aggregation", "user", b.User, "primary", primary, "numItems", len(toMove), "primaryWeight", curMax)
if primary == "local" {
return cm.migrateContentsToLocalNode(ctx, toMove)
} else {
return cm.sendConsolidateContentCmd(ctx, primary, toMove)
}
}
func (cm *ContentManager) aggregateContent(ctx context.Context, b *contentStagingZone) error {
ctx, span := cm.tracer.Start(ctx, "aggregateContent")
defer span.End()
cbl, err := cm.stagedContentByLocation(ctx, b)
if err != nil {
return err
}
if len(cbl) > 1 {
// Need to migrate content all to the same shuttle
cm.bucketLk.Lock()
// put the staging zone back in the list
cm.buckets[b.User] = append(cm.buckets[b.User], b)
cm.bucketLk.Unlock()
go func() {
if err := cm.consolidateStagedContent(ctx, b); err != nil {
log.Errorf("failed to consolidate staged content: %s", err)
}
}()
return nil
}
var loc string
for k := range cbl {
loc = k
}
dir, err := cm.createAggregate(ctx, b.Contents)
if err != nil {
return xerrors.Errorf("failed to create aggregate: %w", err)
}
ncid := dir.Cid()
size, err := dir.Size()
if err != nil {
return err
}
if size == 0 {
log.Warnf("content %d aggregate dir apparent size is zero", b.ContID)
}
if err := cm.DB.Model(Content{}).Where("id = ?", b.ContID).UpdateColumns(map[string]interface{}{
"cid": util.DbCID{ncid},
"size": size,
}).Error; err != nil {
return err
}
var content Content
if err := cm.DB.First(&content, "id = ?", b.ContID).Error; err != nil {
return err
}
if loc == "local" {
obj := &Object{
Cid: util.DbCID{ncid},
Size: int(size),
}
if err := cm.DB.Create(obj).Error; err != nil {
return err
}
if err := cm.DB.Create(&ObjRef{
Content: b.ContID,
Object: obj.ID,
}).Error; err != nil {
return err
}
if err := cm.Blockstore.Put(ctx, dir); err != nil {
return err
}
if err := cm.DB.Model(Content{}).Where("id = ?", b.ContID).UpdateColumns(map[string]interface{}{
"active": true,
"pinning": false,
}).Error; err != nil {
return err
}
go func() {
cm.ToCheck <- b.ContID
}()
return nil
} else {
var ids []uint
for _, c := range b.Contents {
ids = append(ids, c.ID)
}
return cm.sendAggregateCmd(ctx, loc, content, ids, dir.RawData())
}
}
func (cm *ContentManager) createAggregate(ctx context.Context, conts []Content) (*merkledag.ProtoNode, error) {
sort.Slice(conts, func(i, j int) bool {
return conts[i].ID < conts[j].ID
})
log.Info("aggregating contents in staging zone into new content")
dir := unixfs.EmptyDirNode()
for _, c := range conts {
dir.AddRawLink(fmt.Sprintf("%d-%s", c.ID, c.Name), &ipld.Link{
Size: uint64(c.Size),
Cid: c.Cid.CID,
})
}
return dir, nil
}
func (cm *ContentManager) startup() error {
return cm.queueAllContent()
}
func (cm *ContentManager) queueAllContent() error {
var allcontent []Content
if err := cm.DB.Find(&allcontent, "active AND NOT aggregated_in > 0").Error; err != nil {
return xerrors.Errorf("finding all content in database: %w", err)
}
log.Infof("queueing all content for checking: %d", len(allcontent))
go func() {
for _, c := range allcontent {
log.Infof("queueing content: %d", c.ID)
cm.ToCheck <- c.ID
}
}()
/* TODO: this should be more correct, just testing the above out though to ensure the things from here are first in queue
for _, c := range allcontent {
cm.queueMgr.add(c.ID, 0)
}
*/
return nil
}
type estimateResponse struct {
Total *abi.TokenAmount
Asks []*minerStorageAsk
}
func (cm *ContentManager) estimatePrice(ctx context.Context, repl int, size abi.PaddedPieceSize, duration abi.ChainEpoch, verified bool) (*estimateResponse, error) {
ctx, span := cm.tracer.Start(ctx, "estimatePrice", trace.WithAttributes(
attribute.Int("replication", repl),
))
defer span.End()
miners, err := cm.pickMiners(ctx, Content{}, repl, size, nil)
if err != nil {
return nil, err
}
if len(miners) == 0 {
return nil, fmt.Errorf("failed to find any miners for estimating deal price")
}
var asks []*minerStorageAsk
total := abi.NewTokenAmount(0)
for _, m := range miners {
ask, err := cm.getAsk(ctx, m, time.Minute*30)
if err != nil {
return nil, err
}
asks = append(asks, ask)
var price *abi.TokenAmount
if verified {
p, err := ask.GetVerifiedPrice()
if err != nil {
return nil, err
}
price = p
} else {
p, err := ask.GetPrice()
if err != nil {
return nil, err
}
price = p
}
dealSize := size
if dealSize < ask.MinPieceSize {
dealSize = ask.MinPieceSize
}
cost, err := filclient.ComputePrice(*price, dealSize, duration)
if err != nil {
return nil, err
}
total = types.BigAdd(total, *cost)
}
return &estimateResponse{
Total: &total,
Asks: asks,
}, nil
}
type minerStorageAsk struct {
gorm.Model `json:"-"`
Miner string `gorm:"unique" json:"miner"`
Price string `json:"price"`
VerifiedPrice string `json:"verifiedPrice"`
MinPieceSize abi.PaddedPieceSize `json:"minPieceSize"`
MaxPieceSize abi.PaddedPieceSize `json:"maxPieceSize"`
}
func (msa *minerStorageAsk) GetPrice() (*types.BigInt, error) {
v, err := types.BigFromString(msa.Price)
if err != nil {
return nil, err
}
return &v, nil
}
func (msa *minerStorageAsk) GetVerifiedPrice() (*types.BigInt, error) {
v, err := types.BigFromString(msa.VerifiedPrice)
if err != nil {
return nil, err
}
return &v, nil
}
func (cm *ContentManager) pickMinerDist(n int) (int, int) {
if n < 3 {
return n, 0
}
if n < 7 {
return 2, n - 2
}
return n - (n / 2), n / 2
}
const topMinerSel = 15
func (cm *ContentManager) pickMiners(ctx context.Context, cont Content, n int, size abi.PaddedPieceSize, exclude map[address.Address]bool) ([]address.Address, error) {
ctx, span := cm.tracer.Start(ctx, "pickMiners", trace.WithAttributes(
attribute.Int("count", n),
))
defer span.End()
if exclude == nil {
exclude = make(map[address.Address]bool)
}
// some portion of the miners will be 'first N of our best miners' and the rest will be randomly chosen from our list
// over time, our miner list will be all fairly high quality so this should just serve to shake things up a bit and
// give miners more of a chance to prove themselves
_, nrand := cm.pickMinerDist(n)
randminers, err := cm.randomMinerList()
if err != nil {
return nil, err
}
var out []address.Address
for _, m := range randminers {
if len(out) >= nrand {
break
}
if exclude[m] {
continue
}
exclude[m] = true
ask, err := cm.getAsk(ctx, m, time.Minute*30)
if err != nil {
log.Errorf("getting ask from %s failed: %s", m, err)
continue
}
if cm.sizeIsCloseEnough(size, ask.MinPieceSize) {
out = append(out, m)
}
}
sortedminers, _, err := cm.sortedMinerList()
if err != nil {
return nil, err
}
if len(sortedminers) > topMinerSel {
sortedminers = sortedminers[:topMinerSel]
}
rand.Shuffle(len(sortedminers), func(i, j int) {
sortedminers[i], sortedminers[j] = sortedminers[j], sortedminers[i]
})
for _, m := range sortedminers {
if len(out) >= n {
break
}
if exclude[m] {
continue
}
ask, err := cm.getAsk(ctx, m, time.Minute*30)
if err != nil {
log.Errorf("getting ask from %s failed: %s", m, err)
continue
}
if cm.sizeIsCloseEnough(size, ask.MinPieceSize) {
out = append(out, m)
}
}
return out, nil
}
func (cm *ContentManager) randomMinerList() ([]address.Address, error) {
var dbminers []storageMiner
if err := cm.DB.Find(&dbminers, "not suspended").Error; err != nil {
return nil, err
}
out := make([]address.Address, 0, len(dbminers))
for _, dbm := range dbminers {
out = append(out, dbm.Address.Addr)
}
rand.Shuffle(len(dbminers), func(i, j int) {
out[i], out[j] = out[j], out[i]
})
return out, nil
}
func (cm *ContentManager) getAsk(ctx context.Context, m address.Address, maxCacheAge time.Duration) (*minerStorageAsk, error) {
ctx, span := cm.tracer.Start(ctx, "getAsk", trace.WithAttributes(
attribute.Stringer("miner", m),
))
defer span.End()
var asks []minerStorageAsk
if err := cm.DB.Find(&asks, "miner = ?", m.String()).Error; err != nil {
return nil, err
}
var msa minerStorageAsk
if len(asks) > 0 {
msa = asks[0]
}
if time.Since(msa.UpdatedAt) < maxCacheAge {
return &msa, nil
}
netask, err := cm.FilClient.GetAsk(ctx, m)
if err != nil {
var clientErr *filclient.Error
if !(xerrors.As(err, &clientErr) && clientErr.Code == filclient.ErrLotusError) {
cm.recordDealFailure(&DealFailureError{
Miner: m,
Phase: "query-ask",
Message: err.Error(),
})
}
span.RecordError(err)
return nil, err
}
if err := cm.updateMinerVersion(ctx, m); err != nil {
log.Warnf("failed to update miner version: %s", err)
}
nmsa := toDBAsk(netask)
nmsa.UpdatedAt = time.Now()
if err := cm.DB.Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "miner"},
},
DoUpdates: clause.AssignmentColumns([]string{"price", "verified_price", "min_piece_size", "updated_at"}),
}).Create(nmsa).Error; err != nil {
span.RecordError(err)
return nil, err
}