|
| 1 | +/* |
| 2 | +Copyright 2026 The Kubernetes Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package controller |
| 18 | + |
| 19 | +import ( |
| 20 | + "bytes" |
| 21 | + "context" |
| 22 | + "fmt" |
| 23 | + |
| 24 | + corev1 "k8s.io/api/core/v1" |
| 25 | + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 26 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 27 | + apijson "k8s.io/apimachinery/pkg/util/json" |
| 28 | + "k8s.io/client-go/kubernetes/scheme" |
| 29 | + operatorv1 "sigs.k8s.io/cluster-api-operator/api/v1alpha2" |
| 30 | + "sigs.k8s.io/cluster-api/cmd/clusterctl/client/repository" |
| 31 | + "sigs.k8s.io/cluster-api/cmd/clusterctl/client/yamlprocessor" |
| 32 | + ctrl "sigs.k8s.io/controller-runtime" |
| 33 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 34 | +) |
| 35 | + |
| 36 | +// Fetch fetches the provider components from the repository and processes all yaml manifests. |
| 37 | +func (p *PhaseReconciler) Fetch(ctx context.Context) (*Result, error) { |
| 38 | + log := ctrl.LoggerFrom(ctx) |
| 39 | + log.Info("Fetching provider") |
| 40 | + |
| 41 | + // Fetch the provider components yaml file from the provided repository GitHub/GitLab/ConfigMap. |
| 42 | + componentsFile, err := p.repo.GetFile(ctx, p.options.Version, p.repo.ComponentsPath()) |
| 43 | + if err != nil { |
| 44 | + err = fmt.Errorf("failed to read %q from provider's repository %q: %w", p.repo.ComponentsPath(), p.providerConfig.ManifestLabel(), err) |
| 45 | + |
| 46 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsFetchErrorReason, operatorv1.ProviderInstalledCondition) |
| 47 | + } |
| 48 | + |
| 49 | + // Check if components exceed the resource size. |
| 50 | + p.needsCompression = needToCompress(componentsFile) |
| 51 | + |
| 52 | + // Generate a set of new objects using the clusterctl library. NewComponents() will do the yaml processing, |
| 53 | + // like ensure all the provider components are in proper namespace, replace variables, etc. See the clusterctl |
| 54 | + // documentation for more details. |
| 55 | + p.components, err = repository.NewComponents(repository.ComponentsInput{ |
| 56 | + Provider: p.providerConfig, |
| 57 | + ConfigClient: p.configClient, |
| 58 | + Processor: yamlprocessor.NewSimpleProcessor(), |
| 59 | + RawYaml: componentsFile, |
| 60 | + Options: p.options, |
| 61 | + }) |
| 62 | + if err != nil { |
| 63 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsFetchErrorReason, operatorv1.ProviderInstalledCondition) |
| 64 | + } |
| 65 | + |
| 66 | + // ProviderSpec provides fields for customizing the provider deployment options. |
| 67 | + // We can use clusterctl library to apply this customizations. |
| 68 | + if err := repository.AlterComponents(p.components, customizeObjectsFn(p.provider)); err != nil { |
| 69 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 70 | + } |
| 71 | + |
| 72 | + // Apply patches to the provider components if specified. |
| 73 | + if err := repository.AlterComponents(p.components, applyPatches(ctx, p.provider)); err != nil { |
| 74 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsPatchErrorReason, operatorv1.ProviderInstalledCondition) |
| 75 | + } |
| 76 | + |
| 77 | + // Apply image overrides to the provider manifests. |
| 78 | + if err := repository.AlterComponents(p.components, imageOverrides(p.components.ManifestLabel(), p.overridesClient)); err != nil { |
| 79 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsImageOverrideErrorReason, operatorv1.ProviderInstalledCondition) |
| 80 | + } |
| 81 | + |
| 82 | + for _, fn := range p.customAlterComponentsFuncs { |
| 83 | + if err := repository.AlterComponents(p.components, fn); err != nil { |
| 84 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + return &Result{}, nil |
| 89 | +} |
| 90 | + |
| 91 | +// Store stores the provider components in the cache. |
| 92 | +func (p *PhaseReconciler) Store(ctx context.Context) (*Result, error) { |
| 93 | + log := ctrl.LoggerFrom(ctx) |
| 94 | + log.Info("Storing provider in cache") |
| 95 | + |
| 96 | + kinds, _, err := scheme.Scheme.ObjectKinds(&corev1.Secret{}) |
| 97 | + if err != nil || len(kinds) == 0 { |
| 98 | + log.Error(err, "cannot fetch kind of the Secret resource") |
| 99 | + err = fmt.Errorf("cannot fetch kind of the Secret resource: %w", err) |
| 100 | + |
| 101 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 102 | + } |
| 103 | + |
| 104 | + secret := &corev1.Secret{ |
| 105 | + TypeMeta: metav1.TypeMeta{ |
| 106 | + Kind: kinds[0].Kind, |
| 107 | + APIVersion: kinds[0].GroupVersion().String(), |
| 108 | + }, |
| 109 | + ObjectMeta: metav1.ObjectMeta{ |
| 110 | + Name: ProviderCacheName(p.provider), |
| 111 | + Namespace: p.provider.GetNamespace(), |
| 112 | + Annotations: map[string]string{}, |
| 113 | + }, |
| 114 | + StringData: map[string]string{}, |
| 115 | + Data: map[string][]byte{}, |
| 116 | + } |
| 117 | + |
| 118 | + gvk := p.provider.GetObjectKind().GroupVersionKind() |
| 119 | + |
| 120 | + secret.SetOwnerReferences([]metav1.OwnerReference{ |
| 121 | + { |
| 122 | + APIVersion: gvk.GroupVersion().String(), |
| 123 | + Kind: gvk.Kind, |
| 124 | + Name: p.provider.GetName(), |
| 125 | + UID: p.provider.GetUID(), |
| 126 | + }, |
| 127 | + }) |
| 128 | + |
| 129 | + if p.needsCompression { |
| 130 | + secret.Annotations[operatorv1.CompressedAnnotation] = "true" |
| 131 | + } |
| 132 | + |
| 133 | + manifests, err := apijson.Marshal(addNamespaceIfMissing(p.components.Objs(), p.provider.GetNamespace())) |
| 134 | + if err != nil { |
| 135 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 136 | + } |
| 137 | + |
| 138 | + if p.needsCompression { |
| 139 | + var buf bytes.Buffer |
| 140 | + if err := compressData(&buf, manifests); err != nil { |
| 141 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 142 | + } |
| 143 | + |
| 144 | + secret.Data["cache"] = buf.Bytes() |
| 145 | + } else { |
| 146 | + secret.StringData["cache"] = string(manifests) |
| 147 | + } |
| 148 | + |
| 149 | + if err := p.ctrlClient.Patch(ctx, secret, client.Apply, client.ForceOwnership, client.FieldOwner(cacheOwner)); err != nil { |
| 150 | + log.Error(err, "failed to apply cache config map") |
| 151 | + |
| 152 | + return &Result{}, wrapPhaseError(err, operatorv1.ComponentsCustomizationErrorReason, operatorv1.ProviderInstalledCondition) |
| 153 | + } |
| 154 | + |
| 155 | + return &Result{}, nil |
| 156 | +} |
| 157 | + |
| 158 | +// addNamespaceIfMissing adda a Namespace object if missing (this ensure the targetNamespace will be created). |
| 159 | +func addNamespaceIfMissing(objs []unstructured.Unstructured, targetNamespace string) []unstructured.Unstructured { |
| 160 | + namespaceObjectFound := false |
| 161 | + |
| 162 | + for _, o := range objs { |
| 163 | + // if the object has Kind Namespace, fix the namespace name |
| 164 | + if o.GetKind() == namespaceKind { |
| 165 | + namespaceObjectFound = true |
| 166 | + } |
| 167 | + } |
| 168 | + |
| 169 | + // if there isn't an object with Kind Namespace, add it |
| 170 | + if !namespaceObjectFound { |
| 171 | + objs = append(objs, unstructured.Unstructured{ |
| 172 | + Object: map[string]interface{}{ |
| 173 | + "apiVersion": "v1", |
| 174 | + "kind": namespaceKind, |
| 175 | + "metadata": map[string]interface{}{ |
| 176 | + "name": targetNamespace, |
| 177 | + }, |
| 178 | + }, |
| 179 | + }) |
| 180 | + } |
| 181 | + |
| 182 | + return objs |
| 183 | +} |
| 184 | + |
| 185 | +func (p *PhaseReconciler) ReportStatus(_ context.Context) (*Result, error) { |
| 186 | + status := p.provider.GetStatus() |
| 187 | + status.Contract = &p.contract |
| 188 | + installedVersion := p.components.Version() |
| 189 | + status.InstalledVersion = &installedVersion |
| 190 | + p.provider.SetStatus(status) |
| 191 | + |
| 192 | + return &Result{}, nil |
| 193 | +} |
0 commit comments