← Back to Pull requests

importer, registry-datasource: cleanup and simplify #4285

Merged
Acedus merged 9 files (1049 lines) on Sep 29, 2026 19:03 UTC
View on GitHub
Acedus Acedus commented on Sep 19, 2026 12:41 UTC
Author

<!-- Thanks for sending a pull request! Here are some tips for you:
1. Follow the instructions for writing a release note from k8s: https://git.k8s.io/community/contributors/guide/release-notes.md
-->

What this PR does / why we need it:
Cleanup of the registry import path. Along the way it fixes a reader stack leak when NewFormatReaders fails, an ImageSource double close, and three fetches of the same image config instead of one.

Which issue(s) this PR fixes (optional, in fixes #<issue number>(, fixes #<issue_number>, ...) format, will close the issue(s) when PR gets merged):
Fixes #

Special notes for your reviewer:
The last commit pulls layer extraction out of the registry code into a fileExtractor handed a blobOpener, so the tar walk, without handling and zip-slip guard can be unit tested instead of going through OCI archive fixtures.

Release note:
<!-- Write your release note:
1. Enter your extended release note in the below block. If the PR requires additional action from users switching to the new release, include the string "action required".
2. If no release note is required, just write "NONE".
-->
``release-note
NONE
``

Diff: 1049 lines (+573 / -476) across 9 files Reviewer: nav1s Review duration: 14782m
All Vouch review confidence checks passed
Residual risk 0.16 = Change Risk (0.55) × (1 − Review Confidence (0.70)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.55 · 1049 lines diff across 9 files
0.55
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.44 · 5 substantive comment(s)
0.44
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
70%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Real PR Conversation Timeline
13 items
Acedus Acedus commented on Sep 19, 2026 12:41 UTC
Author

/cc @akalenyu @nav1s

kubevirt-prow[bot] kubevirt-prow[bot] commented on Sep 19, 2026 12:41 UTC
Bot

@Acedus: GitHub didn't allow me to request PR reviews from the following users: nav1s.

Note that only kubevirt members and repo collaborators can review this PR, and authors cannot review their own PRs.

<details>

In response to this:

>/cc @akalenyu @nav1s

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>

coveralls coveralls commented on Sep 19, 2026 12:55 UTC
Contributor

![Coverage Status](https://coveralls.io/builds/82037282)

coverage: 49.885% (+0.1%) from 49.777% — Acedus:kill-transport into kubevirt:main

nav1s nav1s commented on code on Sep 29, 2026 12:46 UTC
Code Review
pkg/importer/registry-datasource.go:1
@@ -237,3 +246,185 @@ func collectCerts(certDir, targetDir, targetPrefix string) error {
 	}
 	return nil
 }
+
+// ErrBootcImageDetected is returned when a bootc/ostree-bootable container image is detected
+// but conversion is not yet implemented.
+var ErrBootcImageDetected = errors.New("bootc image detected: this image contains an ostree-based bootable OS (containers.bootc=1 or ostree.bootable=1) and cannot be imported as a regular container disk; bootc-to-disk conversion is not yet implemented")
+
+func commandTimeoutContext() (context.Context, context.CancelFunc) {
+	return context.WithCancel(context.Background())
+}
+
+func buildSourceContext(accessKey, secKey, imageArchitecture, certDir string, insecureRegistry bool) *types.SystemContext {
+	ctx := &types.SystemContext{}
+	if accessKey != "" && secKey != "" {
+		ctx.DockerAuthConfig = &types.DockerAuthConfig{
+			Username: accessKey,
+			Password: secKey,
+		}
+	}
+	if certDir != "" {
+		ctx.DockerCertPath = certDir
+		ctx.DockerDaemonCertPath = certDir
+	}
+
+	if insecureRegistry {
+		ctx.DockerDaemonInsecureSkipTLSVerify = true
+		ctx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(true)
+	}
+
+	if imageArchitecture != "" {
+		ctx.ArchitectureChoice = imageArchitecture
+	}
+
+	return ctx
+}
+
+func readImageSource(ctx context.Context, sys *types.SystemContext, img string) (types.ImageSource, error) {
+	ref, err := parseImageName(img)
+	if err != nil {
+		klog.Errorf("Could not parse image: %v", err)
+		return nil, fmt.Errorf("Could not parse image: %w", err)
+	}
+
+	src, err := ref.NewImageSource(ctx, sys)
+	if err != nil {
+		klog.Errorf("Could not create image reference: %v", err)
+		return nil, NewImagePullFailedError(err)
+	}
+	return src, nil
+}
+
+func parseImageName(img string) (types.ImageReference, error) {
+	parts := strings.SplitN(img, ":", 2)
+	if len(parts) != 2 {
+		return nil, fmt.Errorf(`Invalid image name "%s", expected colon-separated transport:reference`, img)
+	}
+	switch parts[0] {
+	case cdiv1.RegistrySchemeDocker:
+		return docker.ParseReference(parts[1])
+	case cdiv1.RegistrySchemeOci:
+		return archive.ParseReference(parts[1])
+	}
+	return nil, fmt.Errorf(`Invalid image name "%s", unknown transport`, img)
+}
+
+func closeImage(c io.Closer) {
+	if err := c.Close(); err != nil {
+		klog.Warningf("Could not close image source: %v ", err)
+	}
+}
+
+func copyRegistryImage(url, destDir, pathPrefix, accessKey, secKey, imageArchitecture, certDir string, insecureRegistry, preallocation bool) (*types.ImageInspectInfo, error) {
+	klog.Infof("Downloading image from '%v', copying file from '%v' to '%v'", url, pathPrefix, destDir)
+
+	ctx, cancel := commandTimeoutContext()
+	defer cancel()
+	srcCtx := buildSourceContext(accessKey, secKey, imageArchitecture, certDir, insecureRegistry)
+
+	src, err := readImageSource(ctx, srcCtx, url)
+	if err != nil {
+		return nil, err
+	}
+
+	imgCloser, err := image.FromSource(ctx, srcCtx, src)
+	if err != nil {
+		closeImage(src)
+		klog.Errorf("Error retrieving image: %v", err)
+		return nil, fmt.Errorf("Error retrieving image: %w", err)
+	}
+	defer closeImage(imgCloser)
+
+	// The config the checks below read is also what the caller gets back, so inspect once.
+	info, err := imgCloser.Inspect(ctx)
+	if err != nil {
+		return nil, fmt.Errorf("Error inspecting image: %w", err)
+	}
+	if err := validateImagePlatformMatch(srcCtx, info); err != nil {
+		return nil, err
+	}
+	if err := checkBootcImage(info); err != nil {
+		return nil, err
+	}
+
+	cache := blobinfocache.DefaultCache(srcCtx)
+	openBlob := func(ctx context.Context, layer types.BlobInfo) (io.ReadCloser, error) {
+		blob, _, err := src.GetBlob(ctx, layer, cache)
+		return blob, err
+	}
+
+	extractor := fileExtractor{destDir: destDir, pathPrefix: pathPrefix, preallocation: preallocation}
+	if err := extractor.extract(ctx, imgCloser.LayerInfos(), openBlob); err != nil {
+		return nil, err
+	}
+
+	return info, nil
+}
+
+const (
+	bootcImageLabel   = "containers.bootc"
+	ostreeBootLabel   = "ostree.bootable"
+	bootcLabelEnabled = "1"
+)
+
+func checkBootcImage(info *types.ImageInspectInfo) error {
+	if info.Labels[bootcImageLabel] == bootcLabelEnabled ||
+		info.Labels[ostreeBootLabel] == bootcLabelEnabled {
+		klog.Infof("Detected bootc/ostree-bootable container image")
+		return ErrBootcImageDetected
+	}
+	return nil
+}
+
+func validateImagePlatformMatch(sys *types.SystemContext, info *types.ImageInspectInfo) error {
+	if sys.ArchitectureChoice == "" || info.Architecture == sys.ArchitectureChoice {
+		return nil
+	}
+	return fmt.Errorf(`Error validating architecture: manifest image architecture: "%s" doesn't match requested architecture: "%s"`,
+		info.Architecture, sys.ArchitectureChoice)
+}
+
+// GetImageDigest returns the digest of the container image at url.
+// url: source registry url.
+// accessKey: accessKey for the registry described in url.
+// secKey: secretKey for the registry described in url.
+// certDir: directory public CA keys are stored for registry identity verification
+// insecureRegistry: boolean if true will allow insecure registries.
+func GetImageDigest(url, accessKey, secKey, certDir string, insecureRegistry bool) (string, error) {
+	klog.Infof("Inspecting image from '%v'", url)
+
+	ctx, cancel := commandTimeoutContext()
+	defer cancel()
+	srcCtx := buildSourceContext(accessKey, secKey, "", certDir, insecureRegistry)
+
+	src, err := readImageSource(ctx, srcCtx, url)
+	if err != nil {
+		return "", err
+	}
+	defer closeImage(src)
+
+	imageManifest, _, err := src.GetManifest(context.Background(), nil)
+	if err != nil {
+		return "", err
+	}
+
+	digest, err := manifest.Digest(imageManifest)
+	if err != nil {
+		return "", err
+	}
+
+	return digest.String(), nil
+}
+
+// CopyRegistryImage download image from registry with docker image API. It will extract first file under the pathPrefix
+// url: source registry url.
+// destDir: the scratch space destination.
+// pathPrefix: path to extract files from.
+// accessKey: accessKey for the registry described in url.
+// secKey: secretKey for the registry described in url.
+// imageArchitecture: image index filter for CPU architecture.
+// certDir: directory public CA keys are stored for registry identity verification
+// insecureRegistry: boolean if true will allow insecure registries.
+func CopyRegistryImage(url, destDir, pathPrefix, accessKey, secKey, imageArchitecture, certDir string, insecureRegistry, preallocation bool) (*types.ImageInspectInfo, error) {

Is this wrapper still needed?

nav1s nav1s commented on code on Sep 29, 2026 13:41 UTC
Code Review
pkg/importer/format-readers_test.go:1
@@ -94,13 +94,20 @@ var _ = Describe("Format Readers", func() {
 	)
 
 	It("should not crash on no progress reader", func() {
-		stringReader := io.NopCloser(strings.NewReader("This is a test string"))
+		stringReader := io.NopCloser(strings.NewReader(strings.Repeat("This is a test string. ", 32)))
 		testReader, err := NewFormatReaders(stringReader, uint64(0), nil)
-		// Not passing a real string, so the header checking will fail.
-		Expect(err).To(HaveOccurred())
+		Expect(err).ToNot(HaveOccurred())
 		Expect(testReader.progressReader).To(BeNil())
 		// This should not crash
 		testReader.StartProgressUpdate()
+		Expect(testReader.Close()).To(Succeed())
+	})
+
+	It("should return no readers to close when construction fails", func() {
+		stringReader := io.NopCloser(strings.NewReader("This is a test string"))

Could we use a reader that will allow us to verify that it was closed here?

nav1s nav1s requested changes on Sep 29, 2026 13:43 UTC
Changes Requested Reviewer

Thanks @Acedus, looks pretty good, few comments below.

kubevirt-prow[bot] kubevirt-prow[bot] commented on Sep 29, 2026 13:43 UTC
Bot

@nav1s: changing LGTM is restricted to collaborators

<details>

In response to this:

>Thanks @Acedus, looks pretty good, few comments below.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.
</details>

Acedus Acedus commented on code on Sep 29, 2026 13:57 UTC
Code Review
pkg/importer/registry-datasource.go:1
@@ -237,3 +246,185 @@ func collectCerts(certDir, targetDir, targetPrefix string) error {
 	}
 	return nil
 }
+
+// ErrBootcImageDetected is returned when a bootc/ostree-bootable container image is detected
+// but conversion is not yet implemented.
+var ErrBootcImageDetected = errors.New("bootc image detected: this image contains an ostree-based bootable OS (containers.bootc=1 or ostree.bootable=1) and cannot be imported as a regular container disk; bootc-to-disk conversion is not yet implemented")
+
+func commandTimeoutContext() (context.Context, context.CancelFunc) {
+	return context.WithCancel(context.Background())
+}
+
+func buildSourceContext(accessKey, secKey, imageArchitecture, certDir string, insecureRegistry bool) *types.SystemContext {
+	ctx := &types.SystemContext{}
+	if accessKey != "" && secKey != "" {
+		ctx.DockerAuthConfig = &types.DockerAuthConfig{
+			Username: accessKey,
+			Password: secKey,
+		}
+	}
+	if certDir != "" {
+		ctx.DockerCertPath = certDir
+		ctx.DockerDaemonCertPath = certDir
+	}
+
+	if insecureRegistry {
+		ctx.DockerDaemonInsecureSkipTLSVerify = true
+		ctx.DockerInsecureSkipTLSVerify = types.NewOptionalBool(true)
+	}
+
+	if imageArchitecture != "" {
+		ctx.ArchitectureChoice = imageArchitecture
+	}
+
+	return ctx
+}
+
+func readImageSource(ctx context.Context, sys *types.SystemContext, img string) (types.ImageSource, error) {
+	ref, err := parseImageName(img)
+	if err != nil {
+		klog.Errorf("Could not parse image: %v", err)
+		return nil, fmt.Errorf("Could not parse image: %w", err)
+	}
+
+	src, err := ref.NewImageSource(ctx, sys)
+	if err != nil {
+		klog.Errorf("Could not create image reference: %v", err)
+		return nil, NewImagePullFailedError(err)
+	}
+	return src, nil
+}
+
+func parseImageName(img string) (types.ImageReference, error) {
+	parts := strings.SplitN(img, ":", 2)
+	if len(parts) != 2 {
+		return nil, fmt.Errorf(`Invalid image name "%s", expected colon-separated transport:reference`, img)
+	}
+	switch parts[0] {
+	case cdiv1.RegistrySchemeDocker:
+		return docker.ParseReference(parts[1])
+	case cdiv1.RegistrySchemeOci:
+		return archive.ParseReference(parts[1])
+	}
+	return nil, fmt.Errorf(`Invalid image name "%s", unknown transport`, img)
+}
+
+func closeImage(c io.Closer) {
+	if err := c.Close(); err != nil {
+		klog.Warningf("Could not close image source: %v ", err)
+	}
+}
+
+func copyRegistryImage(url, destDir, pathPrefix, accessKey, secKey, imageArchitecture, certDir string, insecureRegistry, preallocation bool) (*types.ImageInspectInfo, error) {
+	klog.Infof("Downloading image from '%v', copying file from '%v' to '%v'", url, pathPrefix, destDir)
+
+	ctx, cancel := commandTimeoutContext()
+	defer cancel()
+	srcCtx := buildSourceContext(accessKey, secKey, imageArchitecture, certDir, insecureRegistry)
+
+	src, err := readImageSource(ctx, srcCtx, url)
+	if err != nil {
+		return nil, err
+	}
+
+	imgCloser, err := image.FromSource(ctx, srcCtx, src)
+	if err != nil {
+		closeImage(src)
+		klog.Errorf("Error retrieving image: %v", err)
+		return nil, fmt.Errorf("Error retrieving image: %w", err)
+	}
+	defer closeImage(imgCloser)
+
+	// The config the checks below read is also what the caller gets back, so inspect once.
+	info, err := imgCloser.Inspect(ctx)
+	if err != nil {
+		return nil, fmt.Errorf("Error inspecting image: %w", err)
+	}
+	if err := validateImagePlatformMatch(srcCtx, info); err != nil {
+		return nil, err
+	}
+	if err := checkBootcImage(info); err != nil {
+		return nil, err
+	}
+
+	cache := blobinfocache.DefaultCache(srcCtx)
+	openBlob := func(ctx context.Context, layer types.BlobInfo) (io.ReadCloser, error) {
+		blob, _, err := src.GetBlob(ctx, layer, cache)
+		return blob, err
+	}
+
+	extractor := fileExtractor{destDir: destDir, pathPrefix: pathPrefix, preallocation: preallocation}
+	if err := extractor.extract(ctx, imgCloser.LayerInfos(), openBlob); err != nil {
+		return nil, err
+	}
+
+	return info, nil
+}
+
+const (
+	bootcImageLabel   = "containers.bootc"
+	ostreeBootLabel   = "ostree.bootable"
+	bootcLabelEnabled = "1"
+)
+
+func checkBootcImage(info *types.ImageInspectInfo) error {
+	if info.Labels[bootcImageLabel] == bootcLabelEnabled ||
+		info.Labels[ostreeBootLabel] == bootcLabelEnabled {
+		klog.Infof("Detected bootc/ostree-bootable container image")
+		return ErrBootcImageDetected
+	}
+	return nil
+}
+
+func validateImagePlatformMatch(sys *types.SystemContext, info *types.ImageInspectInfo) error {
+	if sys.ArchitectureChoice == "" || info.Architecture == sys.ArchitectureChoice {
+		return nil
+	}
+	return fmt.Errorf(`Error validating architecture: manifest image architecture: "%s" doesn't match requested architecture: "%s"`,
+		info.Architecture, sys.ArchitectureChoice)
+}
+
+// GetImageDigest returns the digest of the container image at url.
+// url: source registry url.
+// accessKey: accessKey for the registry described in url.
+// secKey: secretKey for the registry described in url.
+// certDir: directory public CA keys are stored for registry identity verification
+// insecureRegistry: boolean if true will allow insecure registries.
+func GetImageDigest(url, accessKey, secKey, certDir string, insecureRegistry bool) (string, error) {
+	klog.Infof("Inspecting image from '%v'", url)
+
+	ctx, cancel := commandTimeoutContext()
+	defer cancel()
+	srcCtx := buildSourceContext(accessKey, secKey, "", certDir, insecureRegistry)
+
+	src, err := readImageSource(ctx, srcCtx, url)
+	if err != nil {
+		return "", err
+	}
+	defer closeImage(src)
+
+	imageManifest, _, err := src.GetManifest(context.Background(), nil)
+	if err != nil {
+		return "", err
+	}
+
+	digest, err := manifest.Digest(imageManifest)
+	if err != nil {
+		return "", err
+	}
+
+	return digest.String(), nil
+}
+
+// CopyRegistryImage download image from registry with docker image API. It will extract first file under the pathPrefix
+// url: source registry url.
+// destDir: the scratch space destination.
+// pathPrefix: path to extract files from.
+// accessKey: accessKey for the registry described in url.
+// secKey: secretKey for the registry described in url.
+// imageArchitecture: image index filter for CPU architecture.
+// certDir: directory public CA keys are stored for registry identity verification
+// insecureRegistry: boolean if true will allow insecure registries.
+func CopyRegistryImage(url, destDir, pathPrefix, accessKey, secKey, imageArchitecture, certDir string, insecureRegistry, preallocation bool) (*types.ImageInspectInfo, error) {

Nope, let's drop it.

nav1s nav1s approved these changes on Sep 29, 2026 14:22 UTC
Approved Reviewer

Approved these changes.

kubevirt-prow[bot] kubevirt-prow[bot] commented on Sep 29, 2026 14:22 UTC
Bot

@nav1s: changing LGTM is restricted to collaborators

<details>

In response to this:

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

</details>

awels awels approved these changes on Sep 29, 2026 19:02 UTC
Approved Reviewer

/approve

kubevirt-prow[bot] kubevirt-prow[bot] commented on Sep 29, 2026 19:02 UTC
Bot

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: <a href="https://github.com/kubevirt/containerized-data-importer/pull/4285#pullrequestreview-5357102340" title="Approved">awels</a>

The full list of commands accepted by this bot can be found here.

The pull request process is described here

<details >
Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [awels]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    Reviewers
    Assignees
    Acedus Acedus
    Labels
    risk: low confidence: 70.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 54.7% (MEDIUM) · Higher = larger blast radius
    54.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 70.2% · Lower = rushed or shallow review
    70.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 16.3% · Safe to merge
    16.3%