Skip to content

Commit

Permalink
extractZst: allow overwriting image files
Browse files Browse the repository at this point in the history
There is an issue with the new pull image functionality, where
ovewriting an existing file does not work and no errors are generated.

$ rm -rf _data/images/kind_rhel8.qcow2{,.zst}
$ echo "PIZZA" >  _data/images/kind_rhel8.qcow2
$ ~/src/little-vm-helper/lvh images pull  --cache quay.io/lvh-images/kind-ci:rhel8-20240201.122048
$ cat  _data/images/kind_rhel8.qcow2
PIZZA
$ ls _data/images/kind_rhel8.qcow2{,.zst}
_data/images/kind_rhel8.qcow2  _data/images/kind_rhel8.qcow2.zst

There is a check at extractZst for the existance of the destination
file. If the file exists, we erturn os.ErrExist. This error is
propagated up to ExtractImage but is turned to a non-error by its
caller.

This patch adds support for overwriting images. We create a tempfile for
the uncompression and if everything goes well, we rename it to the
intended destination.

Signed-off-by: Kornilios Kourtis <[email protected]>
  • Loading branch information
kkourt committed Feb 1, 2024
1 parent b81560d commit 9d758b7
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions pkg/images/pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,20 @@ func handleTarObject(ctx context.Context, tr *tar.Reader, hdr *tar.Header, conf
}

func extractZst(ctx context.Context, reader io.Reader, dstPath string) error {
if _, err := os.Stat(dstPath); err == nil {
return os.ErrExist
dstDir, dstName := filepath.Split(dstPath)

var tmpPath string
if tmpf, err := os.CreateTemp(dstDir, fmt.Sprintf("%s-*", dstName)); err != nil {
return err
} else {
tmpPath = tmpf.Name()
tmpf.Close()
// NB: remove temp file in case something goes wrong
defer os.Remove(tmpPath)
}

cmd := exec.CommandContext(ctx, "zstd", "-d", "-", "-o", dstPath)
// NB: we need to force with -f, because the destination file exists (we created it)
cmd := exec.CommandContext(ctx, "zstd", "-d", "-", "-o", tmpPath, "-f")
cmd.Stdin = reader

if _, err := cmd.Output(); err != nil {
Expand All @@ -180,5 +189,5 @@ func extractZst(ctx context.Context, reader io.Reader, dstPath string) error {
return fmt.Errorf("failed during zst decompression to %s: %w", dstPath, err)
}

return nil
return os.Rename(tmpPath, dstPath)
}

0 comments on commit 9d758b7

Please sign in to comment.