forked from pachyderm/pachyderm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
2267 lines (2033 loc) · 64.4 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 persist
import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"math"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/pachyderm/pachyderm/src/client"
"github.com/pachyderm/pachyderm/src/client/pfs"
pfsserver "github.com/pachyderm/pachyderm/src/server/pfs"
"github.com/pachyderm/pachyderm/src/server/pfs/db/persist"
"github.com/pachyderm/pachyderm/src/server/pfs/drive"
log "github.com/Sirupsen/logrus"
"github.com/cenkalti/backoff"
"github.com/dancannon/gorethink"
"github.com/gogo/protobuf/proto"
"github.com/gogo/protobuf/types"
"google.golang.org/grpc"
)
// A Table is a rethinkdb table name.
type Table string
// A PrimaryKey is a rethinkdb primary key identifier.
type PrimaryKey string
const (
repoTable Table = "Repos"
diffTable Table = "Diffs"
commitTable Table = "Commits"
connectTimeoutSeconds = 5
maxIdle = 5
maxOpen = 100
)
const (
// ErrConflictFileTypeMsg is used when we see a file that is both a file and directory
ErrConflictFileTypeMsg = "file type conflict"
)
var (
tables = []Table{
repoTable,
commitTable,
diffTable,
}
tableToTableCreateOpts = map[Table][]gorethink.TableCreateOpts{
repoTable: []gorethink.TableCreateOpts{
gorethink.TableCreateOpts{
PrimaryKey: "Name",
},
},
commitTable: []gorethink.TableCreateOpts{
gorethink.TableCreateOpts{
PrimaryKey: "ID",
},
},
diffTable: []gorethink.TableCreateOpts{
gorethink.TableCreateOpts{
PrimaryKey: "ID",
},
},
}
)
type driver struct {
blockAddress string
blockClientOnce sync.Once
blockClient pfs.BlockAPIClient
dbName string
dbClient *gorethink.Session
}
// NewDriver is used to create a new Driver instance
func NewDriver(blockAddress string, dbAddress string, dbName string) (drive.Driver, error) {
dbClient, err := DbConnect(dbAddress)
if err != nil {
return nil, err
}
return &driver{
blockAddress: blockAddress,
blockClientOnce: sync.Once{},
blockClient: nil,
dbName: dbName,
dbClient: dbClient,
}, nil
}
func (d *driver) getBlockClient() (pfs.BlockAPIClient, error) {
if d.blockClient == nil {
var onceErr error
d.blockClientOnce.Do(func() {
clientConn, err := grpc.Dial(d.blockAddress, grpc.WithInsecure())
if err != nil {
onceErr = err
}
d.blockClient = pfs.NewBlockAPIClient(clientConn)
})
if onceErr != nil {
return nil, onceErr
}
}
return d.blockClient, nil
}
// isDBCreated is used to tell when we are trying to initialize a database,
// whether we are getting an error because the database has already been
// initialized.
func isDBCreated(err error) bool {
return strings.Contains(err.Error(), "Database") && strings.Contains(err.Error(), "already exists")
}
//InitDB is used to setup the database with the tables and indices that PFS requires
func InitDB(address string, dbName string) error {
session, err := DbConnect(address)
if err != nil {
return err
}
defer session.Close()
return initDB(session, dbName)
}
func initDB(session *gorethink.Session, dbName string) error {
_, err := gorethink.DBCreate(dbName).RunWrite(session)
if err != nil && !isDBCreated(err) {
return err
} else if err != nil && isDBCreated(err) {
// This function has already run so we abort.
return nil
}
// There is a race here
//
// When rethink is under load, we consistently fail on the table creation
// w a 'db not found' error right after we created it a few lines above.
//
// However, the db shows up fine in the dashboard, so it does in fact get
// created. This is only relevant for tests, because thats the only time
// we create a bunch of databases while R/W from rethink as well
config := backoff.NewExponentialBackOff()
// We want to backoff more aggressively (i.e. wait longer) than the default
config.InitialInterval = 1 * time.Second
config.Multiplier = 2
config.MaxElapsedTime = 5 * time.Minute
// Create tables
for _, table := range tables {
backoff.RetryNotify(func() error {
tableCreateOpts := tableToTableCreateOpts[table]
_, err := gorethink.DB(dbName).TableCreate(table, tableCreateOpts...).RunWrite(session)
return err
}, config, func(err error, d time.Duration) {
log.Errorf("error creating table %v on database %v; retrying in %s: %v\n", table, dbName, d, err)
})
}
// Create indexes
for _, someIndex := range Indexes {
if _, err := gorethink.DB(dbName).Table(someIndex.Table).IndexCreateFunc(someIndex.Name, someIndex.CreateFunction, someIndex.CreateOptions).RunWrite(session); err != nil {
return err
}
if _, err := gorethink.DB(dbName).Table(someIndex.Table).IndexWait(someIndex.Name).RunWrite(session); err != nil {
return err
}
}
return nil
}
// RemoveDB removes the tables in the database that are relavant to PFS
// It keeps the database around tho, as it might contain other tables that
// others created (e.g. PPS).
func RemoveDB(address string, dbName string) error {
session, err := DbConnect(address)
if err != nil {
return err
}
defer session.Close()
return removeDB(session, dbName)
}
func removeDB(session *gorethink.Session, dbName string) error {
for _, table := range tables {
if _, err := gorethink.DB(dbName).TableDrop(table).RunWrite(session); err != nil {
return err
}
}
return nil
}
// DbConnect returns a rethink DB session connected to the provided address
func DbConnect(address string) (*gorethink.Session, error) {
return gorethink.Connect(gorethink.ConnectOpts{
Address: address,
Timeout: connectTimeoutSeconds * time.Second,
MaxIdle: maxIdle,
MaxOpen: maxOpen,
})
}
func validateRepoName(name string) error {
match, _ := regexp.MatchString("^[a-zA-Z0-9_]+$", name)
if !match {
return fmt.Errorf("repo name (%v) invalid: only alphanumeric and underscore characters allowed", name)
}
return nil
}
func (d *driver) getTerm(table Table) gorethink.Term {
return gorethink.DB(d.dbName).Table(table)
}
func (d *driver) CreateRepo(repo *pfs.Repo, provenance []*pfs.Repo) error {
if repo == nil {
return fmt.Errorf("repo cannot be nil")
}
err := validateRepoName(repo.Name)
if err != nil {
return err
}
// Verify that all provenent repos exist
var provenantRepoNames []interface{}
var provenantIDs []string
for _, repo := range provenance {
provenantRepoNames = append(provenantRepoNames, repo.Name)
provenantIDs = append(provenantIDs, repo.Name)
}
var numProvenantRepos int
cursor, err := d.getTerm(repoTable).GetAll(provenantRepoNames...).Count().Run(d.dbClient)
if err != nil {
return err
}
if err := cursor.One(&numProvenantRepos); err != nil {
return err
}
if numProvenantRepos != len(provenance) {
return fmt.Errorf("could not create repo %v, not all provenance repos exist", repo.Name)
}
_, err = d.getTerm(repoTable).Insert(&persist.Repo{
Name: repo.Name,
Created: now(),
Provenance: provenantIDs,
}).RunWrite(d.dbClient)
if err != nil && gorethink.IsConflictErr(err) {
return fmt.Errorf("repo %v exists", repo.Name)
}
return err
}
func (d *driver) inspectRepo(repo *pfs.Repo) (r *persist.Repo, retErr error) {
defer func() {
if retErr == gorethink.ErrEmptyResult {
retErr = pfsserver.NewErrRepoNotFound(repo.Name)
}
}()
cursor, err := d.getTerm(repoTable).Get(repo.Name).Run(d.dbClient)
if err != nil {
return nil, err
}
rawRepo := &persist.Repo{}
if err := cursor.One(rawRepo); err != nil {
return nil, err
}
return rawRepo, nil
}
// byName sorts repos by name
type byName []*pfs.Repo
func (n byName) Len() int { return len(n) }
func (n byName) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
func (n byName) Less(i, j int) bool { return n[i].Name < n[j].Name }
func (d *driver) InspectRepo(repo *pfs.Repo) (*pfs.RepoInfo, error) {
rawRepo, err := d.inspectRepo(repo)
if err != nil {
return nil, err
}
// The full set of this repo's provenance, i.e. its immediate provenance
// plus the provenance of those repos.
fullProvenance := make(map[string]bool)
for _, repoName := range rawRepo.Provenance {
fullProvenance[repoName] = true
}
for _, repoName := range rawRepo.Provenance {
repoInfo, err := d.InspectRepo(&pfs.Repo{Name: repoName})
if err != nil {
return nil, err
}
for _, repo := range repoInfo.Provenance {
fullProvenance[repo.Name] = true
}
}
var provenance []*pfs.Repo
for repoName := range fullProvenance {
provenance = append(provenance, &pfs.Repo{
Name: repoName,
})
}
sort.Sort(byName(provenance))
return &pfs.RepoInfo{
Repo: &pfs.Repo{
Name: rawRepo.Name,
},
Created: rawRepo.Created,
SizeBytes: rawRepo.SizeBytes,
Provenance: provenance,
}, nil
}
func (d *driver) ListRepo(provenance []*pfs.Repo) (repoInfos []*pfs.RepoInfo, retErr error) {
cursor, err := d.getTerm(repoTable).OrderBy("Name").Run(d.dbClient)
if err != nil {
return nil, err
}
var repos []*persist.Repo
if err := cursor.All(&repos); err != nil {
return nil, err
}
nextRepo:
for _, repo := range repos {
if len(provenance) != 0 {
// Filter out the repos that don't have the given provenance
repoInfo, err := d.InspectRepo(&pfs.Repo{Name: repo.Name})
if err != nil {
return nil, err
}
for _, p := range provenance {
var found bool
for _, r := range repoInfo.Provenance {
if p.Name == r.Name {
found = true
break
}
}
if !found {
continue nextRepo
}
}
}
repoInfos = append(repoInfos, &pfs.RepoInfo{
Repo: &pfs.Repo{
Name: repo.Name,
},
Created: repo.Created,
SizeBytes: repo.SizeBytes,
})
}
return repoInfos, nil
}
func (d *driver) DeleteRepo(repo *pfs.Repo, force bool) error {
if !force {
// Make sure that this repo is not the provenance of any other repo
repoInfos, err := d.ListRepo([]*pfs.Repo{repo})
if err != nil {
return err
}
if len(repoInfos) > 0 {
var repoNames []string
for _, repoInfo := range repoInfos {
repoNames = append(repoNames, repoInfo.Repo.Name)
}
return fmt.Errorf("cannot delete repo %v; it's the provenance of the following repos: %v", repo.Name, repoNames)
}
}
// Deleting in the order of repo -> commits -> diffs seems to make sense,
// since if one can't see the repo, one can't see the commits; if they can't
// see the commits, they can't see the diffs. So in a way we are hiding
// potential inconsistency here.
_, err := d.getTerm(repoTable).Get(repo.Name).Delete().RunWrite(d.dbClient)
if err != nil {
return err
}
_, err = d.getTerm(commitTable).Filter(map[string]interface{}{
"Repo": repo.Name,
}).Delete().RunWrite(d.dbClient)
if err != nil {
return err
}
_, err = d.getTerm(diffTable).Filter(map[string]interface{}{
"Repo": repo.Name,
}).Delete().RunWrite(d.dbClient)
return err
}
func (d *driver) getFullProvenance(repo *pfs.Repo, provenance []*pfs.Commit) (fullProvenance []*persist.ProvenanceCommit, archived bool, err error) {
rawRepo, err := d.inspectRepo(repo)
if err != nil {
return nil, false, err
}
repoSet := make(map[string]bool)
for _, repoName := range rawRepo.Provenance {
repoSet[repoName] = true
}
for _, c := range provenance {
if !repoSet[c.Repo.Name] {
return nil, false, fmt.Errorf("cannot use %s/%s as provenance, %s is not provenance of %s", c.Repo.Name, c.ID, c.Repo.Name, repo.Name)
}
fullProvenance = append(fullProvenance, &persist.ProvenanceCommit{
ID: c.ID,
Repo: c.Repo.Name,
})
}
// We compute the complete set of provenance. That is, the provenance of this
// commit includes the provenance of its immediate provenance.
// This is so that running ListCommit with provenance is fast.
provenanceSet := make(map[string]*pfs.Commit)
for _, c := range provenance {
commitInfo, err := d.InspectCommit(c)
if err != nil {
return nil, false, err
}
// If any of the commit's provenance is archived, the commit should be
// archived
archived = archived || commitInfo.Archived
for _, p := range commitInfo.Provenance {
provenanceSet[fmt.Sprintf("%s:%s", p.Repo.Name, p.ID)] = p
}
}
for _, c := range provenanceSet {
fullProvenance = append(fullProvenance, &persist.ProvenanceCommit{
ID: c.ID,
Repo: c.Repo.Name,
})
}
return fullProvenance, archived, nil
}
func (d *driver) ForkCommit(parent *pfs.Commit, branch string, provenance []*pfs.Commit) (*pfs.Commit, error) {
fullProvenance, archived, err := d.getFullProvenance(parent.Repo, provenance)
if err != nil {
return nil, err
}
clock := persist.NewClock(branch)
commit := &persist.Commit{
ID: persist.NewCommitID(parent.Repo.Name, clock),
Repo: parent.Repo.Name,
Started: now(),
Provenance: fullProvenance,
Archived: archived,
}
parentCommit, err := d.getRawCommit(parent)
if err != nil {
return nil, err
}
commit.FullClock = append(parentCommit.FullClock, persist.NewClock(branch))
if err := d.insertMessage(commitTable, commit); err != nil {
if gorethink.IsConflictErr(err) {
return nil, pfsserver.NewErrCommitExists(commit.Repo, commit.ID)
}
return nil, err
}
return &pfs.Commit{
Repo: parent.Repo,
ID: clock.ReadableCommitID(),
}, nil
}
func isBranchName(id string) bool {
return !strings.Contains(id, "/")
}
func (d *driver) StartCommit(parent *pfs.Commit, provenance []*pfs.Commit) (*pfs.Commit, error) {
if parent.Repo.Name == "" || parent.ID == "" {
return nil, fmt.Errorf("Invalid parent commit: %s/%s", parent.Repo.Name, parent.ID)
}
fullProvenance, archived, err := d.getFullProvenance(parent.Repo, provenance)
if err != nil {
return nil, err
}
commit := &persist.Commit{
Repo: parent.Repo.Name,
Started: now(),
Provenance: fullProvenance,
Archived: archived,
}
var makeNewBranch bool
parentCommit, err := d.getRawCommit(parent)
if _, ok := err.(*pfsserver.ErrCommitNotFound); ok && isBranchName(parent.ID) {
makeNewBranch = true
} else if err == gorethink.ErrEmptyResult {
return nil, pfsserver.NewErrCommitNotFound(parent.Repo.Name, parent.ID)
} else if err != nil {
return nil, err
}
var clock *persist.Clock
if makeNewBranch {
branch := parent.ID
clock = persist.NewClock(branch)
commit.ID = persist.NewCommitID(parent.Repo.Name, clock)
commit.FullClock = append(commit.FullClock, clock)
} else {
commit.FullClock = persist.NewChild(parentCommit.FullClock)
clock = persist.FullClockHead(commit.FullClock)
commit.ID = persist.NewCommitID(parent.Repo.Name, clock)
}
if err := d.insertMessage(commitTable, commit); err != nil {
// TODO: there can be a race if two threads concurrently start commit
// using a branch name. We should automatically detect the race and retry.
if gorethink.IsConflictErr(err) {
return nil, pfsserver.NewErrCommitExists(commit.Repo, commit.ID)
}
return nil, err
}
return &pfs.Commit{
Repo: parent.Repo,
ID: clock.ReadableCommitID(),
}, nil
}
func getRawCommitID(repo string, readableCommitID string) (string, error) {
c, err := parseClock(readableCommitID)
if err != nil {
return "", err
}
return persist.NewCommitID(repo, c), nil
}
func (d *driver) getKey(i *index, desiredOutputDocument interface{}) ([]interface{}, error) {
cursor, err := gorethink.Expr(i.CreateFunction(gorethink.Expr(desiredOutputDocument))).Run(d.dbClient)
if err != nil {
return nil, err
}
var key []interface{}
err = cursor.All(&key)
if err != nil {
return nil, err
}
return key, nil
}
func (d *driver) getHeadOfBranch(repo string, branch string, retCommit *persist.Commit) error {
startCommit := &persist.Commit{
Repo: repo,
FullClock: []*persist.Clock{
&persist.Clock{
Branch: branch,
Clock: 0,
},
},
}
start, err := d.getKey(CommitClockIndex, startCommit)
if err != nil {
return err
}
endCommit := &persist.Commit{
Repo: repo,
FullClock: []*persist.Clock{
&persist.Clock{
Branch: branch,
Clock: 0,
},
&persist.Clock{
Branch: branch,
Clock: math.MaxUint64,
},
},
}
end, err := d.getKey(CommitClockIndex, endCommit)
if err != nil {
return err
}
cursor, err := d.betweenIndex(
commitTable, CommitClockIndex.Name,
start,
end,
true,
).Run(d.dbClient)
if err != nil {
return err
}
return cursor.One(retCommit)
}
func getClockID(repo string, c *persist.Clock) *persist.ClockID {
return &persist.ClockID{
ID: fmt.Sprintf("%s/%s/%d", repo, c.Branch, c.Clock),
Repo: repo,
Branch: c.Branch,
Clock: c.Clock,
}
}
// parseClock takes a string of the form "branch/clock"
// and returns a Clock object.
// For example:
// "master/0" -> Clock{"master", 0}
func parseClock(clock string) (*persist.Clock, error) {
parts := strings.Split(clock, "/")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid commit ID %s", clock)
}
c, err := strconv.Atoi(parts[1])
if err != nil {
return nil, fmt.Errorf("invalid commit ID %s", clock)
}
return &persist.Clock{
Branch: parts[0],
Clock: uint64(c),
}, nil
}
type commitChangeFeed struct {
NewVal *persist.Commit `gorethink:"new_val,omitempty"`
}
// Given a commitID (database primary key), compute the size of the commit
// using diffs.
func (d *driver) computeCommitSize(commit *persist.Commit) (uint64, error) {
head := persist.FullClockHead(commit.FullClock)
cursor, err := d.getTerm(diffTable).GetAllByIndex(
DiffClockIndex.Name,
diffClockIndexKey(commit.Repo, head.Branch, head.Clock),
).Reduce(func(left, right gorethink.Term) gorethink.Term {
return left.Merge(map[string]interface{}{
"SizeBytes": left.Field("SizeBytes").Add(right.Field("SizeBytes")),
})
}).Default(&persist.Diff{}).Run(d.dbClient)
if err != nil {
return 0, err
}
var diff persist.Diff
if err := cursor.One(&diff); err != nil {
return 0, err
}
return diff.SizeBytes, nil
}
// FinishCommit blocks until its parent has been finished/cancelled
func (d *driver) FinishCommit(commit *pfs.Commit, cancel bool) error {
// TODO: may want to optimize this. Not ideal to jump to DB to validate repo exists. This is required by error strings test in server_test.go
_, err := d.inspectRepo(commit.Repo)
if err != nil {
return err
}
rawCommit, err := d.getRawCommit(commit)
if err != nil {
return err
}
rawCommit.SizeBytes, err = d.computeCommitSize(rawCommit)
if err != nil {
return err
}
parentClock := persist.FullClockParent(rawCommit.FullClock)
var parentCancelled bool
if parentClock != nil {
parentID := persist.NewCommitID(rawCommit.Repo, persist.FullClockHead(parentClock))
cursor, err := d.getTerm(commitTable).Get(parentID).Changes(gorethink.ChangesOpts{
IncludeInitial: true,
}).Run(d.dbClient)
if err != nil {
return err
}
var change commitChangeFeed
for cursor.Next(&change) {
if change.NewVal != nil && change.NewVal.Finished != nil {
parentCancelled = change.NewVal.Cancelled
break
}
}
if err = cursor.Err(); err != nil {
return err
}
}
// Update the size of the repo. Note that there is a consistency issue here:
// If this transaction succeeds but the next one (updating Commit) fails,
// then the repo size will be wrong. TODO
_, err = d.getTerm(repoTable).Get(rawCommit.Repo).Update(map[string]interface{}{
"SizeBytes": gorethink.Row.Field("SizeBytes").Add(rawCommit.SizeBytes),
}).RunWrite(d.dbClient)
if err != nil {
return err
}
rawCommit.Finished = now()
rawCommit.Cancelled = parentCancelled || cancel
_, err = d.getTerm(commitTable).Get(rawCommit.ID).Update(rawCommit).RunWrite(d.dbClient)
return err
}
// ArchiveCommits archives the given commits and all commits that have any of the
// given commits as provenance
func (d *driver) ArchiveCommit(commits []*pfs.Commit) error {
var provenanceIDs []interface{}
for _, commit := range commits {
provenanceIDs = append(provenanceIDs, commit.ID)
}
var rawIDs []interface{}
for _, commit := range commits {
rawID, err := getRawCommitID(commit.Repo.Name, commit.ID)
if err != nil {
return err
}
rawIDs = append(rawIDs, rawID)
}
query := d.getTerm(commitTable).Filter(func(commit gorethink.Term) gorethink.Term {
// We want to select all commits that have any of the given commits as
// provenance
return gorethink.Or(commit.Field("Provenance").Field("ID").SetIntersection(gorethink.Expr(provenanceIDs)).Count().Ne(0), gorethink.Expr(rawIDs).Contains(commit.Field("ID")))
}).Update(map[string]interface{}{
"Archived": true,
})
_, err := query.RunWrite(d.dbClient)
if err != nil {
return err
}
return nil
}
func (d *driver) InspectCommit(commit *pfs.Commit) (*pfs.CommitInfo, error) {
rawCommit, err := d.getRawCommit(commit)
if err != nil {
return nil, err
}
commitInfo := d.rawCommitToCommitInfo(rawCommit)
if commitInfo.Finished == nil {
commitInfo.SizeBytes, err = d.computeCommitSize(rawCommit)
if err != nil {
return nil, err
}
}
return commitInfo, nil
}
func (d *driver) rawCommitToCommitInfo(rawCommit *persist.Commit) *pfs.CommitInfo {
commitType := pfs.CommitType_COMMIT_TYPE_READ
var branch string
if len(rawCommit.FullClock) > 0 {
branch = persist.FullClockBranch(rawCommit.FullClock)
}
if rawCommit.Finished == nil {
commitType = pfs.CommitType_COMMIT_TYPE_WRITE
}
var provenance []*pfs.Commit
for _, c := range rawCommit.Provenance {
provenance = append(provenance, &pfs.Commit{
Repo: &pfs.Repo{
Name: c.Repo,
},
ID: c.ID,
})
}
parentClock := persist.FullClockParent(rawCommit.FullClock)
var parentCommit *pfs.Commit
if parentClock != nil {
parentCommit = &pfs.Commit{
Repo: &pfs.Repo{
Name: rawCommit.Repo,
},
ID: persist.FullClockHead(parentClock).ReadableCommitID(),
}
}
return &pfs.CommitInfo{
Commit: &pfs.Commit{
Repo: &pfs.Repo{
Name: rawCommit.Repo,
},
ID: persist.FullClockHead(rawCommit.FullClock).ReadableCommitID(),
},
Branch: branch,
Started: rawCommit.Started,
Finished: rawCommit.Finished,
Cancelled: rawCommit.Cancelled,
Archived: rawCommit.Archived,
CommitType: commitType,
SizeBytes: rawCommit.SizeBytes,
ParentCommit: parentCommit,
Provenance: provenance,
}
}
func (d *driver) ListCommit(include []*pfs.Commit, exclude []*pfs.Commit, provenance []*pfs.Commit, commitType pfs.CommitType, status pfs.CommitStatus, block bool) ([]*pfs.CommitInfo, error) {
repoToQuery := make(map[string]gorethink.Term)
for i, commit := range append(include, exclude...) {
// make sure that the repos exist
_, err := d.inspectRepo(commit.Repo)
if err != nil {
return nil, err
}
query, ok := repoToQuery[commit.Repo.Name]
if !ok {
query = d.getTerm(commitTable).OrderBy(gorethink.OrderByOpts{
Index: CommitFullClockIndex.Name,
}).Filter(map[string]interface{}{
"Repo": commit.Repo.Name,
})
repoToQuery[commit.Repo.Name] = query
}
if commit.ID == "" {
continue
}
fullClock, err := d.getFullClock(commit)
if err != nil {
return nil, err
}
if i < len(include) {
query = query.Filter(func(r gorethink.Term) gorethink.Term {
return persist.DBClockAncestor(r.Field("FullClock"), gorethink.Expr(fullClock))
})
} else {
query = query.Filter(func(r gorethink.Term) gorethink.Term {
return gorethink.Not(persist.DBClockAncestor(r.Field("FullClock"), gorethink.Expr(fullClock)))
})
}
repoToQuery[commit.Repo.Name] = query
}
var queries []interface{}
for _, query := range repoToQuery {
queries = append(queries, query)
}
var query gorethink.Term
if len(queries) > 0 {
query = gorethink.Union(queries...)
} else {
query = d.getTerm(commitTable).OrderBy(gorethink.OrderByOpts{
Index: CommitFullClockIndex.Name,
})
}
if status != pfs.CommitStatus_ALL && status != pfs.CommitStatus_CANCELLED {
query = query.Filter(map[string]interface{}{
"Cancelled": false,
})
}
if status != pfs.CommitStatus_ALL && status != pfs.CommitStatus_ARCHIVED {
query = query.Filter(map[string]interface{}{
"Archived": false,
})
}
switch commitType {
case pfs.CommitType_COMMIT_TYPE_READ:
query = query.Filter(func(commit gorethink.Term) gorethink.Term {
return commit.Field("Finished").Ne(nil)
})
case pfs.CommitType_COMMIT_TYPE_WRITE:
query = query.Filter(func(commit gorethink.Term) gorethink.Term {
return commit.Field("Finished").Eq(nil)
})
}
var provenanceIDs []interface{}
for _, commit := range provenance {
// TODO: we need to validate the provenanceIDs: 1) they must actually
// exist, and 2) they can't be just branch names
provenanceIDs = append(provenanceIDs, &persist.ProvenanceCommit{
ID: commit.ID,
Repo: commit.Repo.Name,
})
}
if provenanceIDs != nil {
query = query.Filter(func(commit gorethink.Term) gorethink.Term {
return commit.Field("Provenance").Contains(provenanceIDs...)
})
}
cursor, err := query.Run(d.dbClient)
if err != nil {
return nil, err
}
var commits []*persist.Commit
if err := cursor.All(&commits); err != nil {
return nil, err
}
var commitInfos []*pfs.CommitInfo
if len(commits) > 0 {
for _, commit := range commits {
commitInfos = append(commitInfos, d.rawCommitToCommitInfo(commit))
}
} else if block {
query = query.Changes(gorethink.ChangesOpts{
IncludeInitial: true,
}).Field("new_val")
cursor, err := query.Run(d.dbClient)
if err != nil {
return nil, err
}
var commit persist.Commit
cursor.Next(&commit)
if err := cursor.Err(); err != nil {
return nil, err
}
commitInfos = append(commitInfos, d.rawCommitToCommitInfo(&commit))
}
return commitInfos, nil
}
func (d *driver) FlushCommit(fromCommits []*pfs.Commit, toRepos []*pfs.Repo) ([]*pfs.CommitInfo, error) {
var result []*pfs.CommitInfo
repoSet1 := make(map[string]bool)
repoToProvenance := make(map[string][]*persist.ProvenanceCommit)
for _, commit := range fromCommits {
rawCommit, err := d.getRawCommit(commit)
if err != nil {
return nil, err
}
// always include fromCommits themselves in the result
result = append(result, d.rawCommitToCommitInfo(rawCommit))
repoInfos, err := d.ListRepo([]*pfs.Repo{commit.Repo})
if err != nil {
return nil, err
}
for _, repoInfo := range repoInfos {
repoSet1[repoInfo.Repo.Name] = true
repoToProvenance[repoInfo.Repo.Name] = append(repoToProvenance[repoInfo.Repo.Name], &persist.ProvenanceCommit{
Repo: commit.Repo.Name,
// We can't just use commit.ID directly because it might be a
// branch name instead of a commitID
ID: persist.FullClockHead(rawCommit.FullClock).ReadableCommitID(),
})
}
}
repoSet2 := make(map[string]bool)
for _, repo := range toRepos {
repoInfo, err := d.InspectRepo(repo)
if err != nil {
return nil, err
}
for _, repo := range repoInfo.Provenance {
repoSet2[repo.Name] = true
}
repoSet2[repo.Name] = true
}
// The list of the repos that we care about.
var repos []string
for repoName := range repoSet1 {
if len(repoSet2) == 0 || repoSet2[repoName] {
repos = append(repos, repoName)
}
}