forked from leotons/estuary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlers.go
5083 lines (4239 loc) · 130 KB
/
handlers.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"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
httpprof "net/http/pprof"
"os"
"path/filepath"
"runtime/pprof"
"sort"
"strconv"
"strings"
"sync"
"time"
drpc "github.com/application-research/estuary/drpc"
esmetrics "github.com/application-research/estuary/metrics"
"github.com/application-research/estuary/util"
"github.com/application-research/estuary/util/gateway"
"github.com/application-research/filclient"
"github.com/filecoin-project/go-address"
datatransfer "github.com/filecoin-project/go-data-transfer"
commcid "github.com/filecoin-project/go-fil-commcid"
"github.com/filecoin-project/go-padreader"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/lib/sigs"
"github.com/filecoin-project/specs-actors/v6/actors/builtin/market"
"github.com/google/uuid"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-blockservice"
"github.com/ipfs/go-cid"
blockstore "github.com/ipfs/go-ipfs-blockstore"
exchange "github.com/ipfs/go-ipfs-exchange-interface"
offline "github.com/ipfs/go-ipfs-exchange-offline"
ipld "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log/v2"
merkledag "github.com/ipfs/go-merkledag"
"github.com/ipfs/go-unixfs"
uio "github.com/ipfs/go-unixfs/io"
car "github.com/ipld/go-car"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
promhttp "github.com/prometheus/client_golang/prometheus/promhttp"
"golang.org/x/net/websocket"
"golang.org/x/sys/unix"
"golang.org/x/xerrors"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
"go.opentelemetry.io/otel/trace"
echoSwagger "github.com/swaggo/echo-swagger"
_ "github.com/application-research/estuary/docs"
)
// @title Estuary API
// @version 0.0.0
// @description This is the API for the Estuary application.
// @termsOfService http://estuary.tech
// @contact.name API Support
// @contact.url https://docs.estuary.tech/feedback
// @license.name Apache 2.0 Apache-2.0 OR MIT
// @license.url https://github.com/application-research/estuary/blob/master/LICENSE.md
// @host api.estuary.tech
// @BasePath /
// @securityDefinitions.Bearer
// @securityDefinitions.Bearer.type apiKey
// @securityDefinitions.Bearer.in header
// @securityDefinitions.Bearer.name Authorization
func (s *Server) ServeAPI(srv string, logging bool, lsteptok string, cachedir string) error {
e := echo.New()
e.Binder = new(binder)
if logging {
e.Use(middleware.Logger())
}
e.Use(s.tracingMiddleware)
e.HTTPErrorHandler = func(err error, ctx echo.Context) {
var herr *util.HttpError
if xerrors.As(err, &herr) {
res := map[string]string{
"error": herr.Message,
}
if herr.Details != "" {
res["details"] = herr.Details
}
ctx.JSON(herr.Code, res)
return
}
var echoErr *echo.HTTPError
if xerrors.As(err, &echoErr) {
ctx.JSON(echoErr.Code, map[string]interface{}{
"error": echoErr.Message,
})
return
}
log.Errorf("handler error: %s", err)
// TODO: returning all errors out to the user smells potentially bad
_ = ctx.JSON(500, map[string]interface{}{
"error": err.Error(),
})
}
e.GET("/debug/pprof/:prof", serveProfile)
e.GET("/debug/cpuprofile", serveCpuProfile)
phandle := promhttp.Handler()
e.GET("/debug/metrics/prometheus", func(e echo.Context) error {
phandle.ServeHTTP(e.Response().Writer, e.Request())
return nil
})
exporter := esmetrics.Exporter()
e.GET("/debug/metrics/opencensus", func(e echo.Context) error {
exporter.ServeHTTP(e.Response().Writer, e.Request())
return nil
})
e.Use(middleware.CORS())
e.POST("/register", s.handleRegisterUser)
e.POST("/login", s.handleLoginUser)
e.GET("/health", s.handleHealth)
e.GET("/test-error", s.handleTestError)
e.GET("/viewer", withUser(s.handleGetViewer), s.AuthRequired(util.PermLevelUpload))
e.GET("/retrieval-candidates/:cid", s.handleGetRetrievalCandidates)
e.GET("/gw/:path", s.handleGateway)
user := e.Group("/user")
user.Use(s.AuthRequired(util.PermLevelUser))
user.GET("/test-error", s.handleTestError)
user.GET("/api-keys", withUser(s.handleUserGetApiKeys))
user.POST("/api-keys", withUser(s.handleUserCreateApiKey))
user.DELETE("/api-keys/:key", withUser(s.handleUserRevokeApiKey))
user.GET("/export", withUser(s.handleUserExportData))
user.PUT("/password", withUser(s.handleUserChangePassword))
user.PUT("/address", withUser(s.handleUserChangeAddress))
user.GET("/stats", withUser(s.handleGetUserStats))
userMiner := user.Group("/miner")
userMiner.POST("/claim", withUser(s.handleUserClaimMiner))
userMiner.GET("/claim/:miner", withUser(s.handleUserGetClaimMinerMsg))
userMiner.POST("/suspend/:miner", withUser(s.handleSuspendMiner))
userMiner.PUT("/unsuspend/:miner", withUser(s.handleUnsuspendMiner))
userMiner.PUT("/set-info/:miner", withUser(s.handleMinersSetInfo))
contmeta := e.Group("/content")
uploads := contmeta.Group("", s.AuthRequired(util.PermLevelUpload))
uploads.POST("/add", withUser(s.handleAdd))
uploads.POST("/add-ipfs", withUser(s.handleAddIpfs))
uploads.POST("/add-car", withUser(s.handleAddCar))
uploads.POST("/create", withUser(s.handleCreateContent))
content := contmeta.Group("", s.AuthRequired(util.PermLevelUser))
content.GET("/by-cid/:cid", s.handleGetContentByCid)
content.GET("/stats", withUser(s.handleStats))
content.GET("/ensure-replication/:datacid", s.handleEnsureReplication)
content.GET("/status/:id", withUser(s.handleContentStatus))
content.GET("/list", withUser(s.handleListContent))
content.GET("/deals", withUser(s.handleListContentWithDeals))
content.GET("/failures/:content", withUser(s.handleGetContentFailures))
content.GET("/bw-usage/:content", withUser(s.handleGetContentBandwidth))
content.GET("/staging-zones", withUser(s.handleGetStagingZoneForUser))
content.GET("/aggregated/:content", withUser(s.handleGetAggregatedForContent))
content.GET("/all-deals", withUser(s.handleGetAllDealsForUser))
// TODO: the commented out routes here are still fairly useful, but maybe
// need to have some sort of 'super user' permission level in order to use
// them? Can easily cause harm using them
deals := e.Group("/deals")
deals.Use(s.AuthRequired(util.PermLevelUser))
deals.GET("/status/:deal", withUser(s.handleGetDealStatus))
deals.GET("/status-by-proposal/:propcid", withUser(s.handleGetDealStatusByPropCid))
deals.GET("/query/:miner", s.handleQueryAsk)
deals.POST("/make/:miner", withUser(s.handleMakeDeal))
//deals.POST("/transfer/start/:miner/:propcid/:datacid", s.handleTransferStart)
deals.GET("/transfer/status/:id", s.handleTransferStatusByID)
deals.POST("/transfer/status", s.handleTransferStatus)
deals.GET("/transfer/in-progress", s.handleTransferInProgress)
deals.GET("/status/:miner/:propcid", s.handleDealStatus)
deals.POST("/estimate", s.handleEstimateDealCost)
deals.GET("/proposal/:propcid", s.handleGetProposal)
deals.GET("/info/:dealid", s.handleGetDealInfo)
deals.GET("/failures", s.handleStorageFailures)
cols := e.Group("/collections")
cols.Use(s.AuthRequired(util.PermLevelUser))
cols.GET("/list", withUser(s.handleListCollections))
cols.DELETE("/:coluuid", withUser(s.handleDeleteCollection))
cols.POST("/create", withUser(s.handleCreateCollection))
cols.POST("/add-content", withUser(s.handleAddContentsToCollection))
cols.GET("/content/:coluuid", withUser(s.handleGetCollectionContents))
cols.POST("/:coluuid/commit", withUser(s.handleCommitCollection))
colfs := cols.Group("/fs")
colfs.GET("/list", withUser(s.handleColfsListDir))
colfs.POST("/add", withUser(s.handleColfsAdd))
pinning := e.Group("/pinning")
pinning.Use(openApiMiddleware)
pinning.Use(s.AuthRequired(util.PermLevelUser))
pinning.GET("/pins", withUser(s.handleListPins))
pinning.POST("/pins", withUser(s.handleAddPin))
pinning.GET("/pins/:requestid", withUser(s.handleGetPin))
pinning.POST("/pins/:requestid", withUser(s.handleReplacePin))
pinning.DELETE("/pins/:requestid", withUser(s.handleDeletePin))
// explicitly public, for now
public := e.Group("/public")
public.GET("/stats", s.handlePublicStats)
public.GET("/by-cid/:cid", s.handleGetContentByCid)
public.GET("/deals/failures", s.handleStorageFailures)
public.GET("/info", s.handleGetPublicNodeInfo)
public.GET("/miners", s.handlePublicGetMinerStats)
metrics := public.Group("/metrics")
metrics.GET("/deals-on-chain", s.handleMetricsDealOnChain)
netw := public.Group("/net")
netw.GET("/peers", s.handleNetPeers)
netw.GET("/addrs", s.handleNetAddrs)
miners := public.Group("/miners")
miners.GET("", s.handleAdminGetMiners)
miners.GET("/failures/:miner", s.handleGetMinerFailures)
miners.GET("/deals/:miner", s.handleGetMinerDeals)
miners.GET("/stats/:miner", s.handleGetMinerStats)
miners.GET("/storage/query/:miner", s.handleQueryAsk)
admin := e.Group("/admin")
admin.Use(s.AuthRequired(util.PermLevelAdmin))
admin.GET("/balance", s.handleAdminBalance)
admin.POST("/add-escrow/:amt", s.handleAdminAddEscrow)
admin.GET("/dealstats", s.handleDealStats)
admin.GET("/disk-info", s.handleDiskSpaceCheck)
admin.GET("/stats", s.handleAdminStats)
// miners
admin.POST("/miners/add/:miner", s.handleAdminAddMiner)
admin.POST("/miners/rm/:miner", s.handleAdminRemoveMiner)
admin.POST("/miners/suspend/:miner", withUser(s.handleSuspendMiner))
admin.PUT("/miners/unsuspend/:miner", withUser(s.handleUnsuspendMiner))
admin.PUT("/miners/set-info/:miner", withUser(s.handleMinersSetInfo))
admin.GET("/miners", s.handleAdminGetMiners)
admin.GET("/miners/stats", s.handleAdminGetMinerStats)
admin.GET("/miners/transfers/:miner", s.handleMinerTransferDiagnostics)
admin.GET("/cm/progress", s.handleAdminGetProgress)
admin.GET("/cm/all-deals", s.handleDebugGetAllDeals)
admin.GET("/cm/read/:content", s.handleReadLocalContent)
admin.GET("/cm/staging/all", s.handleAdminGetStagingZones)
admin.GET("/cm/offload/candidates", s.handleGetOffloadingCandidates)
admin.POST("/cm/offload/:content", s.handleOffloadContent)
admin.POST("/cm/offload/collect", s.handleRunOffloadingCollection)
admin.GET("/cm/refresh/:content", s.handleRefreshContent)
admin.POST("/cm/gc", s.handleRunGc)
admin.POST("/cm/move", s.handleMoveContent)
admin.GET("/cm/buckets", s.handleGetBucketDiag)
admin.GET("/cm/health/:id", s.handleContentHealthCheck)
admin.GET("/cm/health-by-cid/:cid", s.handleContentHealthCheckByCid)
admin.POST("/cm/dealmaking", s.handleSetDealMaking)
admin.POST("/cm/break-aggregate/:content", s.handleAdminBreakAggregate)
admin.POST("/cm/transfer/restart/:chanid", s.handleTransferRestart)
admin.POST("/cm/repinall/:shuttle", s.handleShuttleRepinAll)
admnetw := admin.Group("/net")
admnetw.GET("/peers", s.handleNetPeers)
admin.GET("/retrieval/querytest/:content", s.handleRetrievalCheck)
admin.GET("/retrieval/stats", s.handleGetRetrievalInfo)
admin.POST("/invite/:code", withUser(s.handleAdminCreateInvite))
admin.GET("/invites", s.handleAdminGetInvites)
admin.GET("/fixdeals", s.handleFixupDeals)
admin.POST("/loglevel", s.handleLogLevel)
users := admin.Group("/users")
users.GET("", s.handleAdminGetUsers)
shuttle := admin.Group("/shuttle")
shuttle.POST("/init", s.handleShuttleInit)
shuttle.GET("/list", s.handleShuttleList)
autoretrieve := admin.Group("/autoretrieve")
autoretrieve.POST("/init", s.handleAutoretrieveInit)
autoretrieve.GET("/list", s.handleAutoretrieveList)
e.POST("/autoretrieve/heartbeat", s.handleAutoretrieveHeartbeat)
e.GET("/shuttle/conn", s.handleShuttleConnection)
e.POST("/shuttle/content/create", s.handleShuttleCreateContent, s.withShuttleAuth())
if os.Getenv("ENABLE_SWAGGER_ENDPOINT") == "true" {
e.GET("/swagger/*", echoSwagger.WrapHandler)
}
return e.Start(srv)
}
type binder struct{}
func (b binder) Bind(i interface{}, c echo.Context) error {
defer c.Request().Body.Close()
return json.NewDecoder(c.Request().Body).Decode(i)
}
func serveCpuProfile(c echo.Context) error {
if err := pprof.StartCPUProfile(c.Response()); err != nil {
return err
}
defer pprof.StopCPUProfile()
select {
case <-c.Request().Context().Done():
return c.Request().Context().Err()
case <-time.After(time.Second * 30):
}
return nil
}
func serveProfile(c echo.Context) error {
httpprof.Handler(c.Param("prof")).ServeHTTP(c.Response().Writer, c.Request())
return nil
}
type statsResp struct {
ID uint `json:"id"`
Cid cid.Cid `json:"cid"`
File string `json:"file"`
BWUsed int64 `json:"bwUsed"`
TotalRequests int64 `json:"totalRequests"`
Offloaded bool `json:"offloaded"`
AggregatedFiles int64 `json:"aggregatedFiles"`
}
func withUser(f func(echo.Context, *User) error) func(echo.Context) error {
return func(c echo.Context) error {
u, ok := c.Get("user").(*User)
if !ok {
return fmt.Errorf("endpoint not called with proper authentication")
}
return f(c, u)
}
}
// TODO: delete me when debugging done
func (s *Server) handleTestError(c echo.Context) error {
return fmt.Errorf("i am a scary error, log me please more")
}
// handleStats godoc
// @Summary Get content statistics
// @Description This endpoint is used to get content statistics. Every content stored in the network (estuary) is tracked by a unique ID which can be used to get information about the content. This endpoint will allow the consumer to get the collected stats of a conten
// @Tags content
// @Param limit path string true "limit"
// @Produce json
// @Router /content/stats [get]
func (s *Server) handleStats(c echo.Context, u *User) error {
limit := 500
if limstr := c.QueryParam("limit"); limstr != "" {
nlim, err := strconv.Atoi(limstr)
if err != nil {
return err
}
if nlim > 0 {
limit = nlim
}
}
offset := 0
if offstr := c.QueryParam("offset"); offstr != "" {
noff, err := strconv.Atoi(offstr)
if err != nil {
return err
}
if noff > 0 {
offset = noff
}
}
var contents []Content
if err := s.DB.Limit(limit).Offset(offset).Order("created_at desc").Find(&contents, "user_id = ? and active", u.ID).Error; err != nil {
return err
}
out := make([]statsResp, 0, len(contents))
for _, c := range contents {
st := statsResp{
ID: c.ID,
Cid: c.Cid.CID,
File: c.Name,
}
if false {
var res struct {
Bw int64
TotalReads int64
}
if err := s.DB.Model(ObjRef{}).
Select("SUM(size * reads) as bw, SUM(reads) as total_reads").
Where("obj_refs.content = ?", c.ID).
Joins("left join objects on obj_refs.object = objects.id").
Scan(&res).Error; err != nil {
return err
}
st.TotalRequests = res.TotalReads
st.BWUsed = res.Bw
}
if c.Aggregate {
if err := s.DB.Model(Content{}).Where("aggregated_in = ?", c.ID).Count(&st.AggregatedFiles).Error; err != nil {
return err
}
}
out = append(out, st)
}
return c.JSON(200, out)
}
// handleAddIpfs godoc
// @Summary Add IPFS object
// @Description This endpoint is used to add an IPFS object to the network. The object can be a file or a directory.
// @Tags content
// @Produce json
// @Param body body util.ContentAddIpfsBody true "IPFS Body"
// @Router /content/add-ipfs [post]
func (s *Server) handleAddIpfs(c echo.Context, u *User) error {
ctx := c.Request().Context()
if s.CM.contentAddingDisabled || u.StorageDisabled {
return &util.HttpError{
Code: 400,
Message: util.ERR_CONTENT_ADDING_DISABLED,
}
}
var params util.ContentAddIpfsBody
if err := c.Bind(¶ms); err != nil {
return err
}
filename := params.Name
if filename == "" {
filename = params.Root
}
var cols []*CollectionRef
if params.Collection != "" {
var srchCol Collection
if err := s.DB.First(&srchCol, "uuid = ? and user_id = ?", params.Collection, u.ID).Error; err != nil {
return err
}
// if collectionPath is "" or nil, put the file on the root dir (/filename)
defaultPath := "/" + filename
colp := defaultPath
if params.CollectionPath != "" {
p, err := sanitizePath(params.CollectionPath)
if err != nil {
return err
}
colp = p
}
// default: colp ends in / (does not include filename e.g. /hello/)
pathWithFilename := colp + filename
// if path does not end in /, it includes the filename
if !strings.HasSuffix(colp, "/") {
pathWithFilename = colp
filename = filepath.Base(colp)
}
cols = []*CollectionRef{&CollectionRef{
Collection: srchCol.ID,
Path: &pathWithFilename,
}}
}
var addrInfos []peer.AddrInfo
for _, p := range params.Peers {
ai, err := peer.AddrInfoFromString(p)
if err != nil {
return err
}
addrInfos = append(addrInfos, *ai)
}
rcid, err := cid.Decode(params.Root)
if err != nil {
return err
}
if c.QueryParam("ignore-dupes") == "true" {
var count int64
if err := s.DB.Model(Content{}).Where("cid = ? and user_id = ?", rcid.Bytes(), u.ID).Count(&count).Error; err != nil {
return err
}
if count > 0 {
return c.JSON(302, map[string]string{"message": "content with given cid already preserved"})
}
}
makeDeal := true
pinstatus, err := s.CM.pinContent(ctx, u.ID, rcid, filename, cols, addrInfos, 0, nil, makeDeal)
if err != nil {
return err
}
return c.JSON(202, pinstatus)
}
// handleAddCar godoc
// @Summary Add Car object
// @Description This endpoint is used to add a car object to the network. The object can be a file or a directory.
// @Tags content
// @Produce json
// @Param body body string true "Car"
// @Param filename query string false "Filename"
// @Param commp query string false "Commp"
// @Param size query string false "Size"
// @Router /content/add-car [post]
func (s *Server) handleAddCar(c echo.Context, u *User) error {
ctx := c.Request().Context()
if s.CM.contentAddingDisabled || u.StorageDisabled || s.CM.localContentAddingDisabled {
return &util.HttpError{
Code: 400,
Message: util.ERR_CONTENT_ADDING_DISABLED,
}
}
bsid, sbs, err := s.StagingMgr.AllocNew()
if err != nil {
return err
}
defer func() {
go func() {
if err := s.StagingMgr.CleanUp(bsid); err != nil {
log.Errorf("failed to clean up staging blockstore: %s", err)
}
}()
}()
defer c.Request().Body.Close()
header, err := s.loadCar(ctx, sbs, c.Request().Body)
if err != nil {
return err
}
if len(header.Roots) != 1 {
// if someone wants this feature, let me know
return c.JSON(400, map[string]string{"error": "cannot handle uploading car files with multiple roots"})
}
rootCID := header.Roots[0]
if c.QueryParam("ignore-dupes") == "true" {
isDup, err := s.isDupCIDContent(c, rootCID, u)
if err != nil || isDup {
return err
}
}
// TODO: how to specify filename?
filename := rootCID.String()
if qpname := c.QueryParam("filename"); qpname != "" {
filename = qpname
}
var commpcid cid.Cid
var commpSize abi.UnpaddedPieceSize
if cpc := c.QueryParam("commp"); cpc != "" {
if u.Perm < util.PermLevelAdmin {
return fmt.Errorf("must be an admin to specify commp for car file upload")
}
sizestr := c.QueryParam("size")
if sizestr == "" {
return fmt.Errorf("must also specify 'size' when setting commP for car files")
}
ss, err := strconv.ParseUint(sizestr, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse size: %w", err)
}
commpSize = abi.UnpaddedPieceSize(ss)
if err := commpSize.Validate(); err != nil {
return fmt.Errorf("given commP size was invalid: %w", err)
}
cc, err := cid.Decode(cpc)
if err != nil {
return err
}
_, err = commcid.CIDToPieceCommitmentV1(cc)
if err != nil {
return err
}
commpcid = cc
}
bserv := blockservice.New(sbs, nil)
dserv := merkledag.NewDAGService(bserv)
cont, err := s.CM.addDatabaseTracking(ctx, u, dserv, s.Node.Blockstore, rootCID, filename, s.CM.Replication)
if err != nil {
return err
}
if err := s.dumpBlockstoreTo(ctx, sbs, s.Node.Blockstore); err != nil {
return xerrors.Errorf("failed to move data from staging to main blockstore: %w", err)
}
if commpcid.Defined() {
carSize, err := s.CM.calculateCarSize(ctx, header.Roots[0])
if err != nil {
return fmt.Errorf("failed to calculate CAR size: %w", err)
}
opcr := PieceCommRecord{
Data: util.DbCID{rootCID},
Piece: util.DbCID{commpcid},
Size: commpSize,
CarSize: carSize,
}
if err := s.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&opcr).Error; err != nil {
return fmt.Errorf("failed to insert piece commitment record: %w", err)
}
}
go func() {
// TODO: we should probably have a queue to throw these in instead of putting them out in goroutines...
s.CM.ToCheck <- cont.ID
}()
go func() {
if err := s.Node.Provider.Provide(rootCID); err != nil {
log.Warnf("failed to announce providers: %s", err)
}
}()
return c.JSON(200, map[string]interface{}{"content": cont})
}
func (s *Server) loadCar(ctx context.Context, bs blockstore.Blockstore, r io.Reader) (*car.CarHeader, error) {
_, span := s.tracer.Start(ctx, "loadCar")
defer span.End()
return car.LoadCar(ctx, bs, r)
}
// handleAdd godoc
// @Summary Add new content
// @Description This endpoint is used to upload new content.
// @Tags content
// @Produce json
// @Accept multipart/form-data
// @Param file formData file true "File to upload"
// @Router /content/add [post]
func (s *Server) handleAdd(c echo.Context, u *User) error {
ctx, span := s.tracer.Start(c.Request().Context(), "handleAdd", trace.WithAttributes(attribute.Int("user", int(u.ID))))
defer span.End()
if s.CM.contentAddingDisabled || u.StorageDisabled || s.CM.localContentAddingDisabled {
if s.CM.localContentAddingDisabled {
uep, err := s.getPreferredUploadEndpoints(u)
if err != nil {
log.Warnf("failed to get preferred upload endpoints: %s", err)
} else if len(uep) > 0 {
// details := fmt.Sprintf("this estuary instance has disabled adding new content, please redirect your request to one of the following endpoints: %v", uep)
return c.Redirect(http.StatusPermanentRedirect, uep[rand.Intn(len(uep))]) // redirect to a random preferred endpoint
}
}
return &util.HttpError{
Code: 400,
Message: util.ERR_CONTENT_ADDING_DISABLED,
}
}
form, err := c.MultipartForm()
if err != nil {
return err
}
defer form.RemoveAll()
mpf, err := c.FormFile("data")
if err != nil {
return err
}
fname := mpf.Filename
if fvname := c.FormValue("name"); fvname != "" {
fname = fvname
}
fi, err := mpf.Open()
if err != nil {
return err
}
defer fi.Close()
replication := s.CM.Replication
replVal := c.FormValue("replication")
if replVal != "" {
parsed, err := strconv.Atoi(replVal)
if err != nil {
log.Errorf("failed to parse replication value in form data, assuming default for now: %s", err)
} else {
replication = parsed
}
}
collection := c.FormValue("collection")
var col *Collection
if collection != "" {
var srchCol Collection
if err := s.DB.First(&srchCol, "uuid = ? and user_id = ?", collection, u.ID).Error; err != nil {
return err
}
col = &srchCol
}
var colpath *string
if cp := c.FormValue("collectionPath"); cp != "" {
sp, err := sanitizePath(cp)
if err != nil {
return err
}
colpath = &sp
}
bsid, bs, err := s.StagingMgr.AllocNew()
if err != nil {
return err
}
defer func() {
go func() {
if err := s.StagingMgr.CleanUp(bsid); err != nil {
log.Errorf("failed to clean up staging blockstore: %s", err)
}
}()
}()
bserv := blockservice.New(bs, nil)
dserv := merkledag.NewDAGService(bserv)
nd, err := s.importFile(ctx, dserv, fi)
if err != nil {
return err
}
if c.QueryParam("ignore-dupes") == "true" {
isDup, err := s.isDupCIDContent(c, nd.Cid(), u)
if err != nil || isDup {
return err
}
}
content, err := s.CM.addDatabaseTracking(ctx, u, dserv, bs, nd.Cid(), fname, replication)
if err != nil {
return xerrors.Errorf("encountered problem computing object references: %w", err)
}
if col != nil {
fmt.Println("COLLECTION CREATION: ", col.ID, content.ID)
if err := s.DB.Create(&CollectionRef{
Collection: col.ID,
Content: content.ID,
Path: colpath,
}).Error; err != nil {
log.Errorf("failed to add content to requested collection: %s", err)
}
}
if err := s.dumpBlockstoreTo(ctx, bs, s.Node.Blockstore); err != nil {
return xerrors.Errorf("failed to move data from staging to main blockstore: %w", err)
}
go func() {
s.CM.ToCheck <- content.ID
}()
if c.QueryParam("lazy-provide") != "true" {
subctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
if err := s.Node.FullRT.Provide(subctx, nd.Cid(), true); err != nil {
span.RecordError(fmt.Errorf("provide error: %w", err))
log.Errorf("fullrt provide call errored: %s", err)
}
}
go func() {
if err := s.Node.Provider.Provide(nd.Cid()); err != nil {
log.Warnf("failed to announce providers: %s", err)
}
}()
return c.JSON(200, &util.ContentAddResponse{
Cid: nd.Cid().String(),
EstuaryId: content.ID,
Providers: s.CM.pinDelegatesForContent(*content),
})
}
func (s *Server) importFile(ctx context.Context, dserv ipld.DAGService, fi io.Reader) (ipld.Node, error) {
_, span := s.tracer.Start(ctx, "importFile")
defer span.End()
return util.ImportFile(dserv, fi)
}
var noDataTimeout = time.Minute * 10
func (cm *ContentManager) addDatabaseTrackingToContent(ctx context.Context, cont uint, dserv ipld.NodeGetter, bs blockstore.Blockstore, root cid.Cid, cb func(int64)) error {
ctx, span := cm.tracer.Start(ctx, "computeObjRefsUpdate")
defer span.End()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
gotData := make(chan struct{}, 1)
go func() {
nodata := time.NewTimer(noDataTimeout)
defer nodata.Stop()
for {
select {
case <-nodata.C:
cancel()
case <-gotData:
nodata.Reset(noDataTimeout)
case <-ctx.Done():
return
}
}
}()
var objlk sync.Mutex
var objects []*Object
cset := cid.NewSet()
defer func() {
cm.inflightCidsLk.Lock()
_ = cset.ForEach(func(c cid.Cid) error {
v, ok := cm.inflightCids[c]
if !ok || v <= 0 {
log.Errorf("cid should be inflight but isn't: %s", c)
}
cm.inflightCids[c]--
if cm.inflightCids[c] == 0 {
delete(cm.inflightCids, c)
}
return nil
})
cm.inflightCidsLk.Unlock()
}()
err := merkledag.Walk(ctx, func(ctx context.Context, c cid.Cid) ([]*ipld.Link, error) {
// cset.Visit gets called first, so if we reach here we should immediately track the CID
cm.inflightCidsLk.Lock()
cm.inflightCids[c]++
cm.inflightCidsLk.Unlock()
node, err := dserv.Get(ctx, c)
if err != nil {
return nil, err
}
cb(int64(len(node.RawData())))
select {
case gotData <- struct{}{}:
case <-ctx.Done():
}
objlk.Lock()
objects = append(objects, &Object{
Cid: util.DbCID{c},
Size: len(node.RawData()),
})
objlk.Unlock()
if c.Type() == cid.Raw {
return nil, nil
}
return node.Links(), nil
}, root, cset.Visit, merkledag.Concurrent())
if err != nil {
return err
}
if err = cm.addObjectsToDatabase(ctx, cont, dserv, root, objects, "local"); err != nil {
return err
}
return nil
}
func (cm *ContentManager) addDatabaseTracking(ctx context.Context, u *User, dserv ipld.NodeGetter, bs blockstore.Blockstore, root cid.Cid, fname string, replication int) (*Content, error) {
ctx, span := cm.tracer.Start(ctx, "computeObjRefs")
defer span.End()
content := &Content{
Cid: util.DbCID{root},
Name: fname,
Active: false,
Pinning: true,
UserID: u.ID,
Replication: replication,
Location: "local",
}
if err := cm.DB.Create(content).Error; err != nil {
return nil, xerrors.Errorf("failed to track new content in database: %w", err)
}
if err := cm.addDatabaseTrackingToContent(ctx, content.ID, dserv, bs, root, func(int64) {}); err != nil {
return nil, err
}
return content, nil
}
func (s *Server) dumpBlockstoreTo(ctx context.Context, from, to blockstore.Blockstore) error {
ctx, span := s.tracer.Start(ctx, "blockstoreCopy")
defer span.End()
// TODO: smarter batching... im sure ive written this logic before, just gotta go find it
keys, err := from.AllKeysChan(ctx)
if err != nil {
return err
}
var batch []blocks.Block
for k := range keys {
blk, err := from.Get(ctx, k)
if err != nil {
return err
}
batch = append(batch, blk)
if len(batch) > 500 {
if err := to.PutMany(ctx, batch); err != nil {
return err
}
batch = batch[:0]
}