forked from awslabs/soci-snapshotter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvert.go
More file actions
291 lines (247 loc) · 8.25 KB
/
convert.go
File metadata and controls
291 lines (247 loc) · 8.25 KB
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
/*
Copyright The Soci Snapshotter Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package commands
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"github.com/awslabs/soci-snapshotter/cmd/soci/commands/global"
"github.com/awslabs/soci-snapshotter/cmd/soci/commands/internal"
"github.com/awslabs/soci-snapshotter/soci"
"github.com/awslabs/soci-snapshotter/soci/store"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/images"
"github.com/containerd/containerd/reference"
"github.com/urfave/cli/v3"
)
const (
standaloneFlag = "standalone"
outputFormatFlag = "format"
outputFormatOCIArchive = "oci-archive"
outputFormatOCIDir = "oci-dir"
)
var ErrInvalidDestRef = errors.New(`the destination image must be a tagged ref of the form "registry/repository:tag"`)
func verifyRef(r string) error {
if r == "" {
return errors.New("reference cannot be empty")
}
ref, err := reference.Parse(r)
if err != nil {
return fmt.Errorf("could not parse reference: %w", err)
}
object := ref.Object
if object == "" {
return errors.New("reference must be tagged")
}
if strings.Contains(object, "@") {
return errors.New("reference must not contain a digest")
}
return nil
}
// ConvertCommand converts an image into a SOCI enabled image.
// The new image is added to the containerd content store and can
// be pushed and deployed like a normal image.
//
// In standalone mode, the command reads an OCI image layout (tar or directory)
// and writes a converted OCI image layout (tar or directory) without requiring containerd.
var ConvertCommand = &cli.Command{
Name: "convert",
Usage: "convert an OCI image to a SOCI enabled image",
ArgsUsage: "[flags] <image_ref> <dest_ref>",
Flags: slices.Concat(
internal.PlatformFlags,
createZtocFlags,
internal.PrefetchFlags,
[]cli.Flag{
&cli.BoolFlag{
Name: standaloneFlag,
Usage: "Run in standalone mode without containerd runtime. In this mode, the command reads an OCI image layout (tar or directory) and writes a converted OCI image layout without requiring a running containerd instance.",
},
&cli.StringFlag{
Name: outputFormatFlag,
Usage: "Output format for standalone mode: oci-archive (tar) or oci-dir (directory).",
Value: outputFormatOCIArchive,
Validator: func(s string) error {
if s != outputFormatOCIArchive && s != outputFormatOCIDir {
return fmt.Errorf("unsupported output format %q: must be %q or %q", s, outputFormatOCIArchive, outputFormatOCIDir)
}
return nil
},
},
}),
Action: func(ctx context.Context, cmd *cli.Command) error {
src := cmd.Args().Get(0)
if src == "" {
return errors.New("source image needs to be specified")
}
dst := cmd.Args().Get(1)
if dst == "" {
return errors.New("destination needs to be specified")
}
if cmd.Bool(standaloneFlag) {
return runStandaloneConvert(ctx, cmd, src, dst)
}
err := verifyRef(dst)
if err != nil {
return fmt.Errorf("%w: %w", ErrInvalidDestRef, err)
}
client, ctx, cancel, err := internal.NewClient(ctx, cmd)
if err != nil {
return err
}
defer cancel()
cs := client.ContentStore()
is := client.ImageService()
srcImg, err := is.Get(ctx, src)
if err != nil {
return err
}
blobStore, err := store.NewContentStore(internal.ContentStoreOptions(ctx, cmd)...)
if err != nil {
return err
}
artifactsDb, err := soci.NewDB(soci.ArtifactsDbPath(cmd.String(global.RootFlag)))
if err != nil {
return err
}
builderOpts, err := parseBuilderOptions(cmd)
if err != nil {
return err
}
builderOpts = append(builderOpts, soci.WithArtifactsDb(artifactsDb))
builder, err := soci.NewIndexBuilder(cs, blobStore, builderOpts...)
if err != nil {
return err
}
batchCtx, done, err := blobStore.BatchOpen(ctx)
if err != nil {
return err
}
defer done(ctx)
platforms, err := internal.GetPlatforms(ctx, cmd, srcImg, cs)
if err != nil {
return err
}
desc, err := builder.Convert(batchCtx, srcImg,
soci.ConvertWithPlatforms(platforms...),
// Don't set a GC label on the converted OCI Index. We will create an image
// in containerd that will act as the GC root. This way, the OCI index, SOCI indexes, and
// images will be removed when the image is deleted in containerd
soci.ConvertWithNoGarbageCollectionLabels(),
)
if err != nil {
return err
}
im := images.Image{
Name: dst,
Target: *desc,
}
img, err := is.Get(ctx, dst)
if err != nil {
if !errors.Is(err, errdefs.ErrNotFound) {
return err
}
_, err = is.Create(ctx, im)
return err
}
img.Target = *desc
_, err = is.Update(ctx, img)
return err
},
}
// runStandaloneConvert runs the convert command in standalone mode (without containerd).
// It reads an OCI image layout (tar or directory), performs the SOCI conversion, and
// writes the result as an OCI image layout tar or directory based on the --format flag.
func runStandaloneConvert(ctx context.Context, cmd *cli.Command, inputPath string, outputPath string) error {
format := cmd.String(outputFormatFlag)
// Prefer the OS temp dir (/tmp) since it's often memory-backed and faster.
// Fall back to the output path's parent for minimal environments (e.g., scratch images) where /tmp may not exist.
tmpBase := os.TempDir()
if _, err := os.Stat(tmpBase); err != nil {
tmpBase = filepath.Dir(filepath.Clean(outputPath))
}
ociLayoutDir, err := os.MkdirTemp(tmpBase, "soci-oci-*")
if err != nil {
return fmt.Errorf("failed to create temp directory: %w", err)
}
defer os.RemoveAll(ociLayoutDir)
imageInfo, err := internal.LoadImage(ctx, inputPath, ociLayoutDir)
if err != nil {
return err
}
artifactsDir, err := os.MkdirTemp(tmpBase, "soci-artifacts-*")
if err != nil {
return fmt.Errorf("failed to create artifacts temp directory: %w", err)
}
defer os.RemoveAll(artifactsDir)
artifactsDb, err := soci.NewDB(soci.ArtifactsDbPath(artifactsDir))
if err != nil {
return fmt.Errorf("failed to create artifacts database: %w", err)
}
builderOpts, err := parseBuilderOptions(cmd)
if err != nil {
return err
}
builderOpts = append(builderOpts, soci.WithArtifactsDb(artifactsDb))
sociStore := &store.SociStore{Store: imageInfo.OrasStore}
builder, err := soci.NewIndexBuilder(imageInfo.ContentStore, sociStore, builderOpts...)
if err != nil {
return err
}
requestedPlatforms, err := internal.GetPlatforms(ctx, cmd, imageInfo.Image, imageInfo.ContentStore)
if err != nil {
return err
}
batchCtx, done, err := sociStore.BatchOpen(ctx)
if err != nil {
return err
}
defer done(ctx)
convertedDesc, err := builder.Convert(batchCtx, imageInfo.Image, soci.ConvertWithPlatforms(requestedPlatforms...))
if err != nil {
return err
}
if format == outputFormatOCIDir {
return internal.SaveImageToDir(ociLayoutDir, *convertedDesc, outputPath)
}
return internal.SaveImageToTar(ctx, imageInfo.ContentStore, *convertedDesc, outputPath)
}
func parseBuilderOptions(cmd *cli.Command) ([]soci.BuilderOption, error) {
var optimizations []soci.Optimization
for _, o := range cmd.StringSlice(optimizationFlag) {
optimization, err := soci.ParseOptimization(o)
if err != nil {
return nil, err
}
optimizations = append(optimizations, optimization)
}
builderOpts := []soci.BuilderOption{
soci.WithMinLayerSize(cmd.Int64(minLayerSizeFlag)),
soci.WithSpanSize(cmd.Int64(spanSizeFlag)),
soci.WithBuildToolIdentifier(buildToolIdentifier),
soci.WithOptimizations(optimizations),
soci.WithForceRecreateZtocs(cmd.Bool(forceRecreateZtocsFlag)),
}
allPrefetchFiles, err := internal.ParsePrefetchFiles(cmd)
if err != nil {
return nil, fmt.Errorf("failed to parse prefetch files: %w", err)
}
if len(allPrefetchFiles) > 0 {
builderOpts = append(builderOpts, soci.WithPrefetchPaths(allPrefetchFiles))
}
return builderOpts, nil
}