diff --git a/pkg/test/extensions/mirrored_images.go b/pkg/test/extensions/mirrored_images.go new file mode 100644 index 000000000000..0bfcfcf5bca2 --- /dev/null +++ b/pkg/test/extensions/mirrored_images.go @@ -0,0 +1,150 @@ +package extensions + +import ( + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/openshift-eng/openshift-tests-extension/pkg/extension" + "github.com/openshift/library-go/pkg/image/reference" + "github.com/sirupsen/logrus" + k8simage "k8s.io/kubernetes/test/utils/image" +) + +const MirroredImagesEnvVar = "EXTENSION_MIRRORED_IMAGES" + +// ComputeMirroredImages builds a mapping from each extension image's original +// pull spec to its mirrored pull spec at fromRepository. Extensions report +// their images through the info command; each Image carries the upstream +// registry/name/version and an optional Mapped hint for the mirrored tag. +func ComputeMirroredImages(extensionsInfo []*Extension, fromRepository string) (map[string]string, error) { + if fromRepository == "" { + return nil, nil + } + + ref, err := reference.Parse(fromRepository) + if err != nil { + return nil, fmt.Errorf("invalid from-repository %q: %v", fromRepository, err) + } + if !strings.Contains(ref.Exact(), "/") { + return nil, fmt.Errorf("invalid from-repository %q: expected a registry and repository, such as registry.example.com/repo", fromRepository) + } + + mapping := make(map[string]string) + + for _, ext := range extensionsInfo { + if ext == nil || ext.Extension == nil { + continue + } + for _, img := range ext.Images { + original, mapped := mirroredPullSpecs(img, ref) + if original == mapped { + continue + } + mapping[original] = mapped + } + } + + if len(mapping) == 0 { + return nil, nil + } + + logrus.Infof("Computed mirrored image mappings for %d images", len(mapping)) + return mapping, nil +} + +// mirroredPullSpecs returns the original and mirrored pull specs for an image. +// The logic mirrors imageSetsForImage in the images command. +func mirroredPullSpecs(img extension.Image, ref reference.DockerImageReference) (original, mirrored string) { + original = fmt.Sprintf("%s/%s:%s", img.Registry, img.Name, img.Version) + + if img.Mapped == nil { + id := k8simage.ImageID(img.Index) + config := k8simage.Config{} + config.SetName(img.Name) + config.SetVersion(img.Version) + config.SetRegistry(img.Registry) + originalSet := map[k8simage.ImageID]k8simage.Config{id: config} + mappedSet := k8simage.GetMappedImageConfigs(originalSet, ref.Exact()) + mappedConfig := mappedSet[id] + mirrored = mappedConfig.GetE2EImage() + } else { + mirrored = fmt.Sprintf("%s/%s:%s", ref.Registry, ref.RepositoryName(), img.Mapped.Version) + } + + return original, mirrored +} + +// WriteMirroredImagesFile writes the mapping to a temporary JSON file and +// returns the path. The caller is responsible for removing the file. +func WriteMirroredImagesFile(mapping map[string]string) (string, error) { + if len(mapping) == 0 { + return "", nil + } + + data, err := json.Marshal(mapping) + if err != nil { + return "", fmt.Errorf("failed to marshal mirrored images: %v", err) + } + + f, err := os.CreateTemp("", "mirrored-images-*.json") + if err != nil { + return "", fmt.Errorf("failed to create mirrored images file: %v", err) + } + + if _, err := f.Write(data); err != nil { + if closeErr := f.Close(); closeErr != nil { + logrus.Warnf("Failed to close temp file during cleanup: %v", closeErr) + } + if removeErr := os.Remove(f.Name()); removeErr != nil { + logrus.Warnf("Failed to remove temp file during cleanup: %v", removeErr) + } + return "", fmt.Errorf("failed to write mirrored images file: %v", err) + } + + path := f.Name() + if err := f.Close(); err != nil { + if removeErr := os.Remove(path); removeErr != nil { + logrus.Warnf("Failed to remove temp file during cleanup: %v", removeErr) + } + return "", fmt.Errorf("failed to close mirrored images file: %v", err) + } + + return path, nil +} + +// ReadMirroredImagesFile reads a mirrored images mapping from a JSON file. +func ReadMirroredImagesFile(path string) (map[string]string, error) { + data, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("failed to read mirrored images file: %v", err) + } + + mapping := make(map[string]string) + if err := json.Unmarshal(data, &mapping); err != nil { + return nil, fmt.Errorf("failed to parse mirrored images file: %v", err) + } + + return mapping, nil +} + +// MirroredLocationFor returns the mirrored pull spec for an image if one +// exists in the mapping, or the original pull spec unchanged. +func MirroredLocationFor(mapping map[string]string, original string) string { + if mapped, ok := mapping[original]; ok { + return mapped + } + return original +} + +// LoadMirroredImagesFromEnv reads the mirrored images mapping from the file +// referenced by the EXTENSION_MIRRORED_IMAGES environment variable. Returns +// nil without error when the variable is unset. +func LoadMirroredImagesFromEnv() (map[string]string, error) { + path := os.Getenv(MirroredImagesEnvVar) + if path == "" { + return nil, nil + } + return ReadMirroredImagesFile(path) +} diff --git a/pkg/test/extensions/mirrored_images_test.go b/pkg/test/extensions/mirrored_images_test.go new file mode 100644 index 000000000000..f65e0acd2199 --- /dev/null +++ b/pkg/test/extensions/mirrored_images_test.go @@ -0,0 +1,255 @@ +package extensions + +import ( + "os" + "testing" + + "github.com/openshift-eng/openshift-tests-extension/pkg/extension" +) + +func TestComputeMirroredImages(t *testing.T) { + tests := []struct { + name string + extensions []*Extension + fromRepository string + wantCount int + wantMapping map[string]string + wantErr bool + }{ + { + name: "empty from-repository returns nil", + extensions: []*Extension{}, + fromRepository: "", + wantCount: 0, + }, + { + name: "no extensions returns nil", + extensions: []*Extension{}, + fromRepository: "quay.io/openshift/community-e2e-images", + wantCount: 0, + }, + { + name: "nil extension is skipped", + extensions: []*Extension{ + nil, + }, + fromRepository: "quay.io/openshift/community-e2e-images", + wantCount: 0, + }, + { + name: "image without Mapped uses computed tag", + extensions: []*Extension{ + { + Extension: &extension.Extension{ + Images: []extension.Image{ + { + Index: 100, + Registry: "registry.k8s.io", + Name: "e2e-test-images/agnhost", + Version: "2.55", + }, + }, + }, + }, + }, + fromRepository: "private.com/test/repo", + wantCount: 1, + }, + { + name: "image with Mapped uses mapped version", + extensions: []*Extension{ + { + Extension: &extension.Extension{ + Images: []extension.Image{ + { + Index: 200, + Registry: "registry.k8s.io", + Name: "e2e-test-images/busybox", + Version: "1.37.0-2", + Mapped: &extension.Image{ + Version: "custom-tag-v1", + }, + }, + }, + }, + }, + }, + fromRepository: "private.com/test/repo", + wantCount: 1, + wantMapping: map[string]string{ + "registry.k8s.io/e2e-test-images/busybox:1.37.0-2": "private.com/test/repo:custom-tag-v1", + }, + }, + { + name: "multiple extensions aggregate images", + extensions: []*Extension{ + { + Extension: &extension.Extension{ + Images: []extension.Image{ + { + Index: 1, + Registry: "quay.io", + Name: "test/image-a", + Version: "v1", + }, + }, + }, + }, + { + Extension: &extension.Extension{ + Images: []extension.Image{ + { + Index: 2, + Registry: "quay.io", + Name: "test/image-b", + Version: "v2", + }, + }, + }, + }, + }, + fromRepository: "private.com/mirror", + wantCount: 2, + }, + { + name: "invalid from-repository returns error", + extensions: []*Extension{}, + fromRepository: "://invalid", + wantErr: true, + }, + { + name: "from-repository without registry/namespace returns error", + extensions: []*Extension{}, + fromRepository: "mirror", + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + mapping, err := ComputeMirroredImages(tt.extensions, tt.fromRepository) + if (err != nil) != tt.wantErr { + t.Errorf("ComputeMirroredImages() error = %v, wantErr %v", err, tt.wantErr) + return + } + if tt.wantErr { + return + } + if len(mapping) != tt.wantCount { + t.Errorf("ComputeMirroredImages() returned %d mappings, want %d", len(mapping), tt.wantCount) + } + for original, expected := range tt.wantMapping { + if actual, ok := mapping[original]; !ok { + t.Errorf("missing mapping for %q", original) + } else if actual != expected { + t.Errorf("mapping[%q] = %q, want %q", original, actual, expected) + } + } + }) + } +} + +func TestWriteAndReadMirroredImagesFile(t *testing.T) { + mapping := map[string]string{ + "registry.k8s.io/e2e-test-images/agnhost:2.55": "private.com/repo:e2e-1-abc", + "quay.io/test/image:v1": "private.com/repo:e2e-custom", + } + + path, err := WriteMirroredImagesFile(mapping) + if err != nil { + t.Fatalf("WriteMirroredImagesFile() error = %v", err) + } + defer os.Remove(path) + + if path == "" { + t.Fatal("WriteMirroredImagesFile() returned empty path") + } + + read, err := ReadMirroredImagesFile(path) + if err != nil { + t.Fatalf("ReadMirroredImagesFile() error = %v", err) + } + + if len(read) != len(mapping) { + t.Errorf("read %d mappings, want %d", len(read), len(mapping)) + } + + for k, v := range mapping { + if read[k] != v { + t.Errorf("read[%q] = %q, want %q", k, read[k], v) + } + } +} + +func TestWriteMirroredImagesFileEmpty(t *testing.T) { + path, err := WriteMirroredImagesFile(nil) + if err != nil { + t.Fatalf("WriteMirroredImagesFile(nil) error = %v", err) + } + if path != "" { + t.Errorf("WriteMirroredImagesFile(nil) = %q, want empty", path) + } +} + +func TestMirroredLocationFor(t *testing.T) { + mapping := map[string]string{ + "registry.k8s.io/e2e-test-images/agnhost:2.55": "private.com/repo:e2e-1-abc", + } + + t.Run("mapped image returns mirrored pullspec", func(t *testing.T) { + got := MirroredLocationFor(mapping, "registry.k8s.io/e2e-test-images/agnhost:2.55") + want := "private.com/repo:e2e-1-abc" + if got != want { + t.Errorf("MirroredLocationFor() = %q, want %q", got, want) + } + }) + + t.Run("unmapped image returns original", func(t *testing.T) { + got := MirroredLocationFor(mapping, "quay.io/unknown/image:v1") + want := "quay.io/unknown/image:v1" + if got != want { + t.Errorf("MirroredLocationFor() = %q, want %q", got, want) + } + }) + + t.Run("nil mapping returns original", func(t *testing.T) { + got := MirroredLocationFor(nil, "quay.io/test:v1") + if got != "quay.io/test:v1" { + t.Errorf("MirroredLocationFor(nil) = %q, want original", got) + } + }) +} + +func TestLoadMirroredImagesFromEnv(t *testing.T) { + t.Run("unset env returns nil", func(t *testing.T) { + os.Unsetenv(MirroredImagesEnvVar) + mapping, err := LoadMirroredImagesFromEnv() + if err != nil { + t.Fatalf("LoadMirroredImagesFromEnv() error = %v", err) + } + if mapping != nil { + t.Errorf("LoadMirroredImagesFromEnv() = %v, want nil", mapping) + } + }) + + t.Run("set env loads file", func(t *testing.T) { + original := map[string]string{ + "quay.io/test:v1": "private.com/repo:mirrored-v1", + } + path, err := WriteMirroredImagesFile(original) + if err != nil { + t.Fatalf("WriteMirroredImagesFile() error = %v", err) + } + defer os.Remove(path) + + t.Setenv(MirroredImagesEnvVar, path) + + mapping, err := LoadMirroredImagesFromEnv() + if err != nil { + t.Fatalf("LoadMirroredImagesFromEnv() error = %v", err) + } + if mapping["quay.io/test:v1"] != "private.com/repo:mirrored-v1" { + t.Errorf("unexpected mapping: %v", mapping) + } + }) +} diff --git a/pkg/test/ginkgo/cmd_runsuite.go b/pkg/test/ginkgo/cmd_runsuite.go index 77448a01d10b..0ee9ea3c3e1c 100644 --- a/pkg/test/ginkgo/cmd_runsuite.go +++ b/pkg/test/ginkgo/cmd_runsuite.go @@ -354,6 +354,28 @@ func (o *GinkgoRunSuiteOptions) Run(suite *TestSuite, clusterConfig *clusterdisc logrus.Infof("Extension %s found in %s:%s using API version %s", id, e.Source.SourceImage, e.Source.SourceBinary, e.APIVersion) } + // Compute mirrored image mappings so extension binaries can resolve + // original image pull specs to their mirrored locations. + fromRepository := extractEnvValue(o.CommandEnv, "KUBE_TEST_REPO") + mirroredImages, err := extensions.ComputeMirroredImages(extensionsInfo, fromRepository) + if err != nil { + logrus.Warnf("Failed to compute mirrored images: %v", err) + } + if len(mirroredImages) > 0 { + mirroredImagesPath, err := extensions.WriteMirroredImagesFile(mirroredImages) + if err != nil { + return fmt.Errorf("failed to write mirrored images file: %w", err) + } + if !o.PrintCommands { + defer func() { + if err := os.Remove(mirroredImagesPath); err != nil { + logrus.Warnf("Failed to remove mirrored images file: %v", err) + } + }() + } + o.CommandEnv = append(o.CommandEnv, fmt.Sprintf("%s=%s", extensions.MirroredImagesEnvVar, mirroredImagesPath)) + } + // List tests from all available binaries and convert them to origin's testCase format listContext, listContextCancel := context.WithTimeout(context.Background(), 10*time.Minute) defer listContextCancel() @@ -1588,3 +1610,15 @@ func detectPreconditionChecks(tests []*testCase) *junitapi.JUnitTestCase { }, } } + +// extractEnvValue returns the value of a KEY=VALUE entry in env, or empty +// string if not found. +func extractEnvValue(env []string, key string) string { + prefix := key + "=" + for _, entry := range env { + if strings.HasPrefix(entry, prefix) { + return entry[len(prefix):] + } + } + return "" +}