-
Notifications
You must be signed in to change notification settings - Fork 26
/
allocation.go
2557 lines (2254 loc) · 73 KB
/
allocation.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 sdk
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/0chain/common/core/currency"
"github.com/0chain/errors"
thrown "github.com/0chain/errors"
"github.com/0chain/gosdk/constants"
"github.com/0chain/gosdk/core/common"
"github.com/0chain/gosdk/core/pathutil"
"github.com/0chain/gosdk/core/sys"
"github.com/0chain/gosdk/zboxcore/blockchain"
"github.com/0chain/gosdk/zboxcore/fileref"
"github.com/0chain/gosdk/zboxcore/logger"
l "github.com/0chain/gosdk/zboxcore/logger"
"github.com/0chain/gosdk/zboxcore/marker"
"github.com/0chain/gosdk/zboxcore/zboxutil"
"github.com/mitchellh/go-homedir"
"go.uber.org/zap"
)
var (
noBLOBBERS = errors.New("", "No Blobbers set in this allocation")
notInitialized = errors.New("sdk_not_initialized", "Please call InitStorageSDK Init and use GetAllocation to get the allocation object")
IsWasm = false
MultiOpBatchSize = 50
Workdir string
)
const (
KB = 1024
MB = 1024 * KB
GB = 1024 * MB
)
const (
CanUploadMask = uint16(1) // 0000 0001
CanDeleteMask = uint16(2) // 0000 0010
CanUpdateMask = uint16(4) // 0000 0100
CanMoveMask = uint16(8) // 0000 1000
CanCopyMask = uint16(16) // 0001 0000
CanRenameMask = uint16(32) // 0010 0000
)
const (
emptyFileDataHash = "d41d8cd98f00b204e9800998ecf8427e"
)
// Expected success rate is calculated (NumDataShards)*100/(NumDataShards+NumParityShards)
var GetFileInfo = func(localpath string) (os.FileInfo, error) {
return sys.Files.Stat(localpath)
}
type BlobberAllocationStats struct {
BlobberID string
BlobberURL string
ID string `json:"ID"`
Tx string `json:"Tx"`
TotalSize int64 `json:"TotalSize"`
UsedSize int `json:"UsedSize"`
OwnerID string `json:"OwnerID"`
OwnerPublicKey string `json:"OwnerPublicKey"`
Expiration int `json:"Expiration"`
AllocationRoot string `json:"AllocationRoot"`
BlobberSize int `json:"BlobberSize"`
BlobberSizeUsed int `json:"BlobberSizeUsed"`
LatestRedeemedWM string `json:"LatestRedeemedWM"`
IsRedeemRequired bool `json:"IsRedeemRequired"`
CleanedUp bool `json:"CleanedUp"`
Finalized bool `json:"Finalized"`
Terms []struct {
ID int `json:"ID"`
BlobberID string `json:"BlobberID"`
AllocationID string `json:"AllocationID"`
ReadPrice int `json:"ReadPrice"`
WritePrice int `json:"WritePrice"`
} `json:"Terms"`
}
type ConsolidatedFileMeta struct {
Name string
Type string
Path string
LookupHash string
Hash string
MimeType string
Size int64
NumBlocks int64
ActualFileSize int64
ActualNumBlocks int64
EncryptedKey string
ActualThumbnailSize int64
ActualThumbnailHash string
Collaborators []fileref.Collaborator
}
type AllocationStats struct {
UsedSize int64 `json:"used_size"`
NumWrites int64 `json:"num_of_writes"`
NumReads int64 `json:"num_of_reads"`
TotalChallenges int64 `json:"total_challenges"`
OpenChallenges int64 `json:"num_open_challenges"`
SuccessChallenges int64 `json:"num_success_challenges"`
FailedChallenges int64 `json:"num_failed_challenges"`
LastestClosedChallengeTxn string `json:"latest_closed_challenge"`
}
// PriceRange represents a price range allowed by user to filter blobbers.
type PriceRange struct {
Min uint64 `json:"min"`
Max uint64 `json:"max"`
}
// IsValid price range.
func (pr *PriceRange) IsValid() bool {
return pr.Min <= pr.Max
}
// Terms represents Blobber terms. A Blobber can update its terms,
// but any existing offer will use terms of offer signing time.
type Terms struct {
ReadPrice common.Balance `json:"read_price"` // tokens / GB
WritePrice common.Balance `json:"write_price"` // tokens / GB
MaxOfferDuration time.Duration `json:"max_offer_duration"`
}
// UpdateTerms represents Blobber terms during update blobber calls.
// A Blobber can update its terms, but any existing offer will use terms of offer signing time.
type UpdateTerms struct {
ReadPrice *common.Balance `json:"read_price,omitempty"` // tokens / GB
WritePrice *common.Balance `json:"write_price,omitempty"` // tokens / GB
MaxOfferDuration *time.Duration `json:"max_offer_duration,omitempty"`
}
type BlobberAllocation struct {
BlobberID string `json:"blobber_id"`
Size int64 `json:"size"`
Terms Terms `json:"terms"`
MinLockDemand common.Balance `json:"min_lock_demand"`
Spent common.Balance `json:"spent"`
Penalty common.Balance `json:"penalty"`
ReadReward common.Balance `json:"read_reward"`
Returned common.Balance `json:"returned"`
ChallengeReward common.Balance `json:"challenge_reward"`
FinalReward common.Balance `json:"final_reward"`
}
type Allocation struct {
ID string `json:"id"`
Tx string `json:"tx"`
DataShards int `json:"data_shards"`
ParityShards int `json:"parity_shards"`
Size int64 `json:"size"`
Expiration int64 `json:"expiration_date"`
Owner string `json:"owner_id"`
OwnerPublicKey string `json:"owner_public_key"`
Payer string `json:"payer_id"`
Blobbers []*blockchain.StorageNode `json:"blobbers"`
Stats *AllocationStats `json:"stats"`
TimeUnit time.Duration `json:"time_unit"`
WritePool common.Balance `json:"write_pool"`
// BlobberDetails contains real terms used for the allocation.
// If the allocation has updated, then terms calculated using
// weighted average values.
BlobberDetails []*BlobberAllocation `json:"blobber_details"`
// ReadPriceRange is requested reading prices range.
ReadPriceRange PriceRange `json:"read_price_range"`
// WritePriceRange is requested writing prices range.
WritePriceRange PriceRange `json:"write_price_range"`
MinLockDemand float64 `json:"min_lock_demand"`
ChallengeCompletionTime time.Duration `json:"challenge_completion_time"`
StartTime common.Timestamp `json:"start_time"`
Finalized bool `json:"finalized,omitempty"`
Canceled bool `json:"canceled,omitempty"`
MovedToChallenge common.Balance `json:"moved_to_challenge,omitempty"`
MovedBack common.Balance `json:"moved_back,omitempty"`
MovedToValidators common.Balance `json:"moved_to_validators,omitempty"`
FileOptions uint16 `json:"file_options"`
ThirdPartyExtendable bool `json:"third_party_extendable"`
numBlockDownloads int
downloadChan chan *DownloadRequest
repairChan chan *RepairRequest
ctx context.Context
ctxCancelF context.CancelFunc
mutex *sync.Mutex
commitMutex *sync.Mutex
downloadProgressMap map[string]*DownloadRequest
downloadRequests []*DownloadRequest
repairRequestInProgress *RepairRequest
initialized bool
checkStatus bool
readFree bool
// conseususes
consensusThreshold int
fullconsensus int
}
type OperationRequest struct {
OperationType string
LocalPath string
RemotePath string
DestName string // Required only for rename operation
DestPath string // Required for copy and move operation
IsUpdate bool
IsRepair bool // Required for repair operation
IsWebstreaming bool
// Required for uploads
Workdir string
FileMeta FileMeta
FileReader io.Reader
Mask *zboxutil.Uint128 // Required for delete repair operation
DownloadFile bool // Required for upload repair operation
StreamUpload bool // Required for streaming file when actualSize is not available
Opts []ChunkedUploadOption
}
func GetReadPriceRange() (PriceRange, error) {
return getPriceRange("max_read_price")
}
func GetWritePriceRange() (PriceRange, error) {
return getPriceRange("max_write_price")
}
func SetMultiOpBatchSize(size int) {
MultiOpBatchSize = size
}
func SetWasm() {
IsWasm = true
BatchSize = 5
}
func getPriceRange(name string) (PriceRange, error) {
conf, err := GetStorageSCConfig()
if err != nil {
return PriceRange{}, err
}
f := conf.Fields[name]
fStr, ok := f.(string)
if !ok {
return PriceRange{}, fmt.Errorf("type is wrong")
}
mrp, err := strconv.ParseFloat(fStr, 64)
if err != nil {
return PriceRange{}, err
}
coin, err := currency.ParseZCN(mrp)
if err != nil {
return PriceRange{}, err
}
max, err := coin.Int64()
if err != nil {
return PriceRange{}, err
}
return PriceRange{0, uint64(max)}, err
}
func (a *Allocation) GetStats() *AllocationStats {
return a.Stats
}
func (a *Allocation) GetBlobberStats() map[string]*BlobberAllocationStats {
numList := len(a.Blobbers)
wg := &sync.WaitGroup{}
wg.Add(numList)
rspCh := make(chan *BlobberAllocationStats, numList)
for _, blobber := range a.Blobbers {
go getAllocationDataFromBlobber(blobber, a.ID, a.Tx, rspCh, wg)
}
wg.Wait()
result := make(map[string]*BlobberAllocationStats, len(a.Blobbers))
for i := 0; i < numList; i++ {
resp := <-rspCh
result[resp.BlobberURL] = resp
}
return result
}
const downloadWorkerCount = 6
func (a *Allocation) InitAllocation() {
a.downloadChan = make(chan *DownloadRequest, 100)
a.repairChan = make(chan *RepairRequest, 1)
a.ctx, a.ctxCancelF = context.WithCancel(context.Background())
a.downloadProgressMap = make(map[string]*DownloadRequest)
a.downloadRequests = make([]*DownloadRequest, 0, 100)
a.mutex = &sync.Mutex{}
a.commitMutex = &sync.Mutex{}
a.fullconsensus, a.consensusThreshold = a.getConsensuses()
for _, blobber := range a.Blobbers {
zboxutil.SetHostClient(blobber.ID, blobber.Baseurl)
}
a.readFree = true
if a.ReadPriceRange.Max > 0 {
for _, blobberDetail := range a.BlobberDetails {
if blobberDetail.Terms.ReadPrice > 0 {
a.readFree = false
break
}
}
}
a.startWorker(a.ctx)
InitCommitWorker(a.Blobbers)
InitBlockDownloader(a.Blobbers, downloadWorkerCount)
a.initialized = true
}
func (a *Allocation) isInitialized() bool {
return a.initialized && sdkInitialized
}
func (a *Allocation) startWorker(ctx context.Context) {
go a.dispatchWork(ctx)
}
func (a *Allocation) dispatchWork(ctx context.Context) {
for {
select {
case <-ctx.Done():
l.Logger.Info("Upload cancelled by the parent")
return
case downloadReq := <-a.downloadChan:
l.Logger.Info(fmt.Sprintf("received a download request for %v\n", downloadReq.remotefilepath))
go func() {
downloadReq.processDownload()
}()
case repairReq := <-a.repairChan:
l.Logger.Info(fmt.Sprintf("received a repair request for %v\n", repairReq.listDir.Path))
go repairReq.processRepair(ctx, a)
}
}
}
func (a *Allocation) CanUpload() bool {
return (a.FileOptions & CanUploadMask) > 0
}
func (a *Allocation) CanDelete() bool {
return (a.FileOptions & CanDeleteMask) > 0
}
func (a *Allocation) CanUpdate() bool {
return (a.FileOptions & CanUpdateMask) > 0
}
func (a *Allocation) CanMove() bool {
return (a.FileOptions & CanMoveMask) > 0
}
func (a *Allocation) CanCopy() bool {
return (a.FileOptions & CanCopyMask) > 0
}
func (a *Allocation) CanRename() bool {
return (a.FileOptions & CanRenameMask) > 0
}
// UpdateFile [Deprecated]please use CreateChunkedUpload
func (a *Allocation) UpdateFile(workdir, localpath string, remotepath string,
status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, true, false, "", false, false)
}
// UploadFile [Deprecated]please use CreateChunkedUpload
func (a *Allocation) UploadFile(workdir, localpath string, remotepath string,
status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", false, false)
}
func (a *Allocation) RepairFile(file sys.File, remotepath string, statusCallback StatusCallback, mask zboxutil.Uint128, ref *fileref.FileRef) *OperationRequest {
idr, _ := homedir.Dir()
if Workdir != "" {
idr = Workdir
}
mask = mask.Not().And(zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1))
fileMeta := FileMeta{
ActualSize: ref.ActualFileSize,
MimeType: ref.MimeType,
RemoteName: ref.Name,
RemotePath: remotepath,
}
var opts []ChunkedUploadOption
if ref.EncryptedKey != "" {
opts = []ChunkedUploadOption{
WithMask(mask),
WithEncrypt(true),
WithStatusCallback(statusCallback),
WithEncryptedPoint(ref.EncryptedKeyPoint),
WithChunkNumber(100),
}
} else {
opts = []ChunkedUploadOption{
WithMask(mask),
WithStatusCallback(statusCallback),
WithChunkNumber(100),
}
}
op := &OperationRequest{
OperationType: constants.FileOperationInsert,
IsRepair: true,
RemotePath: remotepath,
Workdir: idr,
FileMeta: fileMeta,
Opts: opts,
FileReader: file,
}
if ref.ActualFileHash == emptyFileDataHash {
op.FileMeta.ActualSize = 0
}
return op
}
// UpdateFileWithThumbnail [Deprecated]please use CreateChunkedUpload
func (a *Allocation) UpdateFileWithThumbnail(workdir, localpath string, remotepath string,
thumbnailpath string, status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, true, false,
thumbnailpath, false, false)
}
// UploadFileWithThumbnail [Deprecated]please use CreateChunkedUpload
func (a *Allocation) UploadFileWithThumbnail(workdir string, localpath string,
remotepath string, thumbnailpath string,
status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false,
thumbnailpath, false, false)
}
// EncryptAndUpdateFile [Deprecated]please use CreateChunkedUpload
func (a *Allocation) EncryptAndUpdateFile(workdir string, localpath string, remotepath string,
status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, true, false, "", true, false)
}
// EncryptAndUploadFile [Deprecated]please use CreateChunkedUpload
func (a *Allocation) EncryptAndUploadFile(workdir string, localpath string, remotepath string,
status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, false, false, "", true, false)
}
// EncryptAndUpdateFileWithThumbnail [Deprecated]please use CreateChunkedUpload
func (a *Allocation) EncryptAndUpdateFileWithThumbnail(workdir string, localpath string,
remotepath string, thumbnailpath string, status StatusCallback) error {
return a.StartChunkedUpload(workdir, localpath, remotepath, status, true, false,
thumbnailpath, true, false)
}
// EncryptAndUploadFileWithThumbnail [Deprecated]please use CreateChunkedUpload
func (a *Allocation) EncryptAndUploadFileWithThumbnail(
workdir string,
localpath string,
remotepath string,
thumbnailpath string,
status StatusCallback,
) error {
return a.StartChunkedUpload(workdir,
localpath,
remotepath,
status,
false,
false,
thumbnailpath,
true,
false,
)
}
func (a *Allocation) StartMultiUpload(workdir string, localPaths []string, fileNames []string, thumbnailPaths []string, encrypts []bool, chunkNumbers []int, remotePaths []string, isUpdate []bool, isWebstreaming []bool, status StatusCallback) error {
if len(localPaths) != len(thumbnailPaths) {
return errors.New("invalid_value", "length of localpaths and thumbnailpaths must be equal")
}
if len(localPaths) != len(encrypts) {
return errors.New("invalid_value", "length of encrypt not equal to number of files")
}
if !a.isInitialized() {
return notInitialized
}
if !a.CanUpload() {
return constants.ErrFileOptionNotPermitted
}
totalOperations := len(localPaths)
if totalOperations == 0 {
return nil
}
operationRequests := make([]OperationRequest, totalOperations)
for idx, localPath := range localPaths {
remotePath := zboxutil.RemoteClean(remotePaths[idx])
isabs := zboxutil.IsRemoteAbs(remotePath)
if !isabs {
err := thrown.New("invalid_path", "Path should be valid and absolute")
return err
}
fileReader, err := os.Open(localPath)
if err != nil {
return err
}
defer fileReader.Close()
thumbnailPath := thumbnailPaths[idx]
fileName := fileNames[idx]
chunkNumber := chunkNumbers[idx]
if fileName == "" {
return thrown.New("invalid_param", "filename can't be empty")
}
encrypt := encrypts[idx]
fileInfo, err := fileReader.Stat()
if err != nil {
return err
}
mimeType, err := zboxutil.GetFileContentType(path.Ext(fileName), fileReader)
if err != nil {
return err
}
if !strings.HasSuffix(remotePath, "/") {
remotePath = remotePath + "/"
}
fullRemotePath := zboxutil.GetFullRemotePath(localPath, remotePath)
fullRemotePathWithoutName, _ := pathutil.Split(fullRemotePath)
fullRemotePath = fullRemotePathWithoutName + "/" + fileName
fileMeta := FileMeta{
Path: localPath,
ActualSize: fileInfo.Size(),
MimeType: mimeType,
RemoteName: fileName,
RemotePath: fullRemotePath,
}
options := []ChunkedUploadOption{
WithStatusCallback(status),
WithEncrypt(encrypt),
}
if chunkNumber != 0 {
options = append(options, WithChunkNumber(chunkNumber))
}
if thumbnailPath != "" {
buf, err := sys.Files.ReadFile(thumbnailPath)
if err != nil {
return err
}
options = append(options, WithThumbnail(buf))
}
operationRequests[idx] = OperationRequest{
FileMeta: fileMeta,
FileReader: fileReader,
OperationType: constants.FileOperationInsert,
Opts: options,
Workdir: workdir,
RemotePath: fileMeta.RemotePath,
}
if isUpdate[idx] {
operationRequests[idx].OperationType = constants.FileOperationUpdate
}
if isWebstreaming[idx] {
operationRequests[idx].IsWebstreaming = true
}
}
err := a.DoMultiOperation(operationRequests)
if err != nil {
logger.Logger.Error("Error in multi upload ", err.Error())
return err
}
return nil
}
func (a *Allocation) StartChunkedUpload(workdir, localPath string,
remotePath string,
status StatusCallback,
isUpdate bool,
isRepair bool,
thumbnailPath string,
encryption bool,
webStreaming bool,
uploadOpts ...ChunkedUploadOption,
) error {
if !a.isInitialized() {
return notInitialized
}
if (!isUpdate && !a.CanUpload()) || (isUpdate && !a.CanUpdate()) {
return constants.ErrFileOptionNotPermitted
}
fileReader, err := os.Open(localPath)
if err != nil {
return err
}
defer fileReader.Close()
fileInfo, err := fileReader.Stat()
if err != nil {
return err
}
remotePath = zboxutil.RemoteClean(remotePath)
isabs := zboxutil.IsRemoteAbs(remotePath)
if !isabs {
err = thrown.New("invalid_path", "Path should be valid and absolute")
return err
}
remotePath = zboxutil.GetFullRemotePath(localPath, remotePath)
_, fileName := pathutil.Split(remotePath)
mimeType, err := zboxutil.GetFileContentType(path.Ext(fileName), fileReader)
if err != nil {
return err
}
fileMeta := FileMeta{
Path: localPath,
ActualSize: fileInfo.Size(),
MimeType: mimeType,
RemoteName: fileName,
RemotePath: remotePath,
}
options := []ChunkedUploadOption{
WithEncrypt(encryption),
WithStatusCallback(status),
}
options = append(options, uploadOpts...)
if thumbnailPath != "" {
buf, err := sys.Files.ReadFile(thumbnailPath)
if err != nil {
return err
}
options = append(options, WithThumbnail(buf))
}
connectionId := zboxutil.NewConnectionId()
now := time.Now()
ChunkedUpload, err := CreateChunkedUpload(a.ctx, workdir,
a, fileMeta, fileReader,
isUpdate, isRepair, webStreaming, connectionId,
options...)
if err != nil {
return err
}
elapsedCreateChunkedUpload := time.Since(now)
logger.Logger.Info("[StartChunkedUpload]", zap.String("allocation_id", a.ID),
zap.Duration("CreateChunkedUpload", elapsedCreateChunkedUpload))
return ChunkedUpload.Start()
}
func (a *Allocation) GetCurrentVersion() (bool, error) {
//get versions from blobbers
wg := &sync.WaitGroup{}
markerChan := make(chan *RollbackBlobber, len(a.Blobbers))
var errCnt int32
for _, blobber := range a.Blobbers {
wg.Add(1)
go func(blobber *blockchain.StorageNode) {
defer wg.Done()
wr, err := GetWritemarker(a.ID, a.Tx, blobber.ID, blobber.Baseurl)
if err != nil {
atomic.AddInt32(&errCnt, 1)
logger.Logger.Error("error during getWritemarke", zap.Error(err))
}
if wr == nil {
markerChan <- nil
} else {
markerChan <- &RollbackBlobber{
blobber: blobber,
lpm: wr,
commitResult: &CommitResult{},
}
}
}(blobber)
}
wg.Wait()
close(markerChan)
versionMap := make(map[int64][]*RollbackBlobber)
for rb := range markerChan {
if rb == nil {
continue
}
if _, ok := versionMap[rb.lpm.LatestWM.Timestamp]; !ok {
versionMap[rb.lpm.LatestWM.Timestamp] = make([]*RollbackBlobber, 0)
}
versionMap[rb.lpm.LatestWM.Timestamp] = append(versionMap[rb.lpm.LatestWM.Timestamp], rb)
if len(versionMap) > 2 {
return false, fmt.Errorf("more than 2 versions found")
}
}
// TODO: check how many blobbers can be down
if errCnt > 0 {
return false, fmt.Errorf("error in getting writemarker from %v blobbers", errCnt)
}
if len(versionMap) == 0 {
return false, nil
}
// TODO:return if len(versionMap) == 1
var prevVersion int64
var latestVersion int64
for version := range versionMap {
if prevVersion == 0 {
prevVersion = version
} else {
latestVersion = version
}
}
if prevVersion > latestVersion {
prevVersion, latestVersion = latestVersion, prevVersion
}
// TODO: Check if allocation can be repaired
success := true
// rollback to prev version
for _, rb := range versionMap[latestVersion] {
wg.Add(1)
go func(rb *RollbackBlobber) {
defer wg.Done()
err := rb.processRollback(context.TODO(), a.ID)
if err != nil {
success = false
}
}(rb)
}
wg.Wait()
if !success {
return false, fmt.Errorf("error in rollback")
}
return success, nil
}
func (a *Allocation) RepairRequired(remotepath string) (zboxutil.Uint128, zboxutil.Uint128, bool, *fileref.FileRef, error) {
if !a.isInitialized() {
return zboxutil.Uint128{}, zboxutil.Uint128{}, false, nil, notInitialized
}
listReq := &ListRequest{Consensus: Consensus{RWMutex: &sync.RWMutex{}}}
listReq.allocationID = a.ID
listReq.allocationTx = a.Tx
listReq.blobbers = a.Blobbers
listReq.fullconsensus = a.fullconsensus
listReq.consensusThresh = a.DataShards
listReq.ctx = a.ctx
listReq.remotefilepath = remotepath
found, deleteMask, fileRef, _ := listReq.getFileConsensusFromBlobbers()
if fileRef == nil {
var repairErr error
if deleteMask.Equals(zboxutil.NewUint128(0)) {
repairErr = errors.New("", "File not found for the given remotepath")
}
return found, deleteMask, false, fileRef, repairErr
}
uploadMask := zboxutil.NewUint128(1).Lsh(uint64(len(a.Blobbers))).Sub64(1)
return found, deleteMask, !found.Equals(uploadMask), fileRef, nil
}
func (a *Allocation) DoMultiOperation(operations []OperationRequest, opts ...MultiOperationOption) error {
if len(operations) == 0 {
return nil
}
if !a.isInitialized() {
return notInitialized
}
connectionID := zboxutil.NewConnectionId()
var mo MultiOperation
for i := 0; i < len(operations); {
// resetting multi operation and previous paths for every batch
mo.allocationObj = a
mo.operationMask = zboxutil.NewUint128(0)
mo.maskMU = &sync.Mutex{}
mo.connectionID = connectionID
mo.ctx, mo.ctxCncl = context.WithCancelCause(a.ctx)
mo.Consensus = Consensus{
RWMutex: &sync.RWMutex{},
consensusThresh: a.consensusThreshold,
fullconsensus: a.fullconsensus,
}
for _, opt := range opts {
opt(&mo)
}
previousPaths := make(map[string]bool)
connectionErrors := make([]error, len(mo.allocationObj.Blobbers))
var wg sync.WaitGroup
for blobberIdx := range mo.allocationObj.Blobbers {
wg.Add(1)
go func(pos int) {
defer wg.Done()
err := mo.createConnectionObj(pos)
if err != nil {
l.Logger.Error(err.Error())
connectionErrors[pos] = err
}
}(blobberIdx)
}
wg.Wait()
// Check consensus
if mo.operationMask.CountOnes() < mo.consensusThresh {
l.Logger.Error("Multioperation: create connection failed. Required consensus not met",
zap.Int("consensusThresh", mo.consensusThresh),
zap.Int("operationMask", mo.operationMask.CountOnes()),
zap.Any("connectionErrors", connectionErrors))
majorErr := zboxutil.MajorError(connectionErrors)
if majorErr != nil {
return errors.New("consensus_not_met",
fmt.Sprintf("Multioperation: create connection failed. Required consensus %d got %d. Major error: %s",
mo.consensusThresh, mo.operationMask.CountOnes(), majorErr.Error()))
}
return errors.New("consensus_not_met",
fmt.Sprintf("Multioperation: create connection failed. Required consensus %d got %d",
mo.consensusThresh, mo.operationMask.CountOnes()))
}
for ; i < len(operations); i++ {
if len(mo.operations) >= MultiOpBatchSize {
// max batch size reached, commit
connectionID = zboxutil.NewConnectionId()
break
}
op := operations[i]
op.RemotePath = strings.TrimSpace(op.RemotePath)
if op.FileMeta.RemotePath != "" {
op.FileMeta.RemotePath = strings.TrimSpace(op.FileMeta.RemotePath)
op.FileMeta.RemoteName = strings.TrimSpace(op.FileMeta.RemoteName)
}
remotePath := op.RemotePath
parentPaths := GenerateParentPaths(remotePath)
if _, ok := previousPaths[remotePath]; ok {
// conflict found, commit
connectionID = zboxutil.NewConnectionId()
break
}
var (
operation Operationer
err error
newConnectionID string
)
switch op.OperationType {
case constants.FileOperationRename:
operation = NewRenameOperation(op.RemotePath, op.DestName, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
case constants.FileOperationCopy:
operation = NewCopyOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
case constants.FileOperationMove:
operation = NewMoveOperation(op.RemotePath, op.DestPath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
case constants.FileOperationInsert:
cancelLock.Lock()
CancelOpCtx[op.FileMeta.RemotePath] = mo.ctxCncl
cancelLock.Unlock()
operation, newConnectionID, err = NewUploadOperation(mo.ctx, op.Workdir, mo.allocationObj, mo.connectionID, op.FileMeta, op.FileReader, false, op.IsWebstreaming, op.IsRepair, op.DownloadFile, op.StreamUpload, op.Opts...)
case constants.FileOperationDelete:
if op.Mask != nil {
operation = NewDeleteOperation(op.RemotePath, *op.Mask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
} else {
operation = NewDeleteOperation(op.RemotePath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
}
case constants.FileOperationUpdate:
cancelLock.Lock()
CancelOpCtx[op.FileMeta.RemotePath] = mo.ctxCncl
cancelLock.Unlock()
operation, newConnectionID, err = NewUploadOperation(mo.ctx, op.Workdir, mo.allocationObj, mo.connectionID, op.FileMeta, op.FileReader, true, op.IsWebstreaming, op.IsRepair, op.DownloadFile, op.StreamUpload, op.Opts...)
case constants.FileOperationCreateDir:
operation = NewDirOperation(op.RemotePath, mo.operationMask, mo.maskMU, mo.consensusThresh, mo.fullconsensus, mo.ctx)
default:
return errors.New("invalid_operation", "Operation is not valid")
}
if err != nil {
return err
}
if newConnectionID != "" && newConnectionID != connectionID {
connectionID = newConnectionID
break
}
err = operation.Verify(a)
if err != nil {
return err
}
for path := range parentPaths {
previousPaths[path] = true
}
mo.operations = append(mo.operations, operation)
}
if len(mo.operations) > 0 {
err := mo.Process()
if err != nil {
return err
}
mo.operations = nil
}
}
return nil
}
func GenerateParentPaths(path string) map[string]bool {
path = strings.Trim(path, "/")
parts := strings.Split(path, "/")
parentPaths := make(map[string]bool)
for i := range parts {
parentPaths["/"+strings.Join(parts[:i+1], "/")] = true
}
return parentPaths
}
func (a *Allocation) DownloadFileToFileHandler(
fileHandler sys.File,
remotePath string,
verifyDownload bool,
status StatusCallback,
isFinal bool,
downloadReqOpts ...DownloadRequestOption,
) error {
return a.addAndGenerateDownloadRequest(fileHandler, remotePath, DOWNLOAD_CONTENT_FULL, 1, 0,
numBlockDownloads, verifyDownload, status, isFinal, "", downloadReqOpts...)
}
func (a *Allocation) DownloadByBlocksToFileHandler(
fileHandler sys.File,
remotePath string,
startBlock, endBlock int64,