forked from pachyderm/pachyderm
/
driver.go
2053 lines (1869 loc) · 56.2 KB
/
driver.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 server
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/sync/errgroup"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/auth"
"github.com/pachyderm/pachyderm/src/client/pfs"
"github.com/pachyderm/pachyderm/src/client/pkg/grpcutil"
"github.com/pachyderm/pachyderm/src/client/pkg/uuid"
pfsserver "github.com/pachyderm/pachyderm/src/server/pfs"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/hashtree"
"github.com/pachyderm/pachyderm/src/server/pkg/pfsdb"
"github.com/pachyderm/pachyderm/src/server/pkg/watch"
etcd "github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/types"
"github.com/hashicorp/golang-lru"
"google.golang.org/grpc"
)
const (
splitSuffixBase = 16
splitSuffixWidth = 64
splitSuffixFmt = "%016x"
// Makes calls to ListRepo and InspectRepo more legible
includeAuth = true
)
// ValidateRepoName determines if a repo name is valid
func ValidateRepoName(name string) error {
match, _ := regexp.MatchString("^[a-zA-Z0-9_-]+$", name)
if !match {
return fmt.Errorf("repo name (%v) invalid: only alphanumeric characters, underscores, and dashes are allowed", name)
}
return nil
}
// IsPermissionError returns true if a given error is a permission error.
func IsPermissionError(err error) bool {
return strings.Contains(err.Error(), "has already finished")
}
// CommitEvent is an event that contains a CommitInfo or an error
type CommitEvent struct {
Err error
Value *pfs.CommitInfo
}
// CommitStream is a stream of CommitInfos
type CommitStream interface {
Stream() <-chan CommitEvent
Close()
}
type collectionFactory func(string) col.Collection
type driver struct {
// address, and pachConn are used to connect back to Pachd's Object Store API
// and Authorization API
address string
pachConnOnce sync.Once
onceErr error
pachConn *grpc.ClientConn
// pachClient is a cached Pachd client, that connects to Pachyderm's object
// store API and auth API
pachClient *client.APIClient
// etcdClient and prefix write repo and other metadata to etcd
etcdClient *etcd.Client
prefix string
// collections
repos col.Collection
repoRefCounts col.Collection
commits collectionFactory
branches collectionFactory
openCommits col.Collection
// a cache for hashtrees
treeCache *lru.Cache
}
const (
tombstone = "delete"
)
const (
defaultTreeCacheSize = 128
)
// newDriver is used to create a new Driver instance
func newDriver(address string, etcdAddresses []string, etcdPrefix string, treeCacheSize int64) (*driver, error) {
etcdClient, err := etcd.New(etcd.Config{
Endpoints: etcdAddresses,
DialOptions: client.EtcdDialOptions(),
})
if err != nil {
return nil, fmt.Errorf("could not connect to etcd: %v", err)
}
if treeCacheSize <= 0 {
treeCacheSize = defaultTreeCacheSize
}
treeCache, err := lru.New(int(treeCacheSize))
if err != nil {
return nil, fmt.Errorf("could not initialize treeCache: %v", err)
}
d := &driver{
address: address,
etcdClient: etcdClient,
prefix: etcdPrefix,
repos: pfsdb.Repos(etcdClient, etcdPrefix),
repoRefCounts: pfsdb.RepoRefCounts(etcdClient, etcdPrefix),
commits: func(repo string) col.Collection {
return pfsdb.Commits(etcdClient, etcdPrefix, repo)
},
branches: func(repo string) col.Collection {
return pfsdb.Branches(etcdClient, etcdPrefix, repo)
},
openCommits: pfsdb.OpenCommits(etcdClient, etcdPrefix),
treeCache: treeCache,
}
go func() { d.initializePachConn() }() // Begin dialing connection on startup
return d, nil
}
// newLocalDriver creates a driver using an local etcd instance. This
// function is intended for testing purposes
func newLocalDriver(blockAddress string, etcdPrefix string) (*driver, error) {
return newDriver(blockAddress, []string{"localhost:32379"}, etcdPrefix, defaultTreeCacheSize)
}
// initializePachConn initializes the connects that the pfs driver has with the
// Pachyderm object API and auth API, and blocks until the connection is
// established
//
// TODO(msteffen): client initialization (both etcd and pachd) might be better
// placed happen in server.go, near main(), so that we only pay the dial cost
// once, and so that pps doesn't need to have its own initialization code
func (d *driver) initializePachConn() error {
d.pachConnOnce.Do(func() {
d.pachConn, d.onceErr = grpc.Dial(d.address, client.PachDialOptions()...)
d.pachClient = &client.APIClient{
AuthAPIClient: auth.NewAPIClient(d.pachConn),
ObjectAPIClient: pfs.NewObjectAPIClient(d.pachConn),
}
})
return d.onceErr
}
// checkIsAuthorized returns an error if the current user (in 'ctx') has
// authorization scope 's' for repo 'r'
func (d *driver) checkIsAuthorized(ctx context.Context, r *pfs.Repo, s auth.Scope) error {
d.initializePachConn()
resp, err := d.pachClient.AuthAPIClient.Authorize(auth.In2Out(ctx), &auth.AuthorizeRequest{
Repo: r.Name,
Scope: s,
})
if err == nil && !resp.Authorized {
return &auth.NotAuthorizedError{Repo: r.Name, Required: s}
} else if err != nil && !auth.IsNotActivatedError(err) {
return fmt.Errorf("error during authorization check for operation on \"%s\": %v",
r.Name, grpcutil.ScrubGRPC(err))
}
return nil
}
func now() *types.Timestamp {
t, err := types.TimestampProto(time.Now())
if err != nil {
panic(err)
}
return t
}
func present(key string) etcd.Cmp {
return etcd.Compare(etcd.CreateRevision(key), ">", 0)
}
func absent(key string) etcd.Cmp {
return etcd.Compare(etcd.CreateRevision(key), "=", 0)
}
func (d *driver) createRepo(ctx context.Context, repo *pfs.Repo, provenance []*pfs.Repo, description string, update bool) error {
if err := ValidateRepoName(repo.Name); err != nil {
return err
}
d.initializePachConn()
if update {
return d.updateRepo(ctx, repo, provenance, description)
}
_, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
repos := d.repos.ReadWrite(stm)
repoRefCounts := d.repoRefCounts.ReadWriteInt(stm)
// check if 'repo' already exists. If so, return that error. Otherwise,
// proceed with ACL creation (avoids awkward "access denied" error when
// calling "createRepo" on a repo that already exists)
var existingRepoInfo pfs.RepoInfo
err := repos.Get(repo.Name, &existingRepoInfo)
if err != nil && !col.IsErrNotFound(err) {
return fmt.Errorf("error checking whether \"%s\" exists: %v",
repo.Name, err)
} else if err == nil {
return fmt.Errorf("cannot create \"%s\" as it already exists", repo.Name)
}
// Create ACL for new repo
whoAmI, err := d.pachClient.AuthAPIClient.WhoAmI(auth.In2Out(ctx),
&auth.WhoAmIRequest{})
if err != nil && !auth.IsNotActivatedError(err) {
return fmt.Errorf("error while creating repo \"%s\": %v",
repo.Name, grpcutil.ScrubGRPC(err))
} else if err == nil {
// auth is active, and user is logged in. Make user an owner of the new
// repo (and clear any existing ACL under this name that might have been
// created by accident)
_, err := d.pachClient.AuthAPIClient.SetACL(auth.In2Out(ctx), &auth.SetACLRequest{
Repo: repo.Name,
Entries: []*auth.ACLEntry{{
Username: whoAmI.Username,
Scope: auth.Scope_OWNER,
}},
})
if err != nil {
return fmt.Errorf("could not create ACL for new repo \"%s\": %v",
repo.Name, grpcutil.ScrubGRPC(err))
}
}
// compute the full provenance of this repo
fullProv := make(map[string]bool)
for _, prov := range provenance {
fullProv[prov.Name] = true
provRepo := new(pfs.RepoInfo)
if err := repos.Get(prov.Name, provRepo); err != nil {
return err
}
// the provenance of my provenance is my provenance
for _, prov := range provRepo.Provenance {
fullProv[prov.Name] = true
}
}
var fullProvRepos []*pfs.Repo
for prov := range fullProv {
fullProvRepos = append(fullProvRepos, &pfs.Repo{prov})
if err := repoRefCounts.Increment(prov); err != nil {
return err
}
}
if err := repoRefCounts.Create(repo.Name, 0); err != nil {
return err
}
repoInfo := &pfs.RepoInfo{
Repo: repo,
Created: now(),
Provenance: fullProvRepos,
Description: description,
}
return repos.Create(repo.Name, repoInfo)
})
return err
}
func (d *driver) updateRepo(ctx context.Context, repo *pfs.Repo, provenance []*pfs.Repo, description string) error {
_, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
repos := d.repos.ReadWrite(stm)
repoRefCounts := d.repoRefCounts.ReadWriteInt(stm)
repoInfo := new(pfs.RepoInfo)
if err := repos.Get(repo.Name, repoInfo); err != nil {
return fmt.Errorf("error updating repo: %v", err)
}
// Caller only neads to be a WRITER to call UpdatePipeline(), so caller only
// needs to be a WRITER to update the provenance.
if err := d.checkIsAuthorized(ctx, repo, auth.Scope_WRITER); err != nil {
return err
}
provToAdd := make(map[string]bool)
provToRemove := make(map[string]bool)
for _, newProv := range provenance {
provToAdd[newProv.Name] = true
}
for _, oldProv := range repoInfo.Provenance {
delete(provToAdd, oldProv.Name)
provToRemove[oldProv.Name] = true
}
for _, newProv := range provenance {
delete(provToRemove, newProv.Name)
}
// For each new provenance repo, we increase its ref count
// by N where N is this repo's ref count.
// For each old provenance repo we do the opposite.
myRefCount, err := repoRefCounts.Get(repo.Name)
if err != nil {
return err
}
// +1 because we need to include ourselves.
myRefCount++
for newProv := range provToAdd {
if err := repoRefCounts.IncrementBy(newProv, myRefCount); err != nil {
return err
}
}
for oldProv := range provToRemove {
if err := repoRefCounts.DecrementBy(oldProv, myRefCount); err != nil {
return err
}
}
// We also add the new provenance repos to the provenance
// of all downstream repos, and remove the old provenance
// repos from their provenance.
downstreamRepos, err := d.listRepo(ctx, []*pfs.Repo{repo}, !includeAuth)
if err != nil {
return err
}
for _, repoInfo := range downstreamRepos.RepoInfo {
nextNewProv:
for newProv := range provToAdd {
for _, prov := range repoInfo.Provenance {
if newProv == prov.Name {
continue nextNewProv
}
}
repoInfo.Provenance = append(repoInfo.Provenance, &pfs.Repo{newProv})
}
nextOldProv:
for oldProv := range provToRemove {
for i, prov := range repoInfo.Provenance {
if oldProv == prov.Name {
repoInfo.Provenance = append(repoInfo.Provenance[:i], repoInfo.Provenance[i+1:]...)
continue nextOldProv
}
}
}
repos.Put(repoInfo.Repo.Name, repoInfo)
}
repoInfo.Description = description
repoInfo.Provenance = provenance
repos.Put(repo.Name, repoInfo)
return nil
})
return err
}
func (d *driver) inspectRepo(ctx context.Context, repo *pfs.Repo, includeAuth bool) (*pfs.RepoInfo, error) {
d.initializePachConn()
result := &pfs.RepoInfo{}
if err := d.repos.ReadOnly(ctx).Get(repo.Name, result); err != nil {
return nil, err
}
if includeAuth {
accessLevel, err := d.getAccessLevel(ctx, repo)
if err != nil {
if auth.IsNotActivatedError(err) {
return result, nil
}
return nil, fmt.Errorf("error getting access level for \"%s\": %v",
repo.Name, grpcutil.ScrubGRPC(err))
}
result.AuthInfo = &pfs.RepoAuthInfo{AccessLevel: accessLevel}
}
return result, nil
}
func (d *driver) getAccessLevel(ctx context.Context, repo *pfs.Repo) (auth.Scope, error) {
who, err := d.pachClient.AuthAPIClient.WhoAmI(auth.In2Out(ctx),
&auth.WhoAmIRequest{})
if err != nil {
return auth.Scope_NONE, err
}
if who.IsAdmin {
return auth.Scope_OWNER, nil
}
resp, err := d.pachClient.AuthAPIClient.GetScope(auth.In2Out(ctx),
&auth.GetScopeRequest{Repos: []string{repo.Name}})
if err != nil {
return auth.Scope_NONE, err
}
if len(resp.Scopes) != 1 {
return auth.Scope_NONE, fmt.Errorf("too many results from GetScope: %#v", resp)
}
return resp.Scopes[0], nil
}
func (d *driver) listRepo(ctx context.Context, provenance []*pfs.Repo, includeAuth bool) (*pfs.ListRepoResponse, error) {
repos := d.repos.ReadOnly(ctx)
// Ensure that all provenance repos exist
for _, prov := range provenance {
repoInfo := &pfs.RepoInfo{}
if err := repos.Get(prov.Name, repoInfo); err != nil {
return nil, err
}
}
iterator, err := repos.List()
if err != nil {
return nil, err
}
result := new(pfs.ListRepoResponse)
authSeemsActive := true
nextRepo:
for {
repoName, repoInfo := "", new(pfs.RepoInfo)
ok, err := iterator.Next(&repoName, repoInfo)
if err != nil {
return nil, err
}
if !ok {
break
}
// A repo needs to have *all* the given repos as provenance
// in order to be included in the result.
for _, reqProv := range provenance {
var matched bool
for _, prov := range repoInfo.Provenance {
if reqProv.Name == prov.Name {
matched = true
}
}
if !matched {
continue nextRepo
}
}
if includeAuth && authSeemsActive {
accessLevel, err := d.getAccessLevel(ctx, repoInfo.Repo)
if err == nil {
repoInfo.AuthInfo = &pfs.RepoAuthInfo{AccessLevel: accessLevel}
} else if auth.IsNotActivatedError(err) {
authSeemsActive = false
} else {
return nil, fmt.Errorf("error getting access level for \"%s\": %v",
repoName, grpcutil.ScrubGRPC(err))
}
}
result.RepoInfo = append(result.RepoInfo, repoInfo)
}
return result, nil
}
func (d *driver) deleteRepo(ctx context.Context, repo *pfs.Repo, force bool) error {
_, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
repos := d.repos.ReadWrite(stm)
repoRefCounts := d.repoRefCounts.ReadWriteInt(stm)
commits := d.commits(repo.Name).ReadWrite(stm)
branches := d.branches(repo.Name).ReadWrite(stm)
// check if 'repo' is already gone. If so, return that error. Otherwise,
// proceed with auth check (avoids awkward "access denied" error when calling
// "deleteRepo" on a repo that's already gone)
var existingRepoInfo pfs.RepoInfo
err := repos.Get(repo.Name, &existingRepoInfo)
if err != nil {
if col.IsErrNotFound(err) {
return fmt.Errorf("cannot delete \"%s\" as it does not exist", repo.Name)
}
return fmt.Errorf("error checking whether \"%s\" exists: %v",
repo.Name, err)
}
// Check if the caller is authorized to delete this repo
if err := d.checkIsAuthorized(ctx, repo, auth.Scope_OWNER); err != nil {
return err
}
// Check if this repo is the provenance of some other repos
if !force {
refCount, err := repoRefCounts.Get(repo.Name)
if err != nil {
return err
}
if refCount != 0 {
return fmt.Errorf("cannot delete the provenance of other repos")
}
}
repoInfo := new(pfs.RepoInfo)
if err := repos.Get(repo.Name, repoInfo); err != nil {
return err
}
for _, prov := range repoInfo.Provenance {
if err := repoRefCounts.Decrement(prov.Name); err != nil && !col.IsErrNotFound(err) {
// Skip NotFound error, because it's possible that the
// provenance repo has been deleted via --force.
return err
}
}
if err := repos.Delete(repo.Name); err != nil {
return err
}
if err := repoRefCounts.Delete(repo.Name); err != nil {
return err
}
commits.DeleteAll()
branches.DeleteAll()
return nil
})
if err != nil {
return err
}
if _, err = d.pachClient.SetACL(auth.In2Out(ctx), &auth.SetACLRequest{
Repo: repo.Name, // NewACL is unset, so this will clear the acl for 'repo'
}); err != nil && !auth.IsNotActivatedError(err) {
return grpcutil.ScrubGRPC(err)
}
return nil
}
func (d *driver) startCommit(ctx context.Context, parent *pfs.Commit, branch string, provenance []*pfs.Commit, description string) (*pfs.Commit, error) {
return d.makeCommit(ctx, parent, branch, provenance, nil, description)
}
func (d *driver) buildCommit(ctx context.Context, parent *pfs.Commit, branch string, provenance []*pfs.Commit, tree *pfs.Object) (*pfs.Commit, error) {
return d.makeCommit(ctx, parent, branch, provenance, tree, "")
}
func (d *driver) makeCommit(ctx context.Context, parent *pfs.Commit, branch string, provenance []*pfs.Commit, treeRef *pfs.Object, description string) (*pfs.Commit, error) {
if err := d.checkIsAuthorized(ctx, parent.Repo, auth.Scope_WRITER); err != nil {
return nil, err
}
if parent == nil {
return nil, fmt.Errorf("parent cannot be nil")
}
commit := &pfs.Commit{
Repo: parent.Repo,
ID: uuid.NewWithoutDashes(),
}
var tree hashtree.HashTree
if treeRef != nil {
var buf bytes.Buffer
if err := d.pachClient.GetObject(treeRef.Hash, &buf); err != nil {
return nil, err
}
_tree, err := hashtree.Deserialize(buf.Bytes())
if err != nil {
return nil, err
}
tree = _tree
}
if _, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
repos := d.repos.ReadWrite(stm)
commits := d.commits(parent.Repo.Name).ReadWrite(stm)
branches := d.branches(parent.Repo.Name).ReadWrite(stm)
// Check if repo exists
repoInfo := new(pfs.RepoInfo)
if err := repos.Get(parent.Repo.Name, repoInfo); err != nil {
return err
}
commitInfo := &pfs.CommitInfo{
Commit: commit,
Started: now(),
Description: description,
}
// Use a map to de-dup provenance
provenanceMap := make(map[string]*pfs.Commit)
// Build the full provenance; my provenance's provenance is
// my provenance
for _, prov := range provenance {
provCommits := d.commits(prov.Repo.Name).ReadWrite(stm)
provCommitInfo := new(pfs.CommitInfo)
if err := provCommits.Get(prov.ID, provCommitInfo); err != nil {
return err
}
for _, c := range provCommitInfo.Provenance {
provenanceMap[c.ID] = c
}
}
// finally include the given provenance
for _, c := range provenance {
provenanceMap[c.ID] = c
}
for _, c := range provenanceMap {
commitInfo.Provenance = append(commitInfo.Provenance, c)
}
if branch != "" {
// If we don't have an explicit parent we use the previous head of
// branch as the parent, if it exists.
if parent.ID == "" {
head := new(pfs.Commit)
if err := branches.Get(branch, head); err != nil {
if _, ok := err.(col.ErrNotFound); !ok {
return err
}
} else {
parent.ID = head.ID
}
}
// Make commit the new head of the branch
if err := branches.Put(branch, commit); err != nil {
return err
}
}
if parent.ID != "" {
parentCommitInfo, err := d.inspectCommit(ctx, parent)
if err != nil {
return err
}
// fail if the parent commit has not been finished
if parentCommitInfo.Finished == nil {
return fmt.Errorf("parent commit %s has not been finished", parent.ID)
}
commitInfo.ParentCommit = parent
}
parentTree, err := d.getTreeForCommit(ctx, parent)
if err != nil {
return err
}
if treeRef != nil {
commitInfo.Tree = treeRef
commitInfo.SizeBytes = uint64(tree.FSSize())
commitInfo.Finished = now()
repoInfo.SizeBytes += sizeChange(tree, parentTree)
repos.Put(parent.Repo.Name, repoInfo)
} else {
d.openCommits.ReadWrite(stm).Put(commit.ID, commit)
}
return commits.Create(commit.ID, commitInfo)
}); err != nil {
return nil, err
}
return commit, nil
}
func (d *driver) finishCommit(ctx context.Context, commit *pfs.Commit, description string) error {
if err := d.checkIsAuthorized(ctx, commit.Repo, auth.Scope_WRITER); err != nil {
return err
}
commitInfo, err := d.inspectCommit(ctx, commit)
if err != nil {
return err
}
if commitInfo.Finished != nil {
return fmt.Errorf("commit %s has already been finished", commit.FullID())
}
if description != "" {
commitInfo.Description = description
}
prefix, err := d.scratchCommitPrefix(ctx, commit)
if err != nil {
return err
}
// Read everything under the scratch space for this commit
resp, err := d.etcdClient.Get(ctx, prefix, etcd.WithPrefix(), etcd.WithSort(etcd.SortByModRevision, etcd.SortAscend))
if err != nil {
return err
}
parentTree, err := d.getTreeForCommit(ctx, commitInfo.ParentCommit)
if err != nil {
return err
}
tree := parentTree.Open()
if err := d.applyWrites(resp, tree); err != nil {
return err
}
finishedTree, err := tree.Finish()
if err != nil {
return err
}
// Serialize the tree
data, err := hashtree.Serialize(finishedTree)
if err != nil {
return err
}
if len(data) > 0 {
// Put the tree into the blob store
obj, _, err := d.pachClient.PutObject(bytes.NewReader(data))
if err != nil {
return err
}
commitInfo.Tree = obj
}
commitInfo.SizeBytes = uint64(finishedTree.FSSize())
commitInfo.Finished = now()
sizeChange := sizeChange(finishedTree, parentTree)
_, err = col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
commits := d.commits(commit.Repo.Name).ReadWrite(stm)
repos := d.repos.ReadWrite(stm)
commits.Put(commit.ID, commitInfo)
if err := d.openCommits.ReadWrite(stm).Delete(commit.ID); err != nil {
return fmt.Errorf("could not confirm that commit %s is open; this is likely a bug. err: %v", commit.ID, err)
}
// update repo size
repoInfo := new(pfs.RepoInfo)
if err := repos.Get(commit.Repo.Name, repoInfo); err != nil {
return err
}
// Increment the repo sizes by the sizes of the files that have
// been added in this commit.
repoInfo.SizeBytes += sizeChange
repos.Put(commit.Repo.Name, repoInfo)
return nil
})
if err != nil {
return err
}
// Delete the scratch space for this commit
_, err = d.etcdClient.Delete(ctx, prefix, etcd.WithPrefix())
return err
}
func sizeChange(tree hashtree.HashTree, parentTree hashtree.HashTree) uint64 {
if parentTree == nil {
return uint64(tree.FSSize())
}
var result uint64
tree.Diff(parentTree, "", "", -1, func(path string, node *hashtree.NodeProto, new bool) error {
if node.FileNode != nil && new {
result += uint64(node.SubtreeSize)
}
return nil
})
return result
}
// inspectCommit takes a Commit and returns the corresponding CommitInfo.
//
// As a side effect, this function also replaces the ID in the given commit
// with a real commit ID.
func (d *driver) inspectCommit(ctx context.Context, commit *pfs.Commit) (*pfs.CommitInfo, error) {
if commit == nil {
return nil, fmt.Errorf("cannot inspect nil commit")
}
if err := d.checkIsAuthorized(ctx, commit.Repo, auth.Scope_READER); err != nil {
return nil, err
}
commitID, ancestryLength := parseCommitID(commit.ID)
// Check if the commitID is a branch name
_, err := col.NewSTM(ctx, d.etcdClient, func(stm col.STM) error {
branches := d.branches(commit.Repo.Name).ReadWrite(stm)
head := new(pfs.Commit)
// See if we are given a branch
if err := branches.Get(commitID, head); err != nil {
if _, ok := err.(col.ErrNotFound); !ok {
return err
}
// If it's not a branch, use it as it is
return nil
}
commitID = head.ID
return nil
})
if err != nil {
return nil, err
}
var commitInfo *pfs.CommitInfo
nextCommit := &pfs.Commit{
Repo: commit.Repo,
ID: commitID,
}
for i := 0; i <= ancestryLength; i++ {
if nextCommit == nil {
return nil, pfsserver.ErrCommitNotFound{commit}
}
commits := d.commits(commit.Repo.Name).ReadOnly(ctx)
commitInfo = new(pfs.CommitInfo)
if err := commits.Get(nextCommit.ID, commitInfo); err != nil {
return nil, pfsserver.ErrCommitNotFound{nextCommit}
}
nextCommit = commitInfo.ParentCommit
}
commit.ID = commitInfo.Commit.ID
return commitInfo, nil
}
// parseCommitID accepts a commit ID that might contain the Git ancestry
// syntax, such as "master^2", "master~~", "master^^", "master~5", etc.
// It then returns the ID component such as "master" and the depth of the
// ancestor. For instance, for "master^2" it'd return "master" and 2.
func parseCommitID(commitID string) (string, int) {
sepIndex := strings.IndexAny(commitID, "^~")
if sepIndex == -1 {
return commitID, 0
}
// Find the separator, which is either "^" or "~"
sep := commitID[sepIndex]
strAfterSep := commitID[sepIndex+1:]
// Try convert the string after the separator to an int.
intAfterSep, err := strconv.Atoi(strAfterSep)
// If it works, return
if err == nil {
return commitID[:sepIndex], intAfterSep
}
// Otherwise, we check if there's a sequence of separators, as in
// "master^^^^" or "master~~~~"
for i := sepIndex + 1; i < len(commitID); i++ {
if commitID[i] != sep {
// If we find a character that's not the separator, as in
// "master~whatever", then we return.
return commitID, 0
}
}
// Here we've confirmed that the commit ID ends with a sequence of
// (the same) separators and therefore uses the correct ancestry
// syntax.
return commitID[:sepIndex], len(commitID) - sepIndex
}
func (d *driver) listCommit(ctx context.Context, repo *pfs.Repo, to *pfs.Commit, from *pfs.Commit, number uint64) ([]*pfs.CommitInfo, error) {
if err := d.checkIsAuthorized(ctx, repo, auth.Scope_READER); err != nil {
return nil, err
}
if from != nil && from.Repo.Name != repo.Name || to != nil && to.Repo.Name != repo.Name {
return nil, fmt.Errorf("`from` and `to` commits need to be from repo %s", repo.Name)
}
// Make sure that the repo exists
_, err := d.inspectRepo(ctx, repo, !includeAuth)
if err != nil {
return nil, err
}
// Make sure that both from and to are valid commits
if from != nil {
_, err = d.inspectCommit(ctx, from)
if err != nil {
return nil, err
}
}
if to != nil {
_, err = d.inspectCommit(ctx, to)
if err != nil {
return nil, err
}
}
// if number is 0, we return all commits that match the criteria
if number == 0 {
number = math.MaxUint64
}
var commitInfos []*pfs.CommitInfo
commits := d.commits(repo.Name).ReadOnly(ctx)
if from != nil && to == nil {
return nil, fmt.Errorf("cannot use `from` commit without `to` commit")
} else if from == nil && to == nil {
// if neither from and to is given, we list all commits in
// the repo, sorted by revision timestamp
iterator, err := commits.List()
if err != nil {
return nil, err
}
var commitID string
for number != 0 {
var commitInfo pfs.CommitInfo
ok, err := iterator.Next(&commitID, &commitInfo)
if err != nil {
return nil, err
}
if !ok {
break
}
commitInfos = append(commitInfos, &commitInfo)
number--
}
} else {
cursor := to
for number != 0 && cursor != nil && (from == nil || cursor.ID != from.ID) {
var commitInfo pfs.CommitInfo
if err := commits.Get(cursor.ID, &commitInfo); err != nil {
return nil, err
}
commitInfos = append(commitInfos, &commitInfo)
cursor = commitInfo.ParentCommit
number--
}
}
return commitInfos, nil
}
type commitStream struct {
stream chan CommitEvent
done chan struct{}
}
func (c *commitStream) Stream() <-chan CommitEvent {
return c.stream
}
func (c *commitStream) Close() {
close(c.done)
}
func (d *driver) subscribeCommit(ctx context.Context, repo *pfs.Repo, branch string, from *pfs.Commit) (CommitStream, error) {
d.initializePachConn()
if from != nil && from.Repo.Name != repo.Name {
return nil, fmt.Errorf("the `from` commit needs to be from repo %s", repo.Name)
}
// We need to watch for new commits before we start listing commits,
// because otherwise we might miss some commits in between when we
// finish listing and when we start watching.
branches := d.branches(repo.Name).ReadOnly(ctx)
newCommitWatcher, err := branches.WatchOne(branch)
if err != nil {
return nil, err
}
stream := make(chan CommitEvent)
done := make(chan struct{})
go func() (retErr error) {
defer newCommitWatcher.Close()
defer func() {
if retErr != nil {
select {
case stream <- CommitEvent{
Err: retErr,
}:
case <-done:
}
}
close(stream)
}()
// keep track of the commits that have been sent
seen := make(map[string]bool)
// include all commits that are currently on the given branch,
// but only the ones that have been finished
commitInfos, err := d.listCommit(ctx, repo, &pfs.Commit{
Repo: repo,
ID: branch,
}, from, 0)
if err != nil {
// We skip NotFound error because it's ok if the branch
// doesn't exist yet, in which case ListCommit returns
// a NotFound error.
if !isNotFoundErr(err) {
return err
}
}
// ListCommit returns commits in newest-first order,
// but SubscribeCommit should return commit in oldest-first
// order, so we reverse the order.
for i := range commitInfos {
commitInfo := commitInfos[len(commitInfos)-i-1]
if commitInfo.Finished != nil {
select {
case stream <- CommitEvent{
Value: commitInfo,
}:
seen[commitInfo.Commit.ID] = true
case <-done: