-
Notifications
You must be signed in to change notification settings - Fork 361
/
catalog.go
1371 lines (1263 loc) · 45 KB
/
catalog.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 catalog
import (
"bytes"
"context"
"crypto"
_ "crypto/sha256"
"errors"
"fmt"
"io"
"strings"
"github.com/cockroachdb/pebble"
"github.com/hashicorp/go-multierror"
"github.com/treeverse/lakefs/pkg/batch"
"github.com/treeverse/lakefs/pkg/block"
"github.com/treeverse/lakefs/pkg/block/factory"
"github.com/treeverse/lakefs/pkg/config"
"github.com/treeverse/lakefs/pkg/db"
"github.com/treeverse/lakefs/pkg/graveler"
"github.com/treeverse/lakefs/pkg/graveler/branch"
"github.com/treeverse/lakefs/pkg/graveler/committed"
"github.com/treeverse/lakefs/pkg/graveler/ref"
"github.com/treeverse/lakefs/pkg/graveler/retention"
"github.com/treeverse/lakefs/pkg/graveler/settings"
"github.com/treeverse/lakefs/pkg/graveler/sstable"
"github.com/treeverse/lakefs/pkg/graveler/staging"
"github.com/treeverse/lakefs/pkg/ident"
"github.com/treeverse/lakefs/pkg/ingest/store"
"github.com/treeverse/lakefs/pkg/kv"
"github.com/treeverse/lakefs/pkg/logging"
"github.com/treeverse/lakefs/pkg/pyramid"
"github.com/treeverse/lakefs/pkg/pyramid/params"
"github.com/treeverse/lakefs/pkg/validator"
"google.golang.org/protobuf/types/known/timestamppb"
)
// hashAlg is the hashing algorithm to use to generate graveler identifiers. Changing it
// causes all old identifiers to change, so while existing installations will continue to
// function they will be unable to re-use any existing objects.
const hashAlg = crypto.SHA256
const NumberOfParentsOfNonMergeCommit = 1
type Path string
type EntryRecord struct {
Path Path
*Entry
}
type EntryListing struct {
CommonPrefix bool
Path
*Entry
}
type EntryDiff struct {
Type graveler.DiffType
Path Path
Entry *Entry
}
type EntryIterator interface {
Next() bool
SeekGE(id Path)
Value() *EntryRecord
Err() error
Close()
}
type EntryListingIterator interface {
Next() bool
SeekGE(id Path)
Value() *EntryListing
Err() error
Close()
}
type EntryDiffIterator interface {
Next() bool
SeekGE(id Path)
Value() *EntryDiff
Err() error
Close()
}
func (id Path) String() string {
return string(id)
}
type Store interface {
graveler.KeyValueStore
graveler.VersionController
graveler.Dumper
graveler.Loader
graveler.Plumbing
}
const (
RangeFSName = "range"
MetaRangeFSName = "meta-range"
)
type Config struct {
Config *config.Config
DB db.Database
LockDB db.Database
KVStore *kv.StoreMessage
WalkerFactory WalkerFactory
}
type Catalog struct {
BlockAdapter block.Adapter
Store Store
log logging.Logger
walkerFactory WalkerFactory
managers []io.Closer
}
const (
ListRepositoriesLimitMax = 1000
ListBranchesLimitMax = 1000
ListTagsLimitMax = 1000
DiffLimitMax = 1000
ListEntriesLimitMax = 10000
)
var ErrUnknownDiffType = errors.New("unknown graveler difference type")
type ctxCloser struct {
close context.CancelFunc
}
func (c *ctxCloser) Close() error {
go c.close()
return nil
}
func New(ctx context.Context, cfg Config) (*Catalog, error) {
if cfg.LockDB == nil {
cfg.LockDB = cfg.DB
}
ctx, cancelFn := context.WithCancel(ctx)
adapter, err := factory.BuildBlockAdapter(ctx, nil, cfg.Config)
if err != nil {
cancelFn()
return nil, fmt.Errorf("build block adapter: %w", err)
}
if cfg.WalkerFactory == nil {
cfg.WalkerFactory = store.NewFactory(cfg.Config)
}
tierFSParams, err := cfg.Config.GetCommittedTierFSParams(adapter)
if err != nil {
cancelFn()
return nil, fmt.Errorf("configure tiered FS for committed: %w", err)
}
metaRangeFS, err := pyramid.NewFS(¶ms.InstanceParams{
SharedParams: tierFSParams.SharedParams,
FSName: MetaRangeFSName,
DiskAllocProportion: tierFSParams.MetaRangeAllocationProportion,
})
if err != nil {
cancelFn()
return nil, fmt.Errorf("create tiered FS for committed metaranges: %w", err)
}
rangeFS, err := pyramid.NewFS(¶ms.InstanceParams{
SharedParams: tierFSParams.SharedParams,
FSName: RangeFSName,
DiskAllocProportion: tierFSParams.RangeAllocationProportion,
})
if err != nil {
cancelFn()
return nil, fmt.Errorf("create tiered FS for committed ranges: %w", err)
}
pebbleSSTableCache := pebble.NewCache(tierFSParams.PebbleSSTableCacheSizeBytes)
defer pebbleSSTableCache.Unref()
sstableManager := sstable.NewPebbleSSTableRangeManager(pebbleSSTableCache, rangeFS, hashAlg)
sstableMetaManager := sstable.NewPebbleSSTableRangeManager(pebbleSSTableCache, metaRangeFS, hashAlg)
committedParams := *cfg.Config.GetCommittedParams()
sstableMetaRangeManager, err := committed.NewMetaRangeManager(
committedParams,
// TODO(ariels): Use separate range managers for metaranges and ranges
sstableMetaManager,
sstableManager,
)
if err != nil {
cancelFn()
return nil, fmt.Errorf("create SSTable-based metarange manager: %w", err)
}
committedManager := committed.NewCommittedManager(sstableMetaRangeManager, sstableManager, committedParams)
executor := batch.NewExecutor(logging.Default())
go executor.Run(ctx)
var gStore Store
var stagingManager graveler.StagingManager
refManager := ref.NewPGRefManager(executor, cfg.DB, ident.NewHexAddressProvider())
branchLocker := ref.NewBranchLocker(cfg.LockDB) // TODO (niro): Will not be needed in KV implementation
gcManager := retention.NewGarbageCollectionManager(cfg.DB, tierFSParams.Adapter, refManager, cfg.Config.GetCommittedBlockStoragePrefix())
stagingManager = staging.NewDBManager(cfg.DB)
settingManager := settings.NewManager(refManager, branchLocker, adapter, cfg.Config.GetCommittedBlockStoragePrefix())
protectedBranchesManager := branch.NewProtectionManager(settingManager)
if cfg.Config.GetDatabaseParams().KVEnabled { // TODO (niro): Each module should be replaced by an appropriate KV implementation
stagingManager = staging.NewManager(*cfg.KVStore)
gStore = graveler.NewKVGraveler(branchLocker, committedManager, stagingManager, refManager, gcManager, protectedBranchesManager)
} else {
gStore = graveler.NewDBGraveler(branchLocker, committedManager, stagingManager, refManager, gcManager, protectedBranchesManager)
}
return &Catalog{
BlockAdapter: tierFSParams.Adapter,
Store: gStore,
log: logging.Default().WithField("service_name", "entry_catalog"),
walkerFactory: cfg.WalkerFactory,
managers: []io.Closer{sstableManager, sstableMetaManager, &ctxCloser{cancelFn}},
}, nil
}
func (c *Catalog) SetHooksHandler(hooks graveler.HooksHandler) {
c.Store.SetHooksHandler(hooks)
}
// CreateRepository create a new repository pointing to 'storageNamespace' (ex: s3://bucket1/repo) with default branch name 'branch'
func (c *Catalog) CreateRepository(ctx context.Context, repository string, storageNamespace string, branch string) (*Repository, error) {
repositoryID := graveler.RepositoryID(repository)
storageNS := graveler.StorageNamespace(storageNamespace)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "name", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "storageNamespace", Value: storageNS, Fn: graveler.ValidateStorageNamespace},
}); err != nil {
return nil, err
}
repo, err := c.Store.CreateRepository(ctx, repositoryID, storageNS, branchID)
if err != nil {
return nil, err
}
catalogRepo := &Repository{
Name: repositoryID.String(),
StorageNamespace: storageNS.String(),
DefaultBranch: branchID.String(),
CreationDate: repo.CreationDate,
}
return catalogRepo, nil
}
// CreateBareRepository creates a new repository pointing to 'storageNamespace' (ex: s3://bucket1/repo) with no initial branch or commit
func (c *Catalog) CreateBareRepository(ctx context.Context, repository string, storageNamespace string, defaultBranchID string) (*Repository, error) {
repositoryID := graveler.RepositoryID(repository)
storageNS := graveler.StorageNamespace(storageNamespace)
branchID := graveler.BranchID(defaultBranchID)
if err := validator.Validate([]validator.ValidateArg{
{Name: "name", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "storageNamespace", Value: storageNS, Fn: graveler.ValidateStorageNamespace},
}); err != nil {
return nil, err
}
repo, err := c.Store.CreateBareRepository(ctx, repositoryID, storageNS, branchID)
if err != nil {
return nil, err
}
catalogRepo := &Repository{
Name: repositoryID.String(),
StorageNamespace: storageNS.String(),
DefaultBranch: branchID.String(),
CreationDate: repo.CreationDate,
}
return catalogRepo, nil
}
// GetRepository get repository information
func (c *Catalog) GetRepository(ctx context.Context, repository string) (*Repository, error) {
repositoryID := graveler.RepositoryID(repository)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
}); err != nil {
return nil, err
}
repo, err := c.Store.GetRepository(ctx, repositoryID)
if err != nil {
return nil, err
}
catalogRepository := &Repository{
Name: repositoryID.String(),
StorageNamespace: repo.StorageNamespace.String(),
DefaultBranch: repo.DefaultBranchID.String(),
CreationDate: repo.CreationDate,
}
return catalogRepository, nil
}
// DeleteRepository delete a repository
func (c *Catalog) DeleteRepository(ctx context.Context, repository string) error {
repositoryID := graveler.RepositoryID(repository)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
}); err != nil {
return err
}
return c.Store.DeleteRepository(ctx, repositoryID)
}
// ListRepositories list repositories information, the bool returned is true when more repositories can be listed.
// In this case pass the last repository name as 'after' on the next call to ListRepositories
func (c *Catalog) ListRepositories(ctx context.Context, limit int, prefix, after string) ([]*Repository, bool, error) {
// normalize limit
if limit < 0 || limit > ListRepositoriesLimitMax {
limit = ListRepositoriesLimitMax
}
// get list repositories iterator
it, err := c.Store.ListRepositories(ctx)
if err != nil {
return nil, false, fmt.Errorf("get iterator: %w", err)
}
defer it.Close()
// seek for first item
afterRepositoryID := graveler.RepositoryID(after)
prefixRepositoryID := graveler.RepositoryID(prefix)
startPos := prefixRepositoryID
if afterRepositoryID > startPos {
startPos = afterRepositoryID
}
if startPos != "" {
it.SeekGE(startPos)
}
var repos []*Repository
for it.Next() {
record := it.Value()
if !strings.HasPrefix(string(record.RepositoryID), prefix) {
break
}
if record.RepositoryID == afterRepositoryID {
continue
}
repos = append(repos, &Repository{
Name: record.RepositoryID.String(),
StorageNamespace: record.StorageNamespace.String(),
DefaultBranch: record.DefaultBranchID.String(),
CreationDate: record.CreationDate,
})
// collect limit +1 to return limit and has more
if len(repos) >= limit+1 {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
// trim result if needed and return has more
hasMore := false
if len(repos) > limit {
hasMore = true
repos = repos[:limit]
}
return repos, hasMore, nil
}
func (c *Catalog) GetStagingToken(ctx context.Context, repository string, branch string) (*string, error) {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return nil, err
}
token, err := c.Store.GetStagingToken(ctx, repositoryID, branchID)
if err != nil {
return nil, err
}
tokenString := ""
if token != nil {
tokenString = string(*token)
}
return &tokenString, nil
}
func (c *Catalog) CreateBranch(ctx context.Context, repository string, branch string, sourceBranch string) (*CommitLog, error) {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
sourceRef := graveler.Ref(sourceBranch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
{Name: "ref", Value: sourceRef, Fn: graveler.ValidateRef},
}); err != nil {
if errors.Is(err, graveler.ErrInvalidBranchID) {
return nil, fmt.Errorf("%w: branch id must consist of letters, digits, underscores and dashes, and cannot start with a dash", err)
}
return nil, err
}
newBranch, err := c.Store.CreateBranch(ctx, repositoryID, branchID, sourceRef)
if err != nil {
return nil, err
}
commit, err := c.Store.GetCommit(ctx, repositoryID, newBranch.CommitID)
if err != nil {
return nil, err
}
catalogCommitLog := &CommitLog{
Reference: newBranch.CommitID.String(),
Committer: commit.Committer,
Message: commit.Message,
Metadata: Metadata(commit.Metadata),
}
for _, parent := range commit.Parents {
catalogCommitLog.Parents = append(catalogCommitLog.Parents, string(parent))
}
return catalogCommitLog, nil
}
func (c *Catalog) DeleteBranch(ctx context.Context, repository string, branch string) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "name", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return err
}
return c.Store.DeleteBranch(ctx, repositoryID, branchID)
}
func (c *Catalog) ListBranches(ctx context.Context, repository string, prefix string, limit int, after string) ([]*Branch, bool, error) {
repositoryID := graveler.RepositoryID(repository)
afterBranch := graveler.BranchID(after)
prefixBranch := graveler.BranchID(prefix)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
}); err != nil {
return nil, false, err
}
// normalize limit
if limit < 0 || limit > ListBranchesLimitMax {
limit = ListBranchesLimitMax
}
it, err := c.Store.ListBranches(ctx, repositoryID)
if err != nil {
return nil, false, err
}
defer it.Close()
if afterBranch < prefixBranch {
it.SeekGE(prefixBranch)
} else {
it.SeekGE(afterBranch)
}
var branches []*Branch
for it.Next() {
v := it.Value()
if v.BranchID == afterBranch {
continue
}
branchID := v.BranchID.String()
// break in case we got to a branch outside our prefix
if !strings.HasPrefix(branchID, prefix) {
break
}
b := &Branch{
Name: v.BranchID.String(),
Reference: v.CommitID.String(),
}
branches = append(branches, b)
if len(branches) >= limit+1 {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
// return results (optional trimmed) and hasMore
hasMore := false
if len(branches) > limit {
hasMore = true
branches = branches[:limit]
}
return branches, hasMore, nil
}
func (c *Catalog) BranchExists(ctx context.Context, repository string, branch string) (bool, error) {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "name", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return false, err
}
_, err := c.Store.GetBranch(ctx, repositoryID, branchID)
if errors.Is(err, graveler.ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
return true, nil
}
func (c *Catalog) GetBranchReference(ctx context.Context, repository string, branch string) (string, error) {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return "", err
}
b, err := c.Store.GetBranch(ctx, repositoryID, branchID)
if err != nil {
return "", err
}
return string(b.CommitID), nil
}
func (c *Catalog) ResetBranch(ctx context.Context, repository string, branch string) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return err
}
return c.Store.Reset(ctx, repositoryID, branchID)
}
func (c *Catalog) CreateTag(ctx context.Context, repository string, tagID string, ref string) (string, error) {
repositoryID := graveler.RepositoryID(repository)
tag := graveler.TagID(tagID)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "tagID", Value: tag, Fn: graveler.ValidateTagID},
}); err != nil {
return "", err
}
commitID, err := c.dereferenceCommitID(ctx, repositoryID, graveler.Ref(ref))
if err != nil {
return "", err
}
err = c.Store.CreateTag(ctx, repositoryID, tag, commitID)
if err != nil {
return "", err
}
return commitID.String(), nil
}
func (c *Catalog) DeleteTag(ctx context.Context, repository string, tagID string) error {
repositoryID := graveler.RepositoryID(repository)
tag := graveler.TagID(tagID)
if err := validator.Validate([]validator.ValidateArg{
{Name: "name", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "tagID", Value: tag, Fn: graveler.ValidateTagID},
}); err != nil {
return err
}
return c.Store.DeleteTag(ctx, repositoryID, tag)
}
func (c *Catalog) ListTags(ctx context.Context, repository string, prefix string, limit int, after string) ([]*Tag, bool, error) {
if limit < 0 || limit > ListTagsLimitMax {
limit = ListTagsLimitMax
}
repositoryID := graveler.RepositoryID(repository)
if err := validator.Validate([]validator.ValidateArg{
{Name: "name", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
}); err != nil {
return nil, false, err
}
it, err := c.Store.ListTags(ctx, repositoryID)
if err != nil {
return nil, false, err
}
defer it.Close()
afterTagID := graveler.TagID(after)
prefixTagID := graveler.TagID(prefix)
if afterTagID < prefixTagID {
it.SeekGE(prefixTagID)
} else {
it.SeekGE(afterTagID)
}
var tags []*Tag
for it.Next() {
v := it.Value()
if v.TagID == afterTagID {
continue
}
if !strings.HasPrefix(v.TagID.String(), prefix) {
break
}
tag := &Tag{
ID: string(v.TagID),
CommitID: v.CommitID.String(),
}
tags = append(tags, tag)
if len(tags) >= limit+1 {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
// return results (optional trimmed) and hasMore
hasMore := false
if len(tags) > limit {
hasMore = true
tags = tags[:limit]
}
return tags, hasMore, nil
}
func (c *Catalog) GetTag(ctx context.Context, repository string, tagID string) (string, error) {
repositoryID := graveler.RepositoryID(repository)
tag := graveler.TagID(tagID)
if err := validator.Validate([]validator.ValidateArg{
{Name: "name", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "tagID", Value: tag, Fn: graveler.ValidateTagID},
}); err != nil {
return "", err
}
commit, err := c.Store.GetTag(ctx, repositoryID, tag)
if err != nil {
return "", err
}
return commit.String(), nil
}
// GetEntry returns the current entry for path in repository branch reference. Returns
// the entry with ExpiredError if it has expired from underlying storage.
func (c *Catalog) GetEntry(ctx context.Context, repository string, reference string, path string, _ GetEntryParams) (*DBEntry, error) {
repositoryID := graveler.RepositoryID(repository)
refToGet := graveler.Ref(reference)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "ref", Value: refToGet, Fn: graveler.ValidateRef},
{Name: "path", Value: Path(path), Fn: ValidatePath},
}); err != nil {
return nil, err
}
val, err := c.Store.Get(ctx, repositoryID, refToGet, graveler.Key(path))
if err != nil {
return nil, err
}
ent, err := ValueToEntry(val)
if err != nil {
return nil, err
}
catalogEntry := newCatalogEntryFromEntry(false, path, ent)
return &catalogEntry, nil
}
func newEntryFromCatalogEntry(entry DBEntry) *Entry {
ent := &Entry{
Address: entry.PhysicalAddress,
AddressType: addressTypeToProto(entry.AddressType),
Metadata: entry.Metadata,
LastModified: timestamppb.New(entry.CreationDate),
ETag: entry.Checksum,
Size: entry.Size,
ContentType: ContentTypeOrDefault(entry.ContentType),
}
return ent
}
func addressTypeToProto(t AddressType) Entry_AddressType {
switch t {
case AddressTypeByPrefixDeprecated:
return Entry_BY_PREFIX_DEPRECATED
case AddressTypeRelative:
return Entry_RELATIVE
case AddressTypeFull:
return Entry_FULL
default:
panic(fmt.Sprintf("unknown address type: %d", t))
}
}
func addressTypeToCatalog(t Entry_AddressType) AddressType {
switch t {
case Entry_BY_PREFIX_DEPRECATED:
return AddressTypeByPrefixDeprecated
case Entry_RELATIVE:
return AddressTypeRelative
case Entry_FULL:
return AddressTypeFull
default:
panic(fmt.Sprintf("unknown address type: %d", t))
}
}
func (c *Catalog) CreateEntry(ctx context.Context, repository string, branch string, entry DBEntry, writeConditions ...graveler.WriteConditionOption) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
ent := newEntryFromCatalogEntry(entry)
path := Path(entry.Path)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
{Name: "path", Value: path, Fn: ValidatePath},
}); err != nil {
return err
}
key := graveler.Key(path)
value, err := EntryToValue(ent)
if err != nil {
return err
}
return c.Store.Set(ctx, repositoryID, branchID, key, *value, writeConditions...)
}
func (c *Catalog) DeleteEntry(ctx context.Context, repository string, branch string, path string) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
p := Path(path)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
{Name: "path", Value: p, Fn: ValidatePath},
}); err != nil {
return err
}
key := graveler.Key(p)
return c.Store.Delete(ctx, repositoryID, branchID, key)
}
func (c *Catalog) ListEntries(ctx context.Context, repository string, reference string, prefix string, after string, delimiter string, limit int) ([]*DBEntry, bool, error) {
// normalize limit
if limit < 0 || limit > ListEntriesLimitMax {
limit = ListEntriesLimitMax
}
prefixPath := Path(prefix)
afterPath := Path(after)
delimiterPath := Path(delimiter)
repositoryID := graveler.RepositoryID(repository)
refToList := graveler.Ref(reference)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "ref", Value: refToList, Fn: graveler.ValidateRef},
{Name: "prefix", Value: prefixPath, Fn: ValidatePathOptional},
{Name: "delimiter", Value: delimiterPath, Fn: ValidatePathOptional},
}); err != nil {
return nil, false, err
}
iter, err := c.Store.List(ctx, repositoryID, refToList)
if err != nil {
return nil, false, err
}
it := NewEntryListingIterator(NewValueToEntryIterator(iter), prefixPath, delimiterPath)
defer it.Close()
it.SeekGE(afterPath)
var entries []*DBEntry
for it.Next() {
v := it.Value()
if v.Path == afterPath {
continue
}
entry := newCatalogEntryFromEntry(v.CommonPrefix, v.Path.String(), v.Entry)
entries = append(entries, &entry)
if len(entries) >= limit+1 {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
// trim result if needed and return has more
hasMore := false
if len(entries) > limit {
hasMore = true
entries = entries[:limit]
}
return entries, hasMore, nil
}
func (c *Catalog) ResetEntry(ctx context.Context, repository string, branch string, path string) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
entryPath := Path(path)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
{Name: "path", Value: entryPath, Fn: ValidatePath},
}); err != nil {
return err
}
key := graveler.Key(entryPath)
return c.Store.ResetKey(ctx, repositoryID, branchID, key)
}
func (c *Catalog) ResetEntries(ctx context.Context, repository string, branch string, prefix string) error {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
prefixPath := Path(prefix)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return err
}
keyPrefix := graveler.Key(prefixPath)
return c.Store.ResetPrefix(ctx, repositoryID, branchID, keyPrefix)
}
func (c *Catalog) Commit(ctx context.Context, repository, branch, message, committer string, metadata Metadata, date *int64, sourceMetarange *string) (*CommitLog, error) {
repositoryID := graveler.RepositoryID(repository)
branchID := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchID, Fn: graveler.ValidateBranchID},
}); err != nil {
return nil, err
}
p := graveler.CommitParams{
Committer: committer,
Message: message,
Date: date,
Metadata: map[string]string(metadata),
}
if sourceMetarange != nil {
x := graveler.MetaRangeID(*sourceMetarange)
p.SourceMetaRange = &x
}
commitID, err := c.Store.Commit(ctx, repositoryID, branchID, p)
if err != nil {
return nil, err
}
catalogCommitLog := &CommitLog{
Reference: commitID.String(),
Committer: committer,
Message: message,
Metadata: metadata,
}
// in order to return commit log we need the commit creation time and parents
commit, err := c.Store.GetCommit(ctx, repositoryID, commitID)
if err != nil {
return catalogCommitLog, graveler.ErrCommitNotFound
}
for _, parent := range commit.Parents {
catalogCommitLog.Parents = append(catalogCommitLog.Parents, parent.String())
}
catalogCommitLog.CreationDate = commit.CreationDate.UTC()
return catalogCommitLog, nil
}
func (c *Catalog) GetCommit(ctx context.Context, repository string, reference string) (*CommitLog, error) {
repositoryID := graveler.RepositoryID(repository)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
}); err != nil {
return nil, err
}
commitID, err := c.dereferenceCommitID(ctx, repositoryID, graveler.Ref(reference))
if err != nil {
return nil, err
}
commit, err := c.Store.GetCommit(ctx, repositoryID, commitID)
if err != nil {
return nil, err
}
catalogCommitLog := &CommitLog{
Reference: reference,
Committer: commit.Committer,
Message: commit.Message,
CreationDate: commit.CreationDate,
MetaRangeID: string(commit.MetaRangeID),
Metadata: Metadata(commit.Metadata),
}
for _, parent := range commit.Parents {
catalogCommitLog.Parents = append(catalogCommitLog.Parents, string(parent))
}
return catalogCommitLog, nil
}
func (c *Catalog) ListCommits(ctx context.Context, repository string, branch string, params LogParams) ([]*CommitLog, bool, error) {
repositoryID := graveler.RepositoryID(repository)
branchRef := graveler.BranchID(branch)
if err := validator.Validate([]validator.ValidateArg{
{Name: "repository", Value: repositoryID, Fn: graveler.ValidateRepositoryID},
{Name: "branch", Value: branchRef, Fn: graveler.ValidateBranchID},
}); err != nil {
return nil, false, err
}
commitID, err := c.dereferenceCommitID(ctx, repositoryID, graveler.Ref(branchRef))
if err != nil {
return nil, false, fmt.Errorf("branch ref: %w", err)
}
it, err := c.Store.Log(ctx, repositoryID, commitID)
if err != nil {
return nil, false, err
}
defer it.Close()
// skip until 'fromReference' if needed
if params.FromReference != "" {
fromCommitID, err := c.dereferenceCommitID(ctx, repositoryID, graveler.Ref(params.FromReference))
if err != nil {
return nil, false, fmt.Errorf("from ref: %w", err)
}
for it.Next() {
if it.Value().CommitID == fromCommitID {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
}
// collect commits
var commits []*CommitLog
for it.Next() {
v := it.Value()
commit := &CommitLog{
Reference: v.CommitID.String(),
Committer: v.Committer,
Message: v.Message,
CreationDate: v.CreationDate,
Metadata: map[string]string(v.Metadata),
MetaRangeID: string(v.MetaRangeID),
Parents: make([]string, 0, len(v.Parents)),
}
for _, parent := range v.Parents {
commit.Parents = append(commit.Parents, parent.String())
}
if len(params.PathList) != 0 && len(v.Parents) == NumberOfParentsOfNonMergeCommit {
// if path list isn't empty, and also the current commit isn't a merge commit -
// we check if the current commit contains changes to the paths
pathInCommit, err := c.pathInCommit(ctx, repositoryID, v, params)
if err != nil {
return nil, false, err
}
if pathInCommit {
commits = append(commits, commit)
}
} else if len(params.PathList) == 0 {
// if there is no specification of path - we will output all commits
commits = append(commits, commit)
}
if len(commits) >= params.Limit+1 {
break
}
}
if err := it.Err(); err != nil {
return nil, false, err
}
hasMore := false
if len(commits) > params.Limit {
hasMore = true
commits = commits[:params.Limit]
}
return commits, hasMore, nil
}
func (c *Catalog) pathInCommit(ctx context.Context, repositoryID graveler.RepositoryID, commit *graveler.CommitRecord, params LogParams) (bool, error) {
// this function checks whether the given commmit contains changes to a list of paths.
// it searches the path in the diff between the commit and it's parent, but do so only to commits
// that have single parent (not merge commits)
left := graveler.Ref(commit.Parents[0])
right := graveler.Ref(commit.CommitID)
diffIter, err := c.Store.Diff(ctx, repositoryID, left, right)
if err != nil {
return false, err
}
defer diffIter.Close()
for _, path := range params.PathList {
key := graveler.Key(path.Path)
diffIter.SeekGE(key)
if diffIter.Next() {
diffKey := diffIter.Value().Key
var result bool
if path.IsPrefix {
result = bytes.HasPrefix(diffKey, key)
} else {
result = bytes.Equal(diffKey, key)
}
if result {
return true, nil
}
}
if err := diffIter.Err(); err != nil {
return false, err
}
}
return false, nil
}