-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
export.go
300 lines (264 loc) · 7.38 KB
/
export.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
package oci
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
archiveexporter "github.com/containerd/containerd/images/archive"
"github.com/containerd/containerd/leases"
"github.com/distribution/reference"
"github.com/moby/buildkit/cache"
cacheconfig "github.com/moby/buildkit/cache/config"
"github.com/moby/buildkit/exporter"
"github.com/moby/buildkit/exporter/containerimage"
"github.com/moby/buildkit/exporter/containerimage/exptypes"
"github.com/moby/buildkit/session"
sessioncontent "github.com/moby/buildkit/session/content"
"github.com/moby/buildkit/session/filesync"
"github.com/moby/buildkit/util/compression"
"github.com/moby/buildkit/util/contentutil"
"github.com/moby/buildkit/util/grpcerrors"
"github.com/moby/buildkit/util/leaseutil"
"github.com/moby/buildkit/util/progress"
ocispecs "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc/codes"
)
type ExporterVariant string
const (
VariantOCI = "oci"
VariantDocker = "docker"
)
const (
keyTar = "tar"
)
type Opt struct {
SessionManager *session.Manager
ImageWriter *containerimage.ImageWriter
Variant ExporterVariant
LeaseManager leases.Manager
}
type imageExporter struct {
opt Opt
}
func New(opt Opt) (exporter.Exporter, error) {
im := &imageExporter{opt: opt}
return im, nil
}
func (e *imageExporter) Resolve(ctx context.Context, id int, opt map[string]string) (exporter.ExporterInstance, error) {
i := &imageExporterInstance{
imageExporter: e,
id: id,
tar: true,
opts: containerimage.ImageCommitOpts{
RefCfg: cacheconfig.RefConfig{
Compression: compression.New(compression.Default),
},
OCITypes: e.opt.Variant == VariantOCI,
},
}
opt, err := i.opts.Load(ctx, opt)
if err != nil {
return nil, err
}
for k, v := range opt {
switch k {
case keyTar:
if v == "" {
i.tar = true
continue
}
b, err := strconv.ParseBool(v)
if err != nil {
return nil, errors.Wrapf(err, "non-bool value specified for %s", k)
}
i.tar = b
default:
if i.meta == nil {
i.meta = make(map[string][]byte)
}
i.meta[k] = []byte(v)
}
}
return i, nil
}
type imageExporterInstance struct {
*imageExporter
id int
opts containerimage.ImageCommitOpts
tar bool
meta map[string][]byte
}
func (e *imageExporterInstance) ID() int {
return e.id
}
func (e *imageExporterInstance) Name() string {
return fmt.Sprintf("exporting to %s image format", e.opt.Variant)
}
func (e *imageExporterInstance) Config() *exporter.Config {
return exporter.NewConfigWithCompression(e.opts.RefCfg.Compression)
}
func (e *imageExporterInstance) Export(ctx context.Context, src *exporter.Source, inlineCache exptypes.InlineCache, sessionID string) (_ map[string]string, descref exporter.DescriptorReference, err error) {
if e.opt.Variant == VariantDocker && len(src.Refs) > 0 {
return nil, nil, errors.Errorf("docker exporter does not currently support exporting manifest lists")
}
src = src.Clone()
if src.Metadata == nil {
src.Metadata = make(map[string][]byte)
}
for k, v := range e.meta {
src.Metadata[k] = v
}
opts := e.opts
as, _, err := containerimage.ParseAnnotations(src.Metadata)
if err != nil {
return nil, nil, err
}
opts.Annotations = opts.Annotations.Merge(as)
ctx, done, err := leaseutil.WithLease(ctx, e.opt.LeaseManager, leaseutil.MakeTemporary)
if err != nil {
return nil, nil, err
}
defer func() {
if descref == nil {
done(context.TODO())
}
}()
desc, err := e.opt.ImageWriter.Commit(ctx, src, sessionID, inlineCache, &opts)
if err != nil {
return nil, nil, err
}
defer func() {
if err == nil {
descref = containerimage.NewDescriptorReference(*desc, done)
}
}()
if desc.Annotations == nil {
desc.Annotations = map[string]string{}
}
if _, ok := desc.Annotations[ocispecs.AnnotationCreated]; !ok {
tm := time.Now()
if opts.Epoch != nil {
tm = *opts.Epoch
}
desc.Annotations[ocispecs.AnnotationCreated] = tm.UTC().Format(time.RFC3339)
}
resp := make(map[string]string)
resp[exptypes.ExporterImageDigestKey] = desc.Digest.String()
if v, ok := desc.Annotations[exptypes.ExporterConfigDigestKey]; ok {
resp[exptypes.ExporterImageConfigDigestKey] = v
delete(desc.Annotations, exptypes.ExporterConfigDigestKey)
}
dtdesc, err := json.Marshal(desc)
if err != nil {
return nil, nil, err
}
resp[exptypes.ExporterImageDescriptorKey] = base64.StdEncoding.EncodeToString(dtdesc)
if n, ok := src.Metadata["image.name"]; e.opts.ImageName == "*" && ok {
e.opts.ImageName = string(n)
}
names, err := normalizedNames(e.opts.ImageName)
if err != nil {
return nil, nil, err
}
if len(names) != 0 {
resp["image.name"] = strings.Join(names, ",")
}
expOpts := []archiveexporter.ExportOpt{archiveexporter.WithManifest(*desc, names...)}
switch e.opt.Variant {
case VariantOCI:
expOpts = append(expOpts, archiveexporter.WithAllPlatforms(), archiveexporter.WithSkipDockerManifest())
case VariantDocker:
default:
return nil, nil, errors.Errorf("invalid variant %q", e.opt.Variant)
}
timeoutCtx, cancel := context.WithCancelCause(ctx)
timeoutCtx, _ = context.WithTimeoutCause(timeoutCtx, 5*time.Second, errors.WithStack(context.DeadlineExceeded))
defer cancel(errors.WithStack(context.Canceled))
caller, err := e.opt.SessionManager.Get(timeoutCtx, sessionID, false)
if err != nil {
return nil, nil, err
}
var refs []cache.ImmutableRef
if src.Ref != nil {
refs = append(refs, src.Ref)
}
for _, ref := range src.Refs {
refs = append(refs, ref)
}
eg, egCtx := errgroup.WithContext(ctx)
mprovider := contentutil.NewMultiProvider(e.opt.ImageWriter.ContentStore())
for _, ref := range refs {
ref := ref
eg.Go(func() error {
remotes, err := ref.GetRemotes(egCtx, false, e.opts.RefCfg, false, session.NewGroup(sessionID))
if err != nil {
return err
}
remote := remotes[0]
if unlazier, ok := remote.Provider.(cache.Unlazier); ok {
if err := unlazier.Unlazy(egCtx); err != nil {
return err
}
}
for _, desc := range remote.Descriptors {
mprovider.Add(desc.Digest, remote.Provider)
}
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, nil, err
}
if e.tar {
w, err := filesync.CopyFileWriter(ctx, resp, e.id, caller)
if err != nil {
return nil, nil, err
}
report := progress.OneOff(ctx, "sending tarball")
if err := archiveexporter.Export(ctx, mprovider, w, expOpts...); err != nil {
w.Close()
if grpcerrors.Code(err) == codes.AlreadyExists {
return resp, nil, report(nil)
}
return nil, nil, report(err)
}
err = w.Close()
if grpcerrors.Code(err) == codes.AlreadyExists {
return resp, nil, report(nil)
}
if err != nil {
return nil, nil, report(err)
}
report(nil)
} else {
store := sessioncontent.NewCallerStore(caller, "export")
if err != nil {
return nil, nil, err
}
err := contentutil.CopyChain(ctx, store, mprovider, *desc)
if err != nil {
return nil, nil, err
}
}
return resp, nil, nil
}
func normalizedNames(name string) ([]string, error) {
if name == "" {
return nil, nil
}
names := strings.Split(name, ",")
var tagNames = make([]string, len(names))
for i, name := range names {
parsed, err := reference.ParseNormalizedNamed(name)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse %s", name)
}
tagNames[i] = reference.TagNameOnly(parsed).String()
}
return tagNames, nil
}