save docker image to disk before flatten

Signed-off-by: Adphi <philippe.adrien.nousse@gmail.com>
This commit is contained in:
Adphi 2023-02-28 12:04:04 +01:00 committed by Adphi
parent be88bc29f5
commit bfa5f0df1d
2 changed files with 15 additions and 14 deletions

View File

@ -24,11 +24,11 @@ import (
"text/template" "text/template"
"github.com/google/go-containerregistry/cmd/crane/cmd" "github.com/google/go-containerregistry/cmd/crane/cmd"
"github.com/google/go-containerregistry/pkg/name" "github.com/google/go-containerregistry/pkg/crane"
v1 "github.com/google/go-containerregistry/pkg/v1" v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/daemon"
"github.com/google/go-containerregistry/pkg/v1/mutate" "github.com/google/go-containerregistry/pkg/v1/mutate"
"go.linka.cloud/d2vm/pkg/docker"
"go.linka.cloud/d2vm/pkg/exec" "go.linka.cloud/d2vm/pkg/exec"
) )
@ -81,17 +81,18 @@ func (i DockerImage) AsRunScript(w io.Writer) error {
} }
func NewImage(ctx context.Context, tag string, imageTmpPath string) (*image, error) { func NewImage(ctx context.Context, tag string, imageTmpPath string) (*image, error) {
ref, err := name.ParseReference(tag)
if err != nil {
return nil, err
}
img, err := daemon.Image(ref)
if err != nil {
return nil, err
}
if err := os.MkdirAll(imageTmpPath, perm); err != nil { if err := os.MkdirAll(imageTmpPath, perm); err != nil {
return nil, err return nil, err
} }
// save the image to a tar file to avoid loading it in memory
tar := filepath.Join(imageTmpPath, "img.layers.tar")
if err := docker.ImageSave(ctx, tag, tar); err != nil {
return nil, err
}
img, err := crane.Load(tar)
if err != nil {
return nil, err
}
i := &image{ i := &image{
img: img, img: img,
dir: imageTmpPath, dir: imageTmpPath,
@ -109,10 +110,6 @@ type image struct {
} }
func (i image) Flatten(ctx context.Context, out string) error { func (i image) Flatten(ctx context.Context, out string) error {
if err := os.MkdirAll(out, perm); err != nil {
return err
}
tar := filepath.Join(i.dir, "img.tar") tar := filepath.Join(i.dir, "img.tar")
f, err := os.Create(tar) f, err := os.Create(tar)
if err != nil { if err != nil {

View File

@ -92,6 +92,10 @@ func ImageList(ctx context.Context, tag string) ([]string, error) {
return imgs, s.Err() return imgs, s.Err()
} }
func ImageSave(ctx context.Context, tag, file string) error {
return Cmd(ctx, "image", "save", "-o", file, tag)
}
func Pull(ctx context.Context, tag string) error { func Pull(ctx context.Context, tag string) error {
return Cmd(ctx, "image", "pull", tag) return Cmd(ctx, "image", "pull", tag)
} }