-
Notifications
You must be signed in to change notification settings - Fork 566
/
driver.go
2107 lines (2009 loc) · 75.1 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 (
"context"
"fmt"
"math"
"os"
"sort"
"strings"
"time"
etcd "go.etcd.io/etcd/client/v3"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/pachyderm/pachyderm/v2/src/auth"
"github.com/pachyderm/pachyderm/v2/src/internal/ancestry"
"github.com/pachyderm/pachyderm/v2/src/internal/client"
col "github.com/pachyderm/pachyderm/v2/src/internal/collection"
"github.com/pachyderm/pachyderm/v2/src/internal/dbutil"
"github.com/pachyderm/pachyderm/v2/src/internal/errors"
"github.com/pachyderm/pachyderm/v2/src/internal/errutil"
"github.com/pachyderm/pachyderm/v2/src/internal/grpcutil"
"github.com/pachyderm/pachyderm/v2/src/internal/log"
"github.com/pachyderm/pachyderm/v2/src/internal/miscutil"
"github.com/pachyderm/pachyderm/v2/src/internal/obj"
"github.com/pachyderm/pachyderm/v2/src/internal/pachsql"
"github.com/pachyderm/pachyderm/v2/src/internal/pctx"
"github.com/pachyderm/pachyderm/v2/src/internal/pfsdb"
"github.com/pachyderm/pachyderm/v2/src/internal/storage"
"github.com/pachyderm/pachyderm/v2/src/internal/storage/fileset"
"github.com/pachyderm/pachyderm/v2/src/internal/storage/fileset/index"
txnenv "github.com/pachyderm/pachyderm/v2/src/internal/transactionenv"
"github.com/pachyderm/pachyderm/v2/src/internal/transactionenv/txncontext"
"github.com/pachyderm/pachyderm/v2/src/internal/uuid"
"github.com/pachyderm/pachyderm/v2/src/pfs"
"github.com/pachyderm/pachyderm/v2/src/pps"
pfsserver "github.com/pachyderm/pachyderm/v2/src/server/pfs"
)
const (
StorageTaskNamespace = "storage"
fileSetsRepo = client.FileSetsRepoName
defaultTTL = client.DefaultTTL
maxTTL = 30 * time.Minute
)
// 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 driver struct {
env Env
// etcdClient and prefix write repo and other metadata to etcd
etcdClient *etcd.Client
txnEnv *txnenv.TransactionEnv
prefix string
// collections
commits col.PostgresCollection
branches col.PostgresCollection
storage *storage.Server
commitStore commitStore
cache *fileset.Cache
}
func newDriver(env Env) (*driver, error) {
// test object storage.
if err := func() error {
ctx, cf := context.WithTimeout(pctx.Background("newDriver"), 30*time.Second)
defer cf()
return obj.TestStorage(ctx, env.Bucket, env.ObjectClient)
}(); err != nil {
return nil, err
}
commits := pfsdb.Commits(env.DB, env.Listener)
branches := pfsdb.Branches(env.DB, env.Listener)
// Setup driver struct.
d := &driver{
env: env,
etcdClient: env.EtcdClient,
txnEnv: env.TxnEnv,
prefix: env.EtcdPrefix,
commits: commits,
branches: branches,
}
storageEnv := storage.Env{DB: env.DB}
if env.Bucket != nil {
storageEnv.Bucket = env.Bucket
} else {
storageEnv.ObjectStore = env.ObjectClient
}
storageSrv, err := storage.New(storageEnv, env.StorageConfig)
if err != nil {
return nil, err
}
d.storage = storageSrv
d.commitStore = newPostgresCommitStore(env.DB, storageSrv.Tracker, storageSrv.Filesets)
// TODO: Make the cache max size configurable.
d.cache = fileset.NewCache(env.DB, storageSrv.Tracker, 10000)
return d, nil
}
func (d *driver) createRepo(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.Repo, description string, update bool) error {
if repo == nil {
return errors.New("repo cannot be nil")
}
repo.EnsureProject()
if repo.Type == "" {
// default to user type
repo.Type = pfs.UserRepoType
}
if err := ancestry.ValidateName(repo.Name); err != nil {
return err
}
// Check that the repo’s project exists; if not, return an error.
if _, err := pfsdb.GetProjectByName(ctx, txnCtx.SqlTx, repo.Project.Name); err != nil {
return errors.Wrapf(err, "cannot find project %q", repo.Project)
}
// Check whether the user has the permission to create a repo in this project.
if err := d.env.Auth.CheckProjectIsAuthorizedInTransaction(txnCtx, repo.Project, auth.Permission_PROJECT_CREATE_REPO); err != nil {
return errors.Wrap(err, "failed to create repo")
}
// 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).
existingRepoInfo, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, repo.Project.Name, repo.Name, repo.Type)
if err != nil {
if !pfsdb.IsErrRepoNotFound(err) {
return errors.Wrapf(err, "error checking whether repo %q exists", repo)
}
// if this is a system repo, make sure the corresponding user repo already exists
if repo.Type != pfs.UserRepoType {
baseRepo := &pfs.Repo{Project: &pfs.Project{Name: repo.Project.GetName()}, Name: repo.GetName(), Type: pfs.UserRepoType}
_, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, baseRepo.Project.Name, baseRepo.Name, baseRepo.Type)
if err != nil {
if !pfsdb.IsErrRepoNotFound(err) {
return errors.Wrapf(err, "error checking whether user repo for %q exists", baseRepo)
}
return errors.Wrap(err, "cannot create a system repo without a corresponding 'user' repo")
}
}
// New repo case
if whoAmI, err := txnCtx.WhoAmI(); err != nil {
if !errors.Is(err, auth.ErrNotActivated) {
return errors.Wrap(err, "error authenticating (must log in to create a repo)")
}
// ignore ErrNotActivated because we simply don't need to create the role bindings.
} else {
// Create ACL for new repo. Make caller the sole owner. If this is a user repo,
// and the ACL already exists with a different owner, this will fail.
// For now, we expect system repos to share auth info with their corresponding
// user repo, so the role binding should exist
if err := d.env.Auth.CreateRoleBindingInTransaction(txnCtx, whoAmI.Username, []string{auth.RepoOwnerRole}, repo.AuthResource()); err != nil && (!col.IsErrExists(err) || repo.Type == pfs.UserRepoType) {
return errors.Wrapf(grpcutil.ScrubGRPC(err), "could not create role binding for new repo %q", repo)
}
}
_, err := pfsdb.UpsertRepo(ctx, txnCtx.SqlTx, &pfs.RepoInfo{Repo: repo, Description: description})
return errors.Wrapf(err, "could not create repo %q", repo)
}
// Existing repo case--just update the repo description.
if !update {
return pfsserver.ErrRepoExists{
Repo: repo,
}
}
if existingRepoInfo.Description == description {
// Don't overwrite the stored proto with an identical value. This
// optimization is impactful because pps will frequently update the spec
// repo to make sure it exists.
return nil
}
// Check if the caller is authorized to modify this repo
// Note, we don't do this before checking if the description changed because
// there is client code that calls CreateRepo(R, update=true) as an
// idempotent way to ensure that R exists. By permitting these calls when
// they don't actually change anything, even if the caller doesn't have
// WRITER access, we make the pattern more generally useful.
if err := d.env.Auth.CheckRepoIsAuthorizedInTransaction(txnCtx, repo, auth.Permission_REPO_WRITE); err != nil {
return errors.Wrapf(err, "could not update description of %q", repo)
}
existingRepoInfo.Description = description
_, err = pfsdb.UpsertRepo(ctx, txnCtx.SqlTx, existingRepoInfo)
return errors.Wrapf(err, "could not update description of %q", repo)
}
func (d *driver) inspectRepo(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.Repo, includeAuth bool) (*pfs.RepoInfo, error) {
// Validate arguments
if repo == nil {
return nil, errors.New("repo cannot be nil")
}
repoInfo, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, repo.Project.Name, repo.Name, repo.Type)
if err != nil {
if pfsdb.IsErrRepoNotFound(err) {
return nil, pfsserver.ErrRepoNotFound{Repo: repo}
}
return nil, errors.EnsureStack(err)
}
if includeAuth {
resp, err := d.env.Auth.GetPermissionsInTransaction(txnCtx, &auth.GetPermissionsRequest{
Resource: repo.AuthResource(),
})
if err != nil {
if auth.IsErrNotActivated(err) {
return repoInfo, nil
}
return nil, errors.Wrapf(grpcutil.ScrubGRPC(err), "error getting access level for %q", repo)
}
repoInfo.AuthInfo = &pfs.AuthInfo{Permissions: resp.Permissions, Roles: resp.Roles}
}
return repoInfo, nil
}
func (d *driver) getPermissionsInTransaction(txnCtx *txncontext.TransactionContext, repo *pfs.Repo) ([]auth.Permission, []string, error) {
resp, err := d.env.Auth.GetPermissionsInTransaction(txnCtx, &auth.GetPermissionsRequest{Resource: repo.AuthResource()})
if err != nil {
return nil, nil, errors.EnsureStack(err)
}
return resp.Permissions, resp.Roles, nil
}
func (d *driver) hasProjectAccess(
txnCtx *txncontext.TransactionContext,
repoInfo *pfs.RepoInfo,
checkProjectAccess func(string) error) (bool, error) {
if err := checkProjectAccess(repoInfo.Repo.Project.GetName()); err != nil {
if !errors.As(err, &auth.ErrNotAuthorized{}) {
return false, err
}
// Allow access if user has the right permissions at the individual Repo-level.
if err := d.env.Auth.CheckRepoIsAuthorizedInTransaction(txnCtx, repoInfo.Repo, auth.Permission_REPO_READ); err != nil {
if !errors.As(err, &auth.ErrNotAuthorized{}) {
return false, errors.Wrapf(err, "could not check user is authorized to list repo, problem with repo %s", repoInfo.Repo)
}
// User does not have permissions, so we should skip this repo.
return false, nil
}
}
return true, nil
}
func (d *driver) listRepoInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, includeAuth bool, repoType string, projects []*pfs.Project) ([]*pfs.RepoInfo, error) {
projectNames := make(map[string]bool, 0)
for _, project := range projects {
projectNames[project.GetName()] = true
}
filter := &pfs.Repo{}
if repoType != "" { // blank type means return all, otherwise return a specific type
filter.Type = repoType
}
var authActive bool
if includeAuth {
if _, err := txnCtx.WhoAmI(); err == nil {
authActive = true
} else if !errors.Is(err, auth.ErrNotActivated) {
return nil, errors.Wrap(err, "check if auth is active")
}
}
// Cache the project level access because it applies to every repo within the same project.
checkProjectAccess := miscutil.CacheFunc(func(project string) error {
return d.env.Auth.CheckProjectIsAuthorizedInTransaction(txnCtx, &pfs.Project{Name: project}, auth.Permission_PROJECT_LIST_REPO)
}, 100)
var repos []*pfs.RepoInfo
if err := pfsdb.ForEachRepo(ctx, txnCtx.SqlTx, filter, func(repoWithID pfsdb.RepoInfoWithID) error {
if _, ok := projectNames[repoWithID.RepoInfo.Repo.Project.GetName()]; !ok && len(projectNames) > 0 {
return nil // project doesn't match filter.
}
if authActive {
hasAccess, err := d.hasProjectAccess(txnCtx, repoWithID.RepoInfo, checkProjectAccess)
if err != nil {
return errors.Wrap(err, "checking project access")
}
if !hasAccess {
return nil
}
permissions, roles, err := d.getPermissionsInTransaction(txnCtx, repoWithID.RepoInfo.Repo)
if err != nil {
return errors.Wrapf(err, "error getting access level for %q", repoWithID.RepoInfo.Repo)
}
repoWithID.RepoInfo.AuthInfo = &pfs.AuthInfo{Permissions: permissions, Roles: roles}
}
size, err := d.repoSize(ctx, txnCtx, repoWithID.RepoInfo)
if err != nil {
return errors.Wrapf(err, "getting repo size for %q", repoWithID.RepoInfo.Repo)
}
repoWithID.RepoInfo.SizeBytesUpperBound = size
repos = append(repos, repoWithID.RepoInfo)
return nil
}); err != nil {
return nil, errors.Wrap(err, "for each repo")
}
return repos, nil
}
func (d *driver) deleteRepos(ctx context.Context, projects []*pfs.Project, force bool) ([]*pfs.Repo, error) {
var deleted []*pfs.Repo
if err := d.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {
var err error
deleted, err = d.deleteReposInTransaction(ctx, txnCtx, projects, force)
return err
}); err != nil {
return nil, errors.Wrap(err, "delete repos")
}
return deleted, nil
}
func (d *driver) deleteReposInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, projects []*pfs.Project, force bool) ([]*pfs.Repo, error) {
repos, err := d.listRepoInTransaction(ctx, txnCtx, false /* includeAuth */, "", projects)
if err != nil {
return nil, errors.Wrap(err, "list repos")
}
return d.deleteReposHelper(ctx, txnCtx, repos, force)
}
func (d *driver) deleteReposHelper(ctx context.Context, txnCtx *txncontext.TransactionContext, ris []*pfs.RepoInfo, force bool) ([]*pfs.Repo, error) {
if len(ris) == 0 {
return nil, nil
}
// filter out repos that cannot be deleted
var filter []*pfs.RepoInfo
for _, ri := range ris {
ok, err := d.canDeleteRepo(ctx, txnCtx, ri.Repo)
if err != nil {
return nil, err
} else if ok {
filter = append(filter, ri)
}
}
ris = filter
var deleted []*pfs.Repo
var bis []*pfs.BranchInfo
for _, ri := range ris {
bs, err := d.listRepoBranches(ctx, txnCtx, ri)
if err != nil {
return nil, err
}
bis = append(bis, bs...)
}
if err := d.deleteBranches(ctx, txnCtx, bis, force); err != nil {
return nil, err
}
for _, ri := range ris {
if err := d.deleteRepoInfo(ctx, txnCtx, ri, force); err != nil {
return nil, err
}
deleted = append(deleted, ri.Repo)
}
return deleted, nil
}
func (d *driver) deleteRepo(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.Repo, force bool) (bool, error) {
if _, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, repo.Project.Name, repo.Name, repo.Type); err != nil {
if !pfsdb.IsErrRepoNotFound(err) {
return false, errors.Wrapf(err, "error checking whether %q exists", repo)
}
return false, nil
}
if ok, err := d.canDeleteRepo(ctx, txnCtx, repo); err != nil {
return false, errors.Wrapf(err, "error checking whether repo %q can be deleted", repo.String())
} else if !ok {
return false, nil
}
related, err := d.relatedRepos(ctx, txnCtx, repo)
if err != nil {
return false, err
}
var bis []*pfs.BranchInfo
for _, repoInfoWithID := range related {
bs, err := d.listRepoBranches(ctx, txnCtx, repoInfoWithID.RepoInfo)
if err != nil {
return false, err
}
bis = append(bis, bs...)
}
// this is where the deletion is happening.
if err := d.deleteBranches(ctx, txnCtx, bis, force); err != nil {
return false, err
}
for _, repoInfoWithID := range related {
if err := d.deleteRepoInfo(ctx, txnCtx, repoInfoWithID.RepoInfo, force); err != nil {
return false, err
}
}
return true, nil
}
// delete branches from most provenance to least, that way if one
// branch is provenant on another (which is likely the case when
// multiple repos are provided) we delete them in the right order.
func (d *driver) deleteBranches(ctx context.Context, txnCtx *txncontext.TransactionContext, branchInfos []*pfs.BranchInfo, force bool) error {
sort.Slice(branchInfos, func(i, j int) bool { return len(branchInfos[i].Provenance) > len(branchInfos[j].Provenance) })
for _, bi := range branchInfos {
if err := d.deleteBranch(ctx, txnCtx, bi.Branch, force); err != nil {
return errors.Wrapf(err, "delete branch %s", bi.Branch)
}
}
return nil
}
func (d *driver) listRepoBranches(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.RepoInfo) ([]*pfs.BranchInfo, error) {
var bis []*pfs.BranchInfo
for _, branch := range repo.Branches {
bi, err := d.inspectBranchInTransaction(ctx, txnCtx, branch)
if err != nil {
return nil, errors.Wrapf(err, "error inspecting branch %s", branch)
}
bis = append(bis, bi)
}
return bis, nil
}
// before this method is called, a caller should make sure this repo can be deleted with d.canDeleteRepo() and that
// all of the repo's branches are deleted using d.deleteBranches()
func (d *driver) deleteRepoInfo(ctx context.Context, txnCtx *txncontext.TransactionContext, ri *pfs.RepoInfo, force bool) error {
var nonCtxCommitInfos []*pfs.CommitInfo
if err := pfsdb.ForEachCommit(ctx, d.env.DB, &pfs.Commit{Repo: ri.Repo}, func(commitWithID pfsdb.CommitWithID) error {
nonCtxCommitInfos = append(nonCtxCommitInfos, commitWithID.CommitInfo)
return nil
}); err != nil {
return errors.Wrap(err, "delete repo info")
}
commitInfos, err := pfsdb.ListCommitTxByFilter(ctx, txnCtx.SqlTx, &pfs.Commit{Repo: ri.Repo})
if err != nil {
return errors.Wrap(err, "delete repo info")
}
// and then delete their file sets.
for _, ci := range commitInfos {
if err := d.commitStore.DropFileSetsTx(txnCtx.SqlTx, ci.Commit); err != nil {
return errors.EnsureStack(err)
}
}
// Despite the fact that we already deleted each branch with
// deleteBranch, we also do branches.DeleteAll(), this insulates us
// against certain corruption situations where the RepoInfo doesn't
// exist in postgres but branches do.
err = pfsdb.ForEachBranch(ctx, txnCtx.SqlTx, &pfs.Branch{Repo: ri.Repo}, func(branchInfoWithID pfsdb.BranchInfoWithID) error {
return pfsdb.DeleteBranch(ctx, txnCtx.SqlTx, &branchInfoWithID, force)
}, pfsdb.OrderByBranchColumn{Column: pfsdb.BranchColumnID, Order: pfsdb.SortOrderAsc})
if err != nil {
return errors.Wrap(err, "delete repo info")
}
// Similarly with commits
for _, commitInfo := range commitInfos {
if err := pfsdb.DeleteCommit(ctx, txnCtx.SqlTx, commitInfo.Commit); err != nil {
return errors.Wrap(err, "delete repo info")
}
}
if err := pfsdb.DeleteRepo(ctx, txnCtx.SqlTx, ri.Repo.Project.Name, ri.Repo.Name, ri.Repo.Type); err != nil && !pfsdb.IsErrRepoNotFound(err) {
return errors.Wrapf(err, "repos.Delete")
}
// since system repos share a role binding, only delete it if this is the user repo, in which case the other repos will be deleted anyway
if ri.Repo.Type == pfs.UserRepoType {
if err := d.env.Auth.DeleteRoleBindingInTransaction(txnCtx, ri.Repo.AuthResource()); err != nil && !auth.IsErrNotActivated(err) {
return grpcutil.ScrubGRPC(err)
}
}
return nil
}
func (d *driver) relatedRepos(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.Repo) ([]pfsdb.RepoInfoWithID, error) {
if repo.Type != pfs.UserRepoType {
ri, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, repo.Project.Name, repo.Name, repo.Type)
if err != nil {
return nil, err
}
return []pfsdb.RepoInfoWithID{{RepoInfo: ri}}, nil
}
filter := &pfs.Repo{
Name: repo.Name,
Project: repo.Project,
}
related, err := pfsdb.ListRepo(ctx, txnCtx.SqlTx, filter)
if err != nil {
return nil, errors.Wrap(err, "list repo by name")
}
if err != nil && !pfsdb.IsErrRepoNotFound(err) { // TODO(acohen4): !RepoNotFound may be unnecessary
return nil, errors.Wrapf(err, "error finding dependent repos for %q", repo.Name)
}
return related, nil
}
func (d *driver) canDeleteRepo(ctx context.Context, txnCtx *txncontext.TransactionContext, repo *pfs.Repo) (bool, error) {
userRepo := proto.Clone(repo).(*pfs.Repo)
userRepo.Type = pfs.UserRepoType
if err := d.env.Auth.CheckRepoIsAuthorizedInTransaction(txnCtx, userRepo, auth.Permission_REPO_DELETE); err != nil {
if auth.IsErrNotAuthorized(err) {
return false, nil
}
return false, errors.Wrapf(err, "check repo %q is authorized for deletion", userRepo.String())
}
if _, err := d.env.GetPipelineInspector().InspectPipelineInTransaction(ctx, txnCtx, pps.RepoPipeline(repo)); err == nil {
return false, errors.Errorf("cannot delete a repo associated with a pipeline - delete the pipeline instead")
} else if err != nil && !errutil.IsNotFoundError(err) {
return false, errors.Wrapf(err, "inspect pipeline %q", pps.RepoPipeline(repo).String())
}
return true, nil
}
func (d *driver) createProject(ctx context.Context, req *pfs.CreateProjectRequest) error {
return d.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {
return d.createProjectInTransaction(ctx, txnCtx, req)
})
}
func (d *driver) createProjectInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, req *pfs.CreateProjectRequest) error {
if err := req.Project.ValidateName(); err != nil {
return errors.Wrapf(err, "invalid project name")
}
if req.Update {
return errors.Wrapf(pfsdb.UpsertProject(ctx, txnCtx.SqlTx,
&pfs.ProjectInfo{Project: req.Project, Description: req.Description}),
"failed to update project %s", req.Project.Name)
}
// If auth is active, make caller the owner of this new project.
if whoAmI, err := txnCtx.WhoAmI(); err == nil {
if err := d.env.Auth.CreateRoleBindingInTransaction(
txnCtx,
whoAmI.Username,
[]string{auth.ProjectOwnerRole},
&auth.Resource{Type: auth.ResourceType_PROJECT, Name: req.Project.GetName()},
); err != nil && !errors.Is(err, col.ErrExists{}) {
return errors.Wrapf(err, "could not create role binding for new project %s", req.Project.GetName())
}
} else if !errors.Is(err, auth.ErrNotActivated) {
return errors.Wrap(err, "could not get caller's username")
}
if err := pfsdb.CreateProject(ctx, txnCtx.SqlTx, &pfs.ProjectInfo{
Project: req.Project,
Description: req.Description,
CreatedAt: timestamppb.Now(),
}); err != nil {
if errors.As(err, &pfsdb.ProjectAlreadyExistsError{}) {
return errors.Join(err, pfsserver.ErrProjectExists{Project: req.Project})
}
return errors.Wrap(err, "could not create project")
}
return nil
}
func (d *driver) inspectProject(ctx context.Context, project *pfs.Project) (*pfs.ProjectInfo, error) {
var pi *pfs.ProjectInfo
if err := dbutil.WithTx(ctx, d.env.DB, func(ctx context.Context, tx *pachsql.Tx) error {
var err error
pi, err = pfsdb.GetProjectByName(ctx, tx, pfsdb.ProjectKey(project))
if err != nil {
return err
}
return nil
}); err != nil {
return nil, errors.Wrapf(err, "error getting project %q", project)
}
resp, err := d.env.Auth.GetPermissions(ctx, &auth.GetPermissionsRequest{Resource: project.AuthResource()})
if err != nil {
if errors.Is(err, auth.ErrNotActivated) {
return pi, nil
}
return nil, errors.Wrapf(err, "error getting permissions for project %q", project)
}
pi.AuthInfo = &pfs.AuthInfo{Permissions: resp.Permissions, Roles: resp.Roles}
return pi, nil
}
func (d *driver) findCommits(ctx context.Context, request *pfs.FindCommitsRequest, cb func(response *pfs.FindCommitsResponse) error) error {
commit := request.Start
foundCommits, commitsSearched := uint32(0), uint32(0)
searchDone := false
var found *pfs.Commit
makeResp := func(found *pfs.Commit, commitsSearched uint32, lastSearchedCommit *pfs.Commit) *pfs.FindCommitsResponse {
resp := &pfs.FindCommitsResponse{}
if found != nil {
resp.Result = &pfs.FindCommitsResponse_FoundCommit{FoundCommit: found}
} else {
resp.Result = &pfs.FindCommitsResponse_LastSearchedCommit{LastSearchedCommit: commit}
}
resp.CommitsSearched = commitsSearched
return resp
}
for {
if searchDone {
return errors.EnsureStack(cb(makeResp(nil, commitsSearched, commit)))
}
logFields := []zap.Field{
zap.String("commit", commit.Id),
zap.String("repo", commit.Repo.String()),
zap.String("target", request.FilePath),
}
if commit.Branch != nil {
logFields = append(logFields, zap.String("branch", commit.Branch.String()))
}
if err := log.LogStep(ctx, "searchingCommit", func(ctx context.Context) error {
inspectCommitResp, err := d.resolveCommitWithAuth(ctx, commit)
if err != nil {
return err
}
if inspectCommitResp.Finished == nil {
return pfsserver.ErrCommitNotFinished{Commit: commit}
}
commit = inspectCommitResp.Commit
inCommit, err := d.isPathModifiedInCommit(ctx, commit, request.FilePath)
if err != nil {
return err
}
if inCommit {
log.Info(ctx, "found target", zap.String("commit", commit.Id), zap.String("repo", commit.Repo.String()), zap.String("target", request.FilePath))
found = commit
foundCommits++
if err := cb(makeResp(found, commitsSearched, nil)); err != nil {
return err
}
}
commitsSearched++
if (foundCommits == request.Limit && request.Limit != 0) || inspectCommitResp.ParentCommit == nil {
searchDone = true
return nil
}
commit = inspectCommitResp.ParentCommit
return nil
}, logFields...); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return errors.EnsureStack(cb(makeResp(nil, commitsSearched, commit)))
}
return errors.EnsureStack(err)
}
}
}
func (d *driver) isPathModifiedInCommit(ctx context.Context, commit *pfs.Commit, filePath string) (bool, error) {
diffID, err := d.getCompactedDiffFileSet(ctx, commit)
if err != nil {
return false, err
}
diffFileSet, err := d.storage.Filesets.Open(ctx, []fileset.ID{*diffID})
if err != nil {
return false, err
}
found := false
pathOption := []index.Option{
index.WithRange(&index.PathRange{
Lower: filePath,
}),
}
if err = diffFileSet.Iterate(ctx, func(file fileset.File) error {
if file.Index().Path == filePath {
found = true
return errutil.ErrBreak
}
return nil
}, pathOption...); err != nil && !errors.Is(err, errutil.ErrBreak) {
return false, err
}
// we don't care about the file operation, so if a file was already found, skip iterating over deletive set.
if found {
return found, nil
}
if err = diffFileSet.IterateDeletes(ctx, func(file fileset.File) error {
if file.Index().Path == filePath {
found = true
return errutil.ErrBreak
}
return nil
}, pathOption...); err != nil && !errors.Is(err, errutil.ErrBreak) {
return false, err
}
return found, nil
}
func (d *driver) getCompactedDiffFileSet(ctx context.Context, commit *pfs.Commit) (*fileset.ID, error) {
diff, err := d.commitStore.GetDiffFileSet(ctx, commit)
if err != nil {
return nil, errors.EnsureStack(err)
}
isCompacted, err := d.storage.Filesets.IsCompacted(ctx, *diff)
if err != nil {
return nil, errors.EnsureStack(err)
}
if isCompacted {
return diff, nil
}
if err := d.storage.Filesets.WithRenewer(ctx, defaultTTL, func(ctx context.Context, renewer *fileset.Renewer) error {
compactor := newCompactor(d.storage.Filesets, d.env.StorageConfig.StorageCompactionMaxFanIn)
taskDoer := d.env.TaskService.NewDoer(StorageTaskNamespace, commit.Id, nil)
diff, err = d.compactDiffFileSet(ctx, compactor, taskDoer, renewer, commit)
return err
}); err != nil {
return nil, errors.EnsureStack(err)
}
return diff, nil
}
// The ProjectInfo provided to the closure is repurposed on each invocation, so it's the client's responsibility to clone the ProjectInfo if desired
func (d *driver) listProject(ctx context.Context, cb func(*pfs.ProjectInfo) error) error {
authIsActive := true
return errors.Wrap(dbutil.WithTx(ctx, d.env.DB, func(ctx context.Context, tx *pachsql.Tx) error {
return d.txnEnv.WithWriteContext(ctx, func(txnCtx *txncontext.TransactionContext) error {
return d.listProjectInTransaction(ctx, txnCtx, func(proj *pfs.ProjectInfo) error {
if authIsActive {
resp, err := d.env.Auth.GetPermissionsInTransaction(txnCtx, &auth.GetPermissionsRequest{Resource: proj.GetProject().AuthResource()})
if err != nil {
if errors.Is(err, auth.ErrNotActivated) {
// Avoid unnecessary subsequent Auth API calls.
authIsActive = false
return cb(proj)
}
return errors.Wrapf(err, "getting permissions for project %s", proj.Project)
}
proj.AuthInfo = &pfs.AuthInfo{Permissions: resp.Permissions, Roles: resp.Roles}
}
return cb(proj)
})
})
}), "list projects")
}
// The ProjectInfo provided to the closure is repurposed on each invocation, so it's the client's responsibility to clone the ProjectInfo if desired
func (d *driver) listProjectInTransaction(ctx context.Context, txnCtx *txncontext.TransactionContext, cb func(*pfs.ProjectInfo) error) error {
return errors.Wrap(pfsdb.ForEachProject(ctx, txnCtx.SqlTx, func(project pfsdb.ProjectWithID) error {
return cb(project.ProjectInfo)
}), "list projects in transaction")
}
// TODO: delete all repos and pipelines within project
func (d *driver) deleteProject(ctx context.Context, txnCtx *txncontext.TransactionContext, project *pfs.Project, force bool) error {
if err := project.ValidateName(); err != nil {
return errors.Wrap(err, "invalid project name")
}
if err := d.env.Auth.CheckProjectIsAuthorizedInTransaction(txnCtx, project, auth.Permission_PROJECT_DELETE, auth.Permission_PROJECT_MODIFY_BINDINGS); err != nil {
return errors.Wrapf(err, "user is not authorized to delete project %q", project)
}
var errs error
repos, err := d.listRepoInTransaction(ctx, txnCtx, false, "", []*pfs.Project{project})
if err != nil {
return errors.Wrap(err, "list repos to determine if any still exist")
}
for _, repoInfo := range repos {
errs = errors.Join(errs, fmt.Errorf("repo %v still exists", repoInfo.GetRepo()))
}
if errs != nil && !force {
return status.Error(codes.FailedPrecondition, fmt.Sprintf("cannot delete project %s: %v", project.Name, errs))
}
if err := pfsdb.DeleteProject(ctx, txnCtx.SqlTx, pfsdb.ProjectKey(project)); err != nil {
return errors.Wrapf(err, "delete project %q", project)
}
if err := d.env.Auth.DeleteRoleBindingInTransaction(txnCtx, project.AuthResource()); err != nil {
if !errors.Is(err, auth.ErrNotActivated) {
return errors.Wrapf(err, "delete role binding for project %q", project)
}
}
return nil
}
// Set child.ParentCommit (if 'parent' has been determined).
func (d *driver) linkParent(ctx context.Context, txnCtx *txncontext.TransactionContext, child *pfs.CommitInfo, parent *pfs.Commit, needsFinishedParent bool) error {
if parent == nil {
return nil
}
// Resolve 'parent' if it's a branch that isn't 'branch' (which can
// happen if 'branch' is new and diverges from the existing branch in
// 'parent').
parentCommitInfo, err := d.resolveCommit(ctx, txnCtx.SqlTx, parent)
if err != nil {
return errors.Wrapf(err, "parent commit not found")
}
// fail if the parent commit has not been finished
if needsFinishedParent && parentCommitInfo.Finishing == nil {
return errors.Errorf("parent commit %s has not been finished", parentCommitInfo.Commit)
}
child.ParentCommit = parentCommitInfo.Commit
return nil
}
// creates a new commit, and adds both commit ancestry, and commit provenance pointers
//
// NOTE: Requiring source commits to have finishing / finished parents ensures that the commits are not compacted
// in a pathological order (finishing later commits before earlier commits will result with us compacting
// the earlier commits multiple times).
func (d *driver) addCommit(ctx context.Context, txnCtx *txncontext.TransactionContext, newCommitInfo *pfs.CommitInfo, parent *pfs.Commit, directProvenance []*pfs.Branch, needsFinishedParent bool) (pfsdb.CommitID, error) {
if err := d.linkParent(ctx, txnCtx, newCommitInfo, parent, needsFinishedParent); err != nil {
return 0, err
}
for _, prov := range directProvenance {
b, err := pfsdb.GetBranchInfoWithID(ctx, txnCtx.SqlTx, prov)
if err != nil {
if pfsdb.IsNotFoundError(err) {
return 0, errors.Join(err, pfsserver.ErrBranchNotFound{Branch: prov})
}
return 0, errors.Wrap(err, "add commit")
}
newCommitInfo.DirectProvenance = append(newCommitInfo.DirectProvenance, b.BranchInfo.Head)
}
commitID, err := pfsdb.CreateCommit(ctx, txnCtx.SqlTx, newCommitInfo)
if err != nil {
if errors.As(err, &pfsdb.CommitAlreadyExistsError{}) {
return 0, errors.Join(err, pfsserver.ErrInconsistentCommit{Commit: newCommitInfo.Commit})
}
return 0, errors.EnsureStack(err)
}
for _, p := range newCommitInfo.DirectProvenance {
if err := pfsdb.AddCommitProvenance(txnCtx.SqlTx, newCommitInfo.Commit, p); err != nil {
return 0, err
}
}
return commitID, nil
}
// startCommit makes a new commit in 'branch', with the parent 'parent':
// - 'parent' may be omitted, in which case the parent commit is inferred
// from 'branch'.
// - If 'parent' is set, it determines the parent commit, but 'branch' is
// still moved to point at the new commit
func (d *driver) startCommit(
ctx context.Context,
txnCtx *txncontext.TransactionContext,
parent *pfs.Commit,
branch *pfs.Branch,
description string,
) (*pfs.Commit, error) {
// Validate arguments:
if branch == nil || branch.Name == "" {
return nil, errors.Errorf("branch must be specified")
}
// Check that caller is authorized
if err := d.env.Auth.CheckRepoIsAuthorizedInTransaction(txnCtx, branch.Repo, auth.Permission_REPO_WRITE); err != nil {
return nil, errors.EnsureStack(err)
}
// New commit and commitInfo
newCommitInfo := newUserCommitInfo(txnCtx, branch)
newCommitInfo.Description = description
if err := ancestry.ValidateName(branch.Name); err != nil {
return nil, err
}
// Check if repo exists
_, err := pfsdb.GetRepoByName(ctx, txnCtx.SqlTx, branch.Repo.Project.Name, branch.Repo.Name, branch.Repo.Type)
if err != nil {
if pfsdb.IsErrRepoNotFound(err) {
return nil, pfsserver.ErrRepoNotFound{Repo: branch.Repo}
}
return nil, errors.EnsureStack(err)
}
updateCommitBranchField := false
// update 'branch' (which must always be set) and set parent.ID (if 'parent'
// was not set)
b, err := pfsdb.GetBranchInfoWithID(ctx, txnCtx.SqlTx, branch)
if err != nil {
if !pfsdb.IsNotFoundError(err) {
return nil, errors.Wrap(err, "start commit")
}
updateCommitBranchField = true // the branch field on the commit will have to be updated after the branch is created.
}
branchInfo := &pfs.BranchInfo{}
if b != nil && b.BranchInfo != nil {
branchInfo = b.BranchInfo
}
if branchInfo.Branch == nil {
// New branch
branchInfo.Branch = branch
}
// If the parent is unspecified, use the current head of the branch
if parent == nil {
parent = branchInfo.Head
}
commitID, err := d.addCommit(ctx, txnCtx, newCommitInfo, parent, branchInfo.DirectProvenance, true)
if err != nil {
return nil, err
}
// Point 'branch' at the new commit
branchInfo.Head = newCommitInfo.Commit
if _, err = pfsdb.UpsertBranch(ctx, txnCtx.SqlTx, branchInfo); err != nil {
return nil, errors.Wrap(err, "start commit")
}
// update branch field after a new branch is created.
if updateCommitBranchField {
newCommitInfo.Commit.Branch = branchInfo.Branch
if err := pfsdb.UpdateCommit(ctx, txnCtx.SqlTx, commitID, newCommitInfo, pfsdb.AncestryOpt{SkipParent: true, SkipChildren: true}); err != nil {
return nil, errors.Wrap(err, "start commit: update branch field after new branch is created")
}
}
// check if this is happening in a spout pipeline, and alias the spec commit
_, ok1 := os.LookupEnv(client.PPSPipelineNameEnv)
_, ok2 := os.LookupEnv("PPS_SPEC_COMMIT")
if !(ok1 && ok2) && len(branchInfo.Provenance) > 0 {
// Otherwise, we don't allow user code to start commits on output branches
return nil, pfsserver.ErrCommitOnOutputBranch{Branch: branch}
}
// Defer propagation of the commit until the end of the transaction so we can
// batch downstream commits together if there are multiple changes.
if err := txnCtx.PropagateBranch(branch); err != nil {
return nil, err
}
return newCommitInfo.Commit, nil
}
func (d *driver) finishCommit(ctx context.Context, txnCtx *txncontext.TransactionContext, commit *pfs.Commit, description, commitError string, force bool) error {
commitWithID, err := d.resolveCommitWithID(ctx, txnCtx.SqlTx, commit)
if err != nil {
return err
}
commitInfo := commitWithID.CommitInfo
if commitInfo.Finishing != nil {
return pfsserver.ErrCommitFinished{
Commit: commitInfo.Commit,
}
}
if !force && len(commitInfo.DirectProvenance) > 0 {
if info, err := d.env.GetPipelineInspector().InspectPipelineInTransaction(ctx, txnCtx, pps.RepoPipeline(commitInfo.Commit.Repo)); err != nil && !errutil.IsNotFoundError(err) {
return errors.EnsureStack(err)
} else if err == nil && info.Type == pps.PipelineInfo_PIPELINE_TYPE_TRANSFORM {
return errors.Errorf("cannot finish a pipeline output or meta commit, use 'stop job' instead")
}
// otherwise, this either isn't a pipeline at all, or is a spout or service for which we should allow finishing
}
if description != "" {
commitInfo.Description = description
}
commitInfo.Finishing = txnCtx.Timestamp
commitInfo.Error = commitError
return pfsdb.UpdateCommit(ctx, txnCtx.SqlTx, commitWithID.ID, commitInfo, pfsdb.AncestryOpt{SkipParent: true, SkipChildren: true})
}
func (d *driver) repoSize(ctx context.Context, txnCtx *txncontext.TransactionContext, repoInfo *pfs.RepoInfo) (int64, error) {
for _, branch := range repoInfo.Branches {
if branch.Name == "master" {
branchInfo, err := pfsdb.GetBranchInfoWithID(ctx, txnCtx.SqlTx, branch)
if err != nil {
return 0, errors.Wrap(err, "repo size")
}
commit := branchInfo.Head
for commit != nil {
commitInfo, err := d.resolveCommit(ctx, txnCtx.SqlTx, commit)
if err != nil {
return 0, err
}
if commitInfo.Details != nil {
return commitInfo.Details.SizeBytes, nil
}
commit = commitInfo.ParentCommit
}
}
}
return 0, nil
}
// propagateBranches starts commits downstream of 'branches'
// in order to restore the invariant that branch provenance matches HEAD commit
// provenance:
//
// B.Head is provenant on A.Head <=>
// branch B is provenant on branch A
//
// The implementation assumes that the invariant already holds for all branches
// upstream of 'branches', but not necessarily for each 'branch' itself.
//
// In other words, propagateBranches scans all branches b_downstream that are
// equal to or downstream of 'branches', and if the HEAD of b_downstream isn't
// provenant on the HEADs of b_downstream's provenance, propagateBranches starts
// a new HEAD commit in b_downstream that is. For example, propagateBranches
// starts downstream output commits (which trigger PPS jobs) when new input
// commits arrive on 'branch', when 'branches's HEAD is deleted, or when
// 'branches' are newly created (i.e. in CreatePipeline).
func (d *driver) propagateBranches(ctx context.Context, txnCtx *txncontext.TransactionContext, branches []*pfs.Branch) error {
if len(branches) == 0 {
return nil
}
var propagatedBranches []*pfs.BranchInfo
seen := make(map[string]*pfs.BranchInfo)
for _, b := range branches {
biWithID, err := pfsdb.GetBranchInfoWithID(ctx, txnCtx.SqlTx, b)
if err != nil {
return errors.Wrapf(err, "propagate branches: get branch %q", pfsdb.BranchKey(b))
}
for _, subvenantB := range biWithID.Subvenance {