-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathresolver.go
108 lines (91 loc) · 2.39 KB
/
resolver.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
package codegen
import (
"context"
"sync"
"github.com/docker/buildx/util/progress"
"github.com/moby/buildkit/client"
"github.com/moby/buildkit/client/llb"
"github.com/moby/buildkit/client/llb/sourceresolver"
gateway "github.com/moby/buildkit/frontend/gateway/client"
digest "github.com/opencontainers/go-digest"
"github.com/openllb/hlb/parser/ast"
"github.com/openllb/hlb/pkg/llbutil"
"github.com/openllb/hlb/solver"
"golang.org/x/sync/errgroup"
)
const (
// ModuleFilename is the filename of the HLB module expected to be in the
// solved filesystem provided to the import declaration.
ModuleFilename = "module.hlb"
)
// Resolver resolves imports into a reader ready for parsing and checking.
type Resolver interface {
// Resolve returns a reader for the HLB module and its compiled LLB.
Resolve(ctx context.Context, id *ast.ImportDecl, fs Filesystem) (ast.Directory, error)
}
func NewCachedImageResolver(cln *client.Client) llb.ImageMetaResolver {
return &cachedImageResolver{
cln: cln,
cache: make(map[cacheKey]*imageConfig),
}
}
type cacheKey struct {
ref string
os string
arch string
}
type cachedImageResolver struct {
cln *client.Client
cache map[cacheKey]*imageConfig
mu sync.RWMutex
}
type imageConfig struct {
ref string
dgst digest.Digest
config []byte
}
func (r *cachedImageResolver) ResolveImageConfig(ctx context.Context, ref string, opt sourceresolver.Opt) (resolvedRef string, dgst digest.Digest, config []byte, err error) {
key := cacheKey{ref: ref}
if opt.Platform != nil {
key.os = opt.Platform.OS
key.arch = opt.Platform.Architecture
}
r.mu.RLock()
cfg, ok := r.cache[key]
r.mu.RUnlock()
if ok {
return cfg.ref, cfg.dgst, cfg.config, nil
}
s, err := llbutil.NewSession(ctx)
if err != nil {
return
}
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
return s.Run(ctx, r.cln.Dialer())
})
g.Go(func() error {
defer s.Close()
var pw progress.Writer
mw := MultiWriter(ctx)
if mw != nil {
pw = mw.WithPrefix("", false)
}
return solver.Build(ctx, r.cln, s, pw, func(ctx context.Context, c gateway.Client) (res *gateway.Result, err error) {
resolvedRef, dgst, config, err = c.ResolveImageConfig(ctx, ref, opt)
return gateway.NewResult(), err
})
})
err = g.Wait()
if err != nil {
return
}
r.mu.Lock()
r.cache[key] = &imageConfig{
ref: resolvedRef,
dgst: dgst,
config: config,
}
r.mu.Unlock()
return
}