From 7cae771969d1e6fb6c6ee21f1cb64ae8e1b0c699 Mon Sep 17 00:00:00 2001 From: Gianluca Zuccarelli Date: Tue, 12 Mar 2024 20:31:48 +0000 Subject: [PATCH] util: add helper to pull containers Add a helper function to check if a container image exists locally, if not, copy the image into the local containers-storage. --- bib/cmd/bootc-image-builder/main.go | 8 +++++ bib/internal/util/util.go | 45 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/bib/cmd/bootc-image-builder/main.go b/bib/cmd/bootc-image-builder/main.go index 3d6406cef..ee12c4ca6 100644 --- a/bib/cmd/bootc-image-builder/main.go +++ b/bib/cmd/bootc-image-builder/main.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/osbuild/bootc-image-builder/bib/internal/setup" + "github.com/osbuild/bootc-image-builder/bib/internal/util" "github.com/osbuild/images/pkg/arch" "github.com/osbuild/images/pkg/blueprint" "github.com/osbuild/images/pkg/cloud/awscloud" @@ -101,6 +102,13 @@ func loadConfig(path string) (*BuildConfig, error) { } func makeManifest(c *ManifestConfig, cacheRoot string) (manifest.OSBuildManifest, error) { + if !c.Remote { + err := util.EnsureContainerIsInStore(c.Imgref) + if err != nil { + return nil, err + } + } + manifest, err := Manifest(c) if err != nil { return nil, err diff --git a/bib/internal/util/util.go b/bib/internal/util/util.go index 8d32bde25..bf4bbb634 100644 --- a/bib/internal/util/util.go +++ b/bib/internal/util/util.go @@ -26,3 +26,48 @@ func RunCmdSync(cmdName string, args ...string) error { } return nil } + +func checkContainerImageExists(storageRef string) (bool, error) { + cmd := exec.Command("skopeo", "inspect", storageRef) + err := cmd.Run() + if err != nil { + if cmd.ProcessState.ExitCode() == 1 { + return false, nil + } + return false, err + } + return true, err +} + +func pullContainerImage(imgref, storageRef string) error { + return RunCmdSync( + "skopeo", + "copy", + fmt.Sprintf("docker://%s", imgref), + storageRef, + ) +} + +func EnsureContainerIsInStore(imgref string) error { + driver := "overlay" + graphRoot := "/var/lib/containers/storage" + runRoot := "/run/containers/storage" + storageImgRef := fmt.Sprintf("containers-storage:[%s@%s+%s]%s", driver, graphRoot, runRoot, imgref) + + exists, err := checkContainerImageExists(storageImgRef) + if err != nil { + return fmt.Errorf("Failed to check if container is in local store: %v", err) + } + + if exists { + fmt.Println("Container image exists in local store") + return nil + } + + err = pullContainerImage(imgref, storageImgRef) + if err != nil { + return fmt.Errorf("Failed to pull container: %v", err) + } + + return nil +}