forked from moby/buildkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jobs.go
1257 lines (1110 loc) · 30 KB
/
jobs.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 solver
import (
"context"
"fmt"
"sync"
"time"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/identity"
"github.com/moby/buildkit/session"
"github.com/moby/buildkit/solver/errdefs"
"github.com/moby/buildkit/util/bklog"
"github.com/moby/buildkit/util/flightcontrol"
"github.com/moby/buildkit/util/progress"
"github.com/moby/buildkit/util/progress/controller"
"github.com/moby/buildkit/util/tracing"
digest "github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"go.opentelemetry.io/otel/trace/noop"
)
// ResolveOpFunc finds an Op implementation for a Vertex
type ResolveOpFunc func(Vertex, Builder) (Op, error)
type Builder interface {
Build(ctx context.Context, e Edge) (CachedResultWithProvenance, error)
InContext(ctx context.Context, f func(ctx context.Context, g session.Group) error) error
EachValue(ctx context.Context, key string, fn func(interface{}) error) error
}
// Solver provides a shared graph of all the vertexes currently being
// processed. Every vertex that is being solved needs to be loaded into job
// first. Vertex operations are invoked and progress tracking happens through
// jobs.
type Solver struct {
mu sync.RWMutex
jobs map[string]*Job
actives map[digest.Digest]*state
opts SolverOpt
updateCond *sync.Cond
s *scheduler
index *edgeIndex
}
type state struct {
jobs map[*Job]struct{}
parents map[digest.Digest]struct{}
childVtx map[digest.Digest]struct{}
mpw *progress.MultiWriter
allPw map[progress.Writer]struct{}
mspan *tracing.MultiSpan
vtx Vertex
clientVertex client.Vertex
origDigest digest.Digest // original LLB digest. TODO: probably better to use string ID so this isn't needed
mu sync.Mutex
op *sharedOp
edges map[Index]*edge
opts SolverOpt
index *edgeIndex
cache map[string]CacheManager
mainCache CacheManager
solver *Solver
}
func (s *state) SessionIterator() session.Iterator {
return s.sessionIterator()
}
func (s *state) sessionIterator() *sessionGroup {
return &sessionGroup{state: s, visited: map[string]struct{}{}}
}
type sessionGroup struct {
*state
visited map[string]struct{}
parents []session.Iterator
mode int
}
func (g *sessionGroup) NextSession() string {
if g.mode == 0 {
g.mu.Lock()
for j := range g.jobs {
if j.SessionID != "" {
if _, ok := g.visited[j.SessionID]; ok {
continue
}
g.visited[j.SessionID] = struct{}{}
g.mu.Unlock()
return j.SessionID
}
}
g.mu.Unlock()
g.mode = 1
}
if g.mode == 1 {
parents := map[digest.Digest]struct{}{}
g.mu.Lock()
for p := range g.state.parents {
parents[p] = struct{}{}
}
g.mu.Unlock()
for p := range parents {
g.solver.mu.Lock()
pst, ok := g.solver.actives[p]
g.solver.mu.Unlock()
if ok {
gg := pst.sessionIterator()
gg.visited = g.visited
g.parents = append(g.parents, gg)
}
}
g.mode = 2
}
for {
if len(g.parents) == 0 {
return ""
}
p := g.parents[0]
id := p.NextSession()
if id != "" {
return id
}
g.parents = g.parents[1:]
}
}
func (s *state) builder() *subBuilder {
return &subBuilder{state: s}
}
func (s *state) getEdge(index Index) *edge {
s.mu.Lock()
defer s.mu.Unlock()
if e, ok := s.edges[index]; ok {
for e.owner != nil {
e = e.owner
}
return e
}
if s.op == nil {
s.op = newSharedOp(s.opts.ResolveOpFunc, s)
}
e := newEdge(Edge{Index: index, Vertex: s.vtx}, s.op, s.index)
s.edges[index] = e
return e
}
func (s *state) setEdge(index Index, targetEdge *edge, targetState *state) {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.edges[index]
if ok {
for e.owner != nil {
e = e.owner
}
if e == targetEdge {
return
}
} else {
e = newEdge(Edge{Index: index, Vertex: s.vtx}, s.op, s.index)
s.edges[index] = e
}
targetEdge.takeOwnership(e)
if targetState != nil {
targetState.addJobs(s, map[*state]struct{}{})
if _, ok := targetState.allPw[s.mpw]; !ok {
targetState.mpw.Add(s.mpw)
targetState.allPw[s.mpw] = struct{}{}
}
}
}
// addJobs recursively adds jobs to state and all its ancestors. currently
// only used during edge merges to add jobs from the source of the merge to the
// target and its ancestors.
// requires that Solver.mu is read-locked and srcState.mu is locked
func (s *state) addJobs(srcState *state, memo map[*state]struct{}) {
if _, ok := memo[s]; ok {
return
}
memo[s] = struct{}{}
s.mu.Lock()
defer s.mu.Unlock()
for j := range srcState.jobs {
s.jobs[j] = struct{}{}
}
for _, inputEdge := range s.vtx.Inputs() {
inputState, ok := s.solver.actives[inputEdge.Vertex.Digest()]
if !ok {
bklog.G(context.TODO()).
WithField("vertex_digest", inputEdge.Vertex.Digest()).
Error("input vertex not found during addJobs")
continue
}
inputState.addJobs(srcState, memo)
// tricky case: if the inputState's edge was *already* merged we should
// also add jobs to the merged edge's state
mergedInputEdge := inputState.getEdge(inputEdge.Index)
if mergedInputEdge == nil || mergedInputEdge.edge.Vertex.Digest() == inputEdge.Vertex.Digest() {
// not merged
continue
}
mergedInputState, ok := s.solver.actives[mergedInputEdge.edge.Vertex.Digest()]
if !ok {
bklog.G(context.TODO()).
WithField("vertex_digest", mergedInputEdge.edge.Vertex.Digest()).
Error("merged input vertex not found during addJobs")
continue
}
mergedInputState.addJobs(srcState, memo)
}
}
func (s *state) combinedCacheManager() CacheManager {
s.mu.Lock()
cms := make([]CacheManager, 0, len(s.cache)+1)
cms = append(cms, s.mainCache)
for _, cm := range s.cache {
cms = append(cms, cm)
}
s.mu.Unlock()
if len(cms) == 1 {
return s.mainCache
}
return NewCombinedCacheManager(cms, s.mainCache)
}
func (s *state) Release() {
for _, e := range s.edges {
for e.owner != nil {
e = e.owner
}
e.release()
}
if s.op != nil {
s.op.release()
}
}
type subBuilder struct {
*state
mu sync.Mutex
exporters []ExportableCacheKey
}
func (sb *subBuilder) Build(ctx context.Context, e Edge) (CachedResultWithProvenance, error) {
res, err := sb.solver.subBuild(ctx, e, sb.vtx)
if err != nil {
return nil, err
}
sb.mu.Lock()
sb.exporters = append(sb.exporters, res.CacheKeys()[0]) // all keys already have full export chain
sb.mu.Unlock()
return &withProvenance{CachedResult: res}, nil
}
func (sb *subBuilder) InContext(ctx context.Context, f func(context.Context, session.Group) error) error {
ctx = progress.WithProgress(ctx, sb.mpw)
if sb.mspan.Span != nil {
ctx = trace.ContextWithSpan(ctx, sb.mspan)
}
return f(ctx, sb.state)
}
func (sb *subBuilder) EachValue(ctx context.Context, key string, fn func(interface{}) error) error {
sb.mu.Lock()
defer sb.mu.Unlock()
for j := range sb.jobs {
if err := j.EachValue(ctx, key, fn); err != nil {
return err
}
}
return nil
}
type Job struct {
list *Solver
pr *progress.MultiReader
pw progress.Writer
span trace.Span
values sync.Map
id string
startedTime time.Time
completedTime time.Time
progressCloser func(error)
SessionID string
uniqueID string // unique ID is used for provenance. We use a different field that client can't control
}
type SolverOpt struct {
ResolveOpFunc ResolveOpFunc
DefaultCache CacheManager
}
func NewSolver(opts SolverOpt) *Solver {
if opts.DefaultCache == nil {
opts.DefaultCache = NewInMemoryCacheManager()
}
jl := &Solver{
jobs: make(map[string]*Job),
actives: make(map[digest.Digest]*state),
opts: opts,
index: newEdgeIndex(),
}
jl.s = newScheduler(jl)
jl.updateCond = sync.NewCond(jl.mu.RLocker())
return jl
}
// hasOwner returns true if the provided target edge (or any of it's sibling
// edges) has the provided owner.
func (jl *Solver) hasOwner(target Edge, owner Edge) bool {
jl.mu.RLock()
defer jl.mu.RUnlock()
st, ok := jl.actives[target.Vertex.Digest()]
if !ok {
return false
}
var owners []Edge
for _, e := range st.edges {
if e.owner != nil {
owners = append(owners, e.owner.edge)
}
}
for len(owners) > 0 {
var owners2 []Edge
for _, e := range owners {
st, ok = jl.actives[e.Vertex.Digest()]
if !ok {
continue
}
if st.vtx.Digest() == owner.Vertex.Digest() {
return true
}
for _, e := range st.edges {
if e.owner != nil {
owners2 = append(owners2, e.owner.edge)
}
}
}
// repeat recursively, this time with the linked owners owners
owners = owners2
}
return false
}
func (jl *Solver) setEdge(e Edge, targetEdge *edge) {
jl.mu.RLock()
defer jl.mu.RUnlock()
st, ok := jl.actives[e.Vertex.Digest()]
if !ok {
return
}
// potentially passing nil targetSt is intentional and handled in st.setEdge
targetSt := jl.actives[targetEdge.edge.Vertex.Digest()]
st.setEdge(e.Index, targetEdge, targetSt)
}
func (jl *Solver) getState(e Edge) *state {
jl.mu.RLock()
defer jl.mu.RUnlock()
st, ok := jl.actives[e.Vertex.Digest()]
if !ok {
return nil
}
return st
}
func (jl *Solver) getEdge(e Edge) (redge *edge) {
if debugScheduler {
defer func() {
lg := bklog.G(context.TODO()).
WithField("edge_vertex_name", e.Vertex.Name()).
WithField("edge_vertex_digest", e.Vertex.Digest()).
WithField("edge_index", e.Index)
if redge != nil {
lg = lg.
WithField("return_edge_vertex_name", redge.edge.Vertex.Name()).
WithField("return_edge_vertex_digest", redge.edge.Vertex.Digest()).
WithField("return_edge_index", redge.edge.Index)
}
lg.Debug("getEdge return")
}()
}
jl.mu.RLock()
defer jl.mu.RUnlock()
st, ok := jl.actives[e.Vertex.Digest()]
if !ok {
return nil
}
return st.getEdge(e.Index)
}
func (jl *Solver) subBuild(ctx context.Context, e Edge, parent Vertex) (CachedResult, error) {
v, err := jl.load(ctx, e.Vertex, parent, nil)
if err != nil {
return nil, err
}
e.Vertex = v
return jl.s.build(ctx, e)
}
func (jl *Solver) Close() {
jl.s.Stop()
}
func (jl *Solver) load(ctx context.Context, v, parent Vertex, j *Job) (Vertex, error) {
jl.mu.Lock()
defer jl.mu.Unlock()
cache := map[Vertex]Vertex{}
return jl.loadUnlocked(ctx, v, parent, j, cache)
}
// called with solver lock
func (jl *Solver) loadUnlocked(ctx context.Context, v, parent Vertex, j *Job, cache map[Vertex]Vertex) (Vertex, error) {
if v, ok := cache[v]; ok {
return v, nil
}
origVtx := v
inputs := make([]Edge, len(v.Inputs()))
for i, e := range v.Inputs() {
v, err := jl.loadUnlocked(ctx, e.Vertex, parent, j, cache)
if err != nil {
return nil, err
}
inputs[i] = Edge{Index: e.Index, Vertex: v}
}
dgst := v.Digest()
dgstWithoutCache := digest.FromBytes([]byte(fmt.Sprintf("%s-ignorecache", dgst)))
// if same vertex is already loaded without cache just use that
st, ok := jl.actives[dgstWithoutCache]
if ok {
// When matching an existing active vertext by dgstWithoutCache, set v to the
// existing active vertex, as otherwise the original vertex will use an
// incorrect digest and can incorrectly delete it while it is still in use.
v = st.vtx
}
if !ok {
st, ok = jl.actives[dgst]
// !ignorecache merges with ignorecache but ignorecache doesn't merge with !ignorecache
if ok && !st.vtx.Options().IgnoreCache && v.Options().IgnoreCache {
dgst = dgstWithoutCache
}
v = &vertexWithCacheOptions{
Vertex: v,
dgst: dgst,
inputs: inputs,
}
st, ok = jl.actives[dgst]
}
if !ok {
st = &state{
opts: jl.opts,
jobs: map[*Job]struct{}{},
parents: map[digest.Digest]struct{}{},
childVtx: map[digest.Digest]struct{}{},
allPw: map[progress.Writer]struct{}{},
mpw: progress.NewMultiWriter(progress.WithMetadata("vertex", dgst)),
mspan: tracing.NewMultiSpan(),
vtx: v,
clientVertex: initClientVertex(v),
edges: map[Index]*edge{},
index: jl.index,
mainCache: jl.opts.DefaultCache,
cache: map[string]CacheManager{},
solver: jl,
origDigest: origVtx.Digest(),
}
jl.actives[dgst] = st
if debugScheduler {
lg := bklog.G(ctx).
WithField("vertex_name", v.Name()).
WithField("vertex_digest", v.Digest()).
WithField("actives_digest_key", dgst)
if j != nil {
lg = lg.WithField("job", j.id)
}
lg.Debug("adding active vertex")
for i, inp := range v.Inputs() {
lg.WithField("input_index", i).
WithField("input_vertex_name", inp.Vertex.Name()).
WithField("input_vertex_digest", inp.Vertex.Digest()).
WithField("input_edge_index", inp.Index).
Debug("new active vertex input")
}
}
} else if debugScheduler {
lg := bklog.G(ctx).
WithField("vertex_name", v.Name()).
WithField("vertex_digest", v.Digest()).
WithField("actives_digest_key", dgst)
if j != nil {
lg = lg.WithField("job", j.id)
}
lg.Debug("reusing active vertex")
}
st.mu.Lock()
for _, cache := range v.Options().CacheSources {
if cache.ID() != st.mainCache.ID() {
if _, ok := st.cache[cache.ID()]; !ok {
st.cache[cache.ID()] = cache
}
}
}
if j != nil {
if _, ok := st.jobs[j]; !ok {
st.jobs[j] = struct{}{}
}
}
st.mu.Unlock()
if parent != nil {
if _, ok := st.parents[parent.Digest()]; !ok {
st.parents[parent.Digest()] = struct{}{}
parentState, ok := jl.actives[parent.Digest()]
if !ok {
return nil, errors.Errorf("inactive parent %s", parent.Digest())
}
parentState.childVtx[dgst] = struct{}{}
for id, c := range parentState.cache {
st.cache[id] = c
}
}
}
jl.connectProgressFromState(st, st)
cache[origVtx] = v
return v, nil
}
func (jl *Solver) connectProgressFromState(target, src *state) {
for j := range src.jobs {
if _, ok := target.allPw[j.pw]; !ok {
target.mpw.Add(j.pw)
target.allPw[j.pw] = struct{}{}
j.pw.Write(identity.NewID(), target.clientVertex)
if j.span != nil && j.span.SpanContext().IsValid() {
target.mspan.Add(j.span)
}
}
}
for p := range src.parents {
jl.connectProgressFromState(target, jl.actives[p])
}
}
func (jl *Solver) NewJob(id string) (*Job, error) {
jl.mu.Lock()
defer jl.mu.Unlock()
if _, ok := jl.jobs[id]; ok {
return nil, errors.Errorf("job ID %s exists", id)
}
pr, ctx, progressCloser := progress.NewContext(context.Background())
pw, _, _ := progress.NewFromContext(ctx) // TODO: expose progress.Pipe()
_, span := noop.NewTracerProvider().Tracer("").Start(ctx, "")
j := &Job{
list: jl,
pr: progress.NewMultiReader(pr),
pw: pw,
progressCloser: progressCloser,
span: span,
id: id,
startedTime: time.Now(),
uniqueID: identity.NewID(),
}
jl.jobs[id] = j
jl.updateCond.Broadcast()
return j, nil
}
func (jl *Solver) Get(id string) (*Job, error) {
ctx, cancel := context.WithCancelCause(context.Background())
ctx, _ = context.WithTimeoutCause(ctx, 6*time.Second, errors.WithStack(context.DeadlineExceeded))
defer cancel(errors.WithStack(context.Canceled))
go func() {
<-ctx.Done()
jl.mu.Lock()
jl.updateCond.Broadcast()
jl.mu.Unlock()
}()
jl.mu.RLock()
defer jl.mu.RUnlock()
for {
select {
case <-ctx.Done():
return nil, errdefs.NewUnknownJobError(id)
default:
}
j, ok := jl.jobs[id]
if !ok {
jl.updateCond.Wait()
continue
}
return j, nil
}
}
// called with solver lock
func (jl *Solver) deleteIfUnreferenced(k digest.Digest, st *state) {
if len(st.jobs) == 0 && len(st.parents) == 0 {
if debugScheduler {
bklog.G(context.TODO()).
WithField("vertex_name", st.vtx.Name()).
WithField("vertex_digest", st.vtx.Digest()).
WithField("actives_key", k).
Debug("deleting unreferenced active vertex")
for _, e := range st.edges {
bklog.G(context.TODO()).
WithField("vertex_name", e.edge.Vertex.Name()).
WithField("vertex_digest", e.edge.Vertex.Digest()).
WithField("index", e.edge.Index).
WithField("state", e.state).
Debug("edge in deleted unreferenced state")
}
}
for chKey := range st.childVtx {
chState := jl.actives[chKey]
delete(chState.parents, k)
jl.deleteIfUnreferenced(chKey, chState)
}
st.Release()
delete(jl.actives, k)
} else if debugScheduler {
var jobIDs []string
for j := range st.jobs {
jobIDs = append(jobIDs, j.id)
}
bklog.G(context.TODO()).
WithField("vertex_name", st.vtx.Name()).
WithField("vertex_digest", st.vtx.Digest()).
WithField("actives_key", k).
WithField("jobs", jobIDs).
Debug("not deleting referenced active vertex")
}
}
func (j *Job) Build(ctx context.Context, e Edge) (CachedResultWithProvenance, error) {
if span := trace.SpanFromContext(ctx); span.SpanContext().IsValid() {
j.span = span
}
v, err := j.list.load(ctx, e.Vertex, nil, j)
if err != nil {
return nil, err
}
e.Vertex = v
res, err := j.list.s.build(ctx, e)
if err != nil {
return nil, err
}
return &withProvenance{CachedResult: res, j: j, e: e}, nil
}
type withProvenance struct {
CachedResult
j *Job
e Edge
}
func (wp *withProvenance) WalkProvenance(ctx context.Context, f func(ProvenanceProvider) error) error {
if wp.j == nil {
return nil
}
wp.j.list.mu.RLock()
defer wp.j.list.mu.RUnlock()
m := map[digest.Digest]struct{}{}
return wp.j.walkProvenance(ctx, wp.e, f, m)
}
// called with solver lock
func (j *Job) walkProvenance(ctx context.Context, e Edge, f func(ProvenanceProvider) error, visited map[digest.Digest]struct{}) error {
if _, ok := visited[e.Vertex.Digest()]; ok {
return nil
}
visited[e.Vertex.Digest()] = struct{}{}
if st, ok := j.list.actives[e.Vertex.Digest()]; ok {
st.mu.Lock()
if wp, ok := st.op.op.(ProvenanceProvider); ok {
if err := f(wp); err != nil {
st.mu.Unlock()
return err
}
}
st.mu.Unlock()
}
for _, inp := range e.Vertex.Inputs() {
if err := j.walkProvenance(ctx, inp, f, visited); err != nil {
return err
}
}
return nil
}
func (j *Job) CloseProgress() {
j.progressCloser(errors.WithStack(context.Canceled))
j.pw.Close()
}
func (j *Job) Discard() error {
j.list.mu.Lock()
defer j.list.mu.Unlock()
j.pw.Close()
for k, st := range j.list.actives {
st.mu.Lock()
if _, ok := st.jobs[j]; ok {
if debugScheduler {
bklog.G(context.TODO()).
WithField("job", j.id).
WithField("vertex_name", st.vtx.Name()).
WithField("vertex_digest", st.vtx.Digest()).
WithField("actives_key", k).
Debug("deleting job from state")
}
delete(st.jobs, j)
j.list.deleteIfUnreferenced(k, st)
}
delete(st.allPw, j.pw)
st.mu.Unlock()
}
go func() {
// don't clear job right away. there might still be a status request coming to read progress
time.Sleep(10 * time.Second)
j.list.mu.Lock()
defer j.list.mu.Unlock()
delete(j.list.jobs, j.id)
}()
return nil
}
func (j *Job) StartedTime() time.Time {
return j.startedTime
}
func (j *Job) RegisterCompleteTime() time.Time {
if j.completedTime.IsZero() {
j.completedTime = time.Now()
}
return j.completedTime
}
func (j *Job) UniqueID() string {
return j.uniqueID
}
func (j *Job) InContext(ctx context.Context, f func(context.Context, session.Group) error) error {
return f(progress.WithProgress(ctx, j.pw), session.NewGroup(j.SessionID))
}
func (j *Job) SetValue(key string, v interface{}) {
j.values.Store(key, v)
}
func (j *Job) EachValue(ctx context.Context, key string, fn func(interface{}) error) error {
v, ok := j.values.Load(key)
if ok {
return fn(v)
}
return nil
}
type cacheMapResp struct {
*CacheMap
complete bool
}
type activeOp interface {
CacheMap(context.Context, int) (*cacheMapResp, error)
LoadCache(ctx context.Context, rec *CacheRecord) (Result, error)
Exec(ctx context.Context, inputs []Result) (outputs []Result, exporters []ExportableCacheKey, err error)
IgnoreCache() bool
Cache() CacheManager
CalcSlowCache(context.Context, Index, PreprocessFunc, ResultBasedCacheFunc, Result) (digest.Digest, error)
}
func newSharedOp(resolver ResolveOpFunc, st *state) *sharedOp {
so := &sharedOp{
resolver: resolver,
st: st,
slowCacheRes: map[Index]digest.Digest{},
slowCacheErr: map[Index]error{},
}
return so
}
type execRes struct {
execRes []*SharedResult
execExporters []ExportableCacheKey
}
type sharedOp struct {
resolver ResolveOpFunc
st *state
gDigest flightcontrol.Group[digest.Digest]
gCacheRes flightcontrol.Group[[]*CacheMap]
gExecRes flightcontrol.Group[*execRes]
opOnce sync.Once
op Op
subBuilder *subBuilder
err error
execRes *execRes
execDone bool
execErr error
cacheRes []*CacheMap
cacheDone bool
cacheErr error
slowMu sync.Mutex
slowCacheRes map[Index]digest.Digest
slowCacheErr map[Index]error
}
func (s *sharedOp) IgnoreCache() bool {
return s.st.vtx.Options().IgnoreCache
}
func (s *sharedOp) Cache() CacheManager {
return &cacheWithCacheOpts{s.st.combinedCacheManager(), s.st}
}
type cacheWithCacheOpts struct {
CacheManager
st *state
}
func (c cacheWithCacheOpts) Records(ctx context.Context, ck *CacheKey) ([]*CacheRecord, error) {
// Allow Records accessing to cache opts through ctx. This enable to use remote provider
// during checking the cache existence.
return c.CacheManager.Records(withAncestorCacheOpts(ctx, c.st), ck)
}
func (s *sharedOp) LoadCache(ctx context.Context, rec *CacheRecord) (Result, error) {
ctx = progress.WithProgress(ctx, s.st.mpw)
if s.st.mspan.Span != nil {
ctx = trace.ContextWithSpan(ctx, s.st.mspan)
}
// no cache hit. start evaluating the node
span, ctx := tracing.StartSpan(ctx, "load cache: "+s.st.vtx.Name(), trace.WithAttributes(attribute.String("vertex", s.st.vtx.Digest().String())))
notifyCompleted := notifyStarted(ctx, &s.st.clientVertex, true)
res, err := s.Cache().Load(withAncestorCacheOpts(ctx, s.st), rec)
tracing.FinishWithError(span, err)
notifyCompleted(err, true)
return res, err
}
// CalcSlowCache computes the digest of an input that is ready and has been
// evaluated, hence "slow" cache.
func (s *sharedOp) CalcSlowCache(ctx context.Context, index Index, p PreprocessFunc, f ResultBasedCacheFunc, res Result) (dgst digest.Digest, err error) {
defer func() {
err = WrapSlowCache(err, index, NewSharedResult(res).Clone())
err = errdefs.WithOp(err, s.st.vtx.Sys())
err = errdefs.WrapVertex(err, s.st.origDigest)
}()
flightControlKey := fmt.Sprintf("slow-compute-%d", index)
key, err := s.gDigest.Do(ctx, flightControlKey, func(ctx context.Context) (digest.Digest, error) {
s.slowMu.Lock()
// TODO: add helpers for these stored values
if res, ok := s.slowCacheRes[index]; ok {
s.slowMu.Unlock()
return res, nil
}
if err := s.slowCacheErr[index]; err != nil {
s.slowMu.Unlock()
return "", err
}
s.slowMu.Unlock()
complete := true
if p != nil {
st := s.st.solver.getState(s.st.vtx.Inputs()[index])
if st == nil {
return "", errors.Errorf("failed to get state for index %d on %v", index, s.st.vtx.Name())
}
ctx2 := progress.WithProgress(ctx, st.mpw)
if st.mspan.Span != nil {
ctx2 = trace.ContextWithSpan(ctx2, st.mspan)
}
err = p(ctx2, res, st)
if err != nil {
f = nil
ctx = ctx2
}
}
var key digest.Digest
if f != nil {
ctx = progress.WithProgress(ctx, s.st.mpw)
if s.st.mspan.Span != nil {
ctx = trace.ContextWithSpan(ctx, s.st.mspan)
}
key, err = f(withAncestorCacheOpts(ctx, s.st), res, s.st)
}
if err != nil {
select {
case <-ctx.Done():
if errdefs.IsCanceled(ctx, err) {
complete = false
releaseError(err)
err = errors.Wrap(context.Cause(ctx), err.Error())
}
default:
}
}
s.slowMu.Lock()
defer s.slowMu.Unlock()
if complete {
if err == nil {
s.slowCacheRes[index] = key
}
s.slowCacheErr[index] = err
}
return key, err
})
if err != nil {
ctx = progress.WithProgress(ctx, s.st.mpw)
if s.st.mspan.Span != nil {
ctx = trace.ContextWithSpan(ctx, s.st.mspan)
}
notifyCompleted := notifyStarted(ctx, &s.st.clientVertex, false)
notifyCompleted(err, false)
return "", err
}
return key, nil
}
func (s *sharedOp) CacheMap(ctx context.Context, index int) (resp *cacheMapResp, err error) {
defer func() {
err = errdefs.WithOp(err, s.st.vtx.Sys())
err = errdefs.WrapVertex(err, s.st.origDigest)
}()
op, err := s.getOp()
if err != nil {
return nil, err
}
flightControlKey := fmt.Sprintf("cachemap-%d", index)
res, err := s.gCacheRes.Do(ctx, flightControlKey, func(ctx context.Context) (ret []*CacheMap, retErr error) {