diff --git a/internal/controller/dataplane/openstackdataplanenodeset_controller.go b/internal/controller/dataplane/openstackdataplanenodeset_controller.go index c800be2d23..648905033b 100644 --- a/internal/controller/dataplane/openstackdataplanenodeset_controller.go +++ b/internal/controller/dataplane/openstackdataplanenodeset_controller.go @@ -29,17 +29,22 @@ import ( rbacv1 "k8s.io/api/rbac/v1" k8s_errors "k8s.io/apimachinery/pkg/api/errors" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/builder" + "sigs.k8s.io/controller-runtime/pkg/cache" "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" + "sigs.k8s.io/controller-runtime/pkg/source" "github.com/go-logr/logr" infranetworkv1 "github.com/openstack-k8s-operators/infra-operator/apis/network/v1beta1" @@ -68,8 +73,11 @@ const ( // OpenStackDataPlaneNodeSetReconciler reconciles a OpenStackDataPlaneNodeSet object type OpenStackDataPlaneNodeSetReconciler struct { client.Client - Kclient kubernetes.Interface - Scheme *runtime.Scheme + Kclient kubernetes.Interface + Scheme *runtime.Scheme + Controller controller.Controller + Cache cache.Cache + Watching map[string]bool } // GetLogger returns a logger object with a prefix of "controller.name" and additional controller context fields @@ -141,6 +149,10 @@ func (r *OpenStackDataPlaneNodeSetReconciler) Reconcile(ctx context.Context, req Log := r.GetLogger(ctx) Log.Info("Reconciling NodeSet") + // Try to set up MachineConfig watch if not already done + // This is done conditionally because MachineConfig CRD may not exist on all clusters + r.ensureMachineConfigWatch(ctx) + validate := validator.New() // Fetch the OpenStackDataPlaneNodeSet instance @@ -669,7 +681,12 @@ func (r *OpenStackDataPlaneNodeSetReconciler) SetupWithManager( }); err != nil { return err } - return ctrl.NewControllerManagedBy(mgr). + // Initialize the Watching map for conditional CRD watches + r.Watching = make(map[string]bool) + r.Cache = mgr.GetCache() + + // Build the controller without MachineConfig watch (added conditionally later) + c, err := ctrl.NewControllerManagedBy(mgr). For(&dataplanev1.OpenStackDataPlaneNodeSet{}, builder.WithPredicates(predicate.Or( predicate.GenerationChangedPredicate{}, @@ -692,10 +709,15 @@ func (r *OpenStackDataPlaneNodeSetReconciler) SetupWithManager( builder.WithPredicates(predicate.ResourceVersionChangedPredicate{})). Watches(&openstackv1.OpenStackVersion{}, handler.EnqueueRequestsFromMapFunc(r.genericWatcherFn)). - Watches(&machineconfig.MachineConfig{}, - handler.EnqueueRequestsFromMapFunc(r.machineConfigWatcherFn), - builder.WithPredicates(predicate.ResourceVersionChangedPredicate{})). - Complete(r) + // NOTE: MachineConfig watch is added conditionally during reconciliation + // to avoid failures when the MachineConfig CRD doesn't exist + Build(r) + + if err != nil { + return err + } + r.Controller = c + return nil } // machineConfigWatcherFn - watches for changes to the registries MachineConfig resource and queues @@ -734,6 +756,70 @@ func (r *OpenStackDataPlaneNodeSetReconciler) machineConfigWatcherFn( return requests } +// machineConfigWatcherFnTyped - typed version of machineConfigWatcherFn for use with source.Kind +func (r *OpenStackDataPlaneNodeSetReconciler) machineConfigWatcherFnTyped( + ctx context.Context, obj *machineconfig.MachineConfig, +) []reconcile.Request { + return r.machineConfigWatcherFn(ctx, obj) +} + +const machineConfigCRDName = "machineconfigs.machineconfiguration.openshift.io" + +// ensureMachineConfigWatch attempts to set up a watch for MachineConfig resources. +// This is done conditionally because the MachineConfig CRD may not exist on all clusters +// (e.g., non-OpenShift Kubernetes clusters or clusters without the Machine Config Operator). +// Returns true if the CRD is available (watch was set up or already exists), false otherwise. +func (r *OpenStackDataPlaneNodeSetReconciler) ensureMachineConfigWatch(ctx context.Context) bool { + Log := r.GetLogger(ctx) + + // Check if we're already watching + if r.Watching[machineConfigCRDName] { + return true + } + + // Check if the MachineConfig CRD exists + crd := &unstructured.Unstructured{} + crd.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "apiextensions.k8s.io", + Kind: "CustomResourceDefinition", + Version: "v1", + }) + + err := r.Get(ctx, client.ObjectKey{Name: machineConfigCRDName}, crd) + if err != nil { + if k8s_errors.IsNotFound(err) { + Log.Info("MachineConfig CRD not found, disconnected environment features disabled") + } else { + Log.Error(err, "Error checking for MachineConfig CRD") + } + return false + } + + // CRD exists, set up the watch + Log.Info("MachineConfig CRD found, enabling watch for disconnected environment support") + err = r.Controller.Watch( + source.Kind( + r.Cache, + &machineconfig.MachineConfig{}, + handler.TypedEnqueueRequestsFromMapFunc(r.machineConfigWatcherFnTyped), + predicate.TypedResourceVersionChangedPredicate[*machineconfig.MachineConfig]{}, + ), + ) + if err != nil { + Log.Error(err, "Failed to set up MachineConfig watch") + return false + } + + r.Watching[machineConfigCRDName] = true + Log.Info("Successfully set up MachineConfig watch") + return true +} + +// IsMachineConfigAvailable returns true if the MachineConfig CRD is available and being watched +func (r *OpenStackDataPlaneNodeSetReconciler) IsMachineConfigAvailable() bool { + return r.Watching[machineConfigCRDName] +} + func (r *OpenStackDataPlaneNodeSetReconciler) secretWatcherFn( ctx context.Context, obj client.Object, ) []reconcile.Request { diff --git a/internal/dataplane/inventory.go b/internal/dataplane/inventory.go index d4c7e7e467..ade650c22a 100644 --- a/internal/dataplane/inventory.go +++ b/internal/dataplane/inventory.go @@ -144,13 +144,28 @@ func GenerateNodeSetInventory(ctx context.Context, helper *helper.Helper, if isDisconnected { registryConfig, err := util.GetMCRegistryConf(ctx, helper) if err != nil { - return "", err - } - helper.GetLogger().Info("disconnected registry was identified via the ImageContentSourcePolicy. Using OCP registry.") + // CRD not installed (non-OpenShift or no MCO) - log warning and continue. + // This allows graceful degradation when running on non-OpenShift clusters. + // Users can manually configure registries.conf via ansibleVars. + if util.IsNoMatchError(err) { + helper.GetLogger().Info("Disconnected environment detected but MachineConfig CRD not available. "+ + "Registry configuration will not be propagated to dataplane nodes. "+ + "You may need to configure registries.conf manually using ansibleVars "+ + "(edpm_podman_disconnected_ocp and edpm_podman_registries_conf).", + "error", err.Error()) + } else { + // CRD exists but resource not found, or other errors (network issues, + // permissions, etc.) - return the error. If MCO is installed but the + // registry MachineConfig doesn't exist, this indicates a misconfiguration. + return "", fmt.Errorf("failed to get MachineConfig registry configuration: %w", err) + } + } else { + helper.GetLogger().Info("disconnected registry was identified via the ImageContentSourcePolicy. Using OCP registry.") - // Use OCP registries.conf for disconnected deployments - nodeSetGroup.Vars["edpm_podman_registries_conf"] = registryConfig - nodeSetGroup.Vars["edpm_podman_disconnected_ocp"] = isDisconnected + // Use OCP registries.conf for disconnected deployments + nodeSetGroup.Vars["edpm_podman_registries_conf"] = registryConfig + nodeSetGroup.Vars["edpm_podman_disconnected_ocp"] = isDisconnected + } } // add TLS ansible variable diff --git a/internal/dataplane/util/image_registry.go b/internal/dataplane/util/image_registry.go index f22be79d02..066d9ca13d 100644 --- a/internal/dataplane/util/image_registry.go +++ b/internal/dataplane/util/image_registry.go @@ -38,27 +38,56 @@ type machineConfigIgnition struct { // IsDisconnectedOCP - Will retrieve a CR's related to disconnected OCP deployments. If the list is not // empty, we can infer that the OCP cluster is a disconnected deployment. +// Returns false without error if the CRDs don't exist (non-OpenShift cluster). func IsDisconnectedOCP(ctx context.Context, helper *helper.Helper) (bool, error) { icspList := ocpicsp.ImageContentSourcePolicyList{} idmsList := ocpidms.ImageDigestMirrorSetList{} listOpts := []client.ListOption{} - var err error - err = helper.GetClient().List(ctx, &icspList, listOpts...) + var icspCount, idmsCount int + + err := helper.GetClient().List(ctx, &icspList, listOpts...) if err != nil { - return false, err + // If the CRD doesn't exist, this is not an OpenShift cluster or ICSP is not available + // This is not an error condition - just means we're not in a disconnected environment + if IsNoMatchError(err) { + helper.GetLogger().Info("ImageContentSourcePolicy CRD not available, assuming not a disconnected environment") + } else { + return false, err + } + } else { + icspCount = len(icspList.Items) } + err = helper.GetClient().List(ctx, &idmsList, listOpts...) if err != nil { - return false, err + // If the CRD doesn't exist, this is not an OpenShift cluster or IDMS is not available + if IsNoMatchError(err) { + helper.GetLogger().Info("ImageDigestMirrorSet CRD not available, assuming not a disconnected environment") + } else { + return false, err + } + } else { + idmsCount = len(idmsList.Items) } - if len(icspList.Items) != 0 || len(idmsList.Items) != 0 { - return true, err + if icspCount != 0 || idmsCount != 0 { + return true, nil } - return false, err + return false, nil +} + +// IsNoMatchError checks if the error indicates that a CRD/resource type doesn't exist +func IsNoMatchError(err error) bool { + errStr := err.Error() + // Check for "no matches for kind" type errors which indicate the CRD doesn't exist. + // Also check for "no kind is registered" which occurs when the type isn't in the scheme. + // This is specifically needed for functional tests where the fake client returns a different + // error type than a real Kubernetes API server when CRDs are not installed. + return strings.Contains(errStr, "no matches for kind") || + strings.Contains(errStr, "no kind is registered") } // GetMCRegistryConf - will unmarshal the MachineConfig ignition file the machineConfigIgnition object. diff --git a/internal/dataplane/util/image_registry_test.go b/internal/dataplane/util/image_registry_test.go new file mode 100644 index 0000000000..7027ff2bd5 --- /dev/null +++ b/internal/dataplane/util/image_registry_test.go @@ -0,0 +1,498 @@ +/* +Copyright 2024. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package util + +import ( + "context" + "encoding/base64" + "errors" + "testing" + + . "github.com/onsi/gomega" //revive:disable:dot-imports + + ocpidms "github.com/openshift/api/config/v1" + mc "github.com/openshift/api/machineconfiguration/v1" + ocpicsp "github.com/openshift/api/operator/v1alpha1" + "github.com/openstack-k8s-operators/lib-common/modules/common/helper" + corev1 "github.com/openstack-k8s-operators/openstack-operator/api/core/v1beta1" + k8s_corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/fake" + "k8s.io/client-go/kubernetes/scheme" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + fakeclient "sigs.k8s.io/controller-runtime/pkg/client/fake" +) + +// setupTestHelper creates a fake client and helper for testing +// The includeOpenShiftCRDs parameter controls whether OpenShift-specific CRDs are registered +func setupTestHelper(includeOpenShiftCRDs bool, objects ...client.Object) *helper.Helper { + s := runtime.NewScheme() + _ = scheme.AddToScheme(s) + _ = corev1.AddToScheme(s) + _ = k8s_corev1.AddToScheme(s) + + if includeOpenShiftCRDs { + _ = ocpicsp.AddToScheme(s) + _ = ocpidms.AddToScheme(s) + _ = mc.AddToScheme(s) + } + + fakeClient := fakeclient.NewClientBuilder(). + WithScheme(s). + WithObjects(objects...). + Build() + + fakeKubeClient := fake.NewSimpleClientset() + + mockObj := &corev1.OpenStackControlPlane{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-controlplane", + Namespace: "test-namespace", + }, + } + + h, _ := helper.NewHelper( + mockObj, + fakeClient, + fakeKubeClient, + s, + ctrl.Log.WithName("test"), + ) + return h +} + +// Test IsNoMatchError +func TestIsNoMatchError(t *testing.T) { + tests := []struct { + name string + err error + expected bool + }{ + { + name: "no matches for kind error", + err: errors.New("no matches for kind \"ImageContentSourcePolicy\" in version \"operator.openshift.io/v1alpha1\""), + expected: true, + }, + { + name: "no matches for kind - IDMS", + err: errors.New("no matches for kind \"ImageDigestMirrorSet\" in version \"config.openshift.io/v1\""), + expected: true, + }, + { + name: "no matches for kind - MachineConfig", + err: errors.New("no matches for kind \"MachineConfig\" in version \"machineconfiguration.openshift.io/v1\""), + expected: true, + }, + { + name: "no kind is registered error (fake client)", + err: errors.New("no kind is registered for the type v1alpha1.ImageContentSourcePolicyList in scheme \"pkg/runtime/scheme.go:100\""), + expected: true, + }, + { + name: "no kind is registered - MachineConfig (fake client)", + err: errors.New("no kind is registered for the type v1.MachineConfig in scheme \"pkg/runtime/scheme.go:100\""), + expected: true, + }, + { + name: "not found error", + err: errors.New("machineconfigs.machineconfiguration.openshift.io \"99-master-generated-registries\" not found"), + expected: false, + }, + { + name: "generic error", + err: errors.New("connection refused"), + expected: false, + }, + { + name: "permission error", + err: errors.New("forbidden: User cannot list resource"), + expected: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + result := IsNoMatchError(tt.err) + g.Expect(result).To(Equal(tt.expected)) + }) + } +} + +// Test IsDisconnectedOCP scenarios +func TestIsDisconnectedOCP_WithICSP(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Create an ICSP resource + icsp := &ocpicsp.ImageContentSourcePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-icsp", + }, + Spec: ocpicsp.ImageContentSourcePolicySpec{ + RepositoryDigestMirrors: []ocpicsp.RepositoryDigestMirrors{ + { + Source: "registry.redhat.io", + Mirrors: []string{"local-registry.example.com"}, + }, + }, + }, + } + + h := setupTestHelper(true, icsp) + + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(disconnected).To(BeTrue(), "Should detect disconnected environment when ICSP exists") +} + +func TestIsDisconnectedOCP_WithIDMS(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Create an IDMS resource + idms := &ocpidms.ImageDigestMirrorSet{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-idms", + }, + Spec: ocpidms.ImageDigestMirrorSetSpec{ + ImageDigestMirrors: []ocpidms.ImageDigestMirrors{ + { + Source: "registry.redhat.io", + Mirrors: []ocpidms.ImageMirror{ + "local-registry.example.com", + }, + }, + }, + }, + } + + h := setupTestHelper(true, idms) + + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(disconnected).To(BeTrue(), "Should detect disconnected environment when IDMS exists") +} + +func TestIsDisconnectedOCP_WithBothICSPAndIDMS(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + icsp := &ocpicsp.ImageContentSourcePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-icsp", + }, + } + + idms := &ocpidms.ImageDigestMirrorSet{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-idms", + }, + } + + h := setupTestHelper(true, icsp, idms) + + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(disconnected).To(BeTrue(), "Should detect disconnected environment when both ICSP and IDMS exist") +} + +func TestIsDisconnectedOCP_EmptyLists(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // No ICSP or IDMS resources, but CRDs are registered + h := setupTestHelper(true) + + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(disconnected).To(BeFalse(), "Should not detect disconnected environment when lists are empty") +} + +func TestIsDisconnectedOCP_CRDsNotInstalled(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Don't register OpenShift CRDs - simulates non-OpenShift cluster + h := setupTestHelper(false) + + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred(), "Should not return error when CRDs don't exist") + g.Expect(disconnected).To(BeFalse(), "Should return false when CRDs don't exist (graceful degradation)") +} + +// Test GetMCRegistryConf scenarios +func TestGetMCRegistryConf_Success(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // The expected registries.conf content + expectedConfig := `[[registry]] + prefix = "" + location = "quay.io/openstack-k8s-operators" + + [[registry.mirror]] + location = "local-registry.example.com/openstack-k8s-operators" +` + + // Encode the config as the MachineConfig expects it + b64Config := base64.StdEncoding.EncodeToString([]byte(expectedConfig)) + ignitionConfig := `{ + "ignition": {"version": "3.2.0"}, + "storage": { + "files": [{ + "contents": { + "source": "data:text/plain;charset=utf-8;base64,` + b64Config + `" + }, + "path": "/etc/containers/registries.conf" + }] + } + }` + + machineConfig := &mc.MachineConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "99-master-generated-registries", + }, + Spec: mc.MachineConfigSpec{ + Config: runtime.RawExtension{ + Raw: []byte(ignitionConfig), + }, + }, + } + + h := setupTestHelper(true, machineConfig) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(config).To(Equal(expectedConfig)) +} + +func TestGetMCRegistryConf_MachineConfigNotFound(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // MachineConfig CRD is registered but no resource exists + // This simulates the case where MCO is installed but the specific + // registry MachineConfig doesn't exist - this should be treated as an error, + // not a warning, because if MCO is present and disconnected env is detected, + // the registry config should exist. + h := setupTestHelper(true) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("not found")) + // Verify this is NOT a "no match" error - it's a regular NotFound error + // which indicates the CRD exists but the resource doesn't + g.Expect(IsNoMatchError(err)).To(BeFalse(), + "NotFound error should NOT be treated as IsNoMatchError - CRD exists but resource doesn't") + g.Expect(config).To(BeEmpty()) +} + +func TestGetMCRegistryConf_CRDNotInstalled(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Don't register MachineConfig CRD - simulates non-OpenShift cluster + h := setupTestHelper(false) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(IsNoMatchError(err)).To(BeTrue(), "Error should be a 'no match' error indicating CRD doesn't exist") + g.Expect(config).To(BeEmpty()) +} + +func TestGetMCRegistryConf_InvalidIgnitionFormat(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Create MachineConfig with invalid JSON + machineConfig := &mc.MachineConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "99-master-generated-registries", + }, + Spec: mc.MachineConfigSpec{ + Config: runtime.RawExtension{ + Raw: []byte(`invalid json`), + }, + }, + } + + h := setupTestHelper(true, machineConfig) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(config).To(BeEmpty()) +} + +func TestGetMCRegistryConf_MissingBase64Prefix(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Create MachineConfig without the expected base64 prefix + ignitionConfig := `{ + "ignition": {"version": "3.2.0"}, + "storage": { + "files": [{ + "contents": { + "source": "plain-text-without-prefix" + }, + "path": "/etc/containers/registries.conf" + }] + } + }` + + machineConfig := &mc.MachineConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "99-master-generated-registries", + }, + Spec: mc.MachineConfigSpec{ + Config: runtime.RawExtension{ + Raw: []byte(ignitionConfig), + }, + }, + } + + h := setupTestHelper(true, machineConfig) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("no b64prefix found")) + g.Expect(config).To(BeEmpty()) +} + +func TestGetMCRegistryConf_InvalidBase64Content(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Create MachineConfig with invalid base64 content + ignitionConfig := `{ + "ignition": {"version": "3.2.0"}, + "storage": { + "files": [{ + "contents": { + "source": "data:text/plain;charset=utf-8;base64,!!!invalid-base64!!!" + }, + "path": "/etc/containers/registries.conf" + }] + } + }` + + machineConfig := &mc.MachineConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "99-master-generated-registries", + }, + Spec: mc.MachineConfigSpec{ + Config: runtime.RawExtension{ + Raw: []byte(ignitionConfig), + }, + }, + } + + h := setupTestHelper(true, machineConfig) + + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(config).To(BeEmpty()) +} + +// Test real-world scenarios +func TestDisconnectedEnvironment_FullScenario(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Simulate a full disconnected environment with IDMS and MachineConfig + expectedConfig := `[[registry]] + prefix = "" + location = "registry.redhat.io/rhosp-dev-preview" + + [[registry.mirror]] + location = "disconnected-registry.example.com:5000/rhosp-dev-preview" +` + + b64Config := base64.StdEncoding.EncodeToString([]byte(expectedConfig)) + ignitionConfig := `{ + "ignition": {"version": "3.2.0"}, + "storage": { + "files": [{ + "contents": { + "source": "data:text/plain;charset=utf-8;base64,` + b64Config + `" + }, + "path": "/etc/containers/registries.conf" + }] + } + }` + + idms := &ocpidms.ImageDigestMirrorSet{ + ObjectMeta: metav1.ObjectMeta{ + Name: "image-policy", + }, + Spec: ocpidms.ImageDigestMirrorSetSpec{ + ImageDigestMirrors: []ocpidms.ImageDigestMirrors{ + { + Source: "registry.redhat.io/rhosp-dev-preview", + Mirrors: []ocpidms.ImageMirror{ + "disconnected-registry.example.com:5000/rhosp-dev-preview", + }, + }, + }, + }, + } + + machineConfig := &mc.MachineConfig{ + ObjectMeta: metav1.ObjectMeta{ + Name: "99-master-generated-registries", + }, + Spec: mc.MachineConfigSpec{ + Config: runtime.RawExtension{ + Raw: []byte(ignitionConfig), + }, + }, + } + + h := setupTestHelper(true, idms, machineConfig) + + // Check for disconnected environment + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(disconnected).To(BeTrue()) + + // Get the registry configuration + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(config).To(Equal(expectedConfig)) +} + +func TestNonOpenShiftCluster_GracefulDegradation(t *testing.T) { + g := NewWithT(t) + ctx := context.Background() + + // Simulate a non-OpenShift Kubernetes cluster (no OpenShift CRDs registered) + h := setupTestHelper(false) + + // IsDisconnectedOCP should return false without error + disconnected, err := IsDisconnectedOCP(ctx, h) + g.Expect(err).ToNot(HaveOccurred(), "Should gracefully handle missing CRDs") + g.Expect(disconnected).To(BeFalse()) + + // GetMCRegistryConf should return an error that can be identified as "CRD not found" + config, err := GetMCRegistryConf(ctx, h) + g.Expect(err).To(HaveOccurred()) + g.Expect(IsNoMatchError(err)).To(BeTrue(), "Error should indicate CRD is not installed") + g.Expect(config).To(BeEmpty()) +}