diff --git a/api/v1beta1/clustersummary_types.go b/api/v1beta1/clustersummary_types.go index 9aa7a3ee..90679411 100644 --- a/api/v1beta1/clustersummary_types.go +++ b/api/v1beta1/clustersummary_types.go @@ -51,6 +51,22 @@ type FeatureSummary struct { // +optional Hash []byte `json:"hash,omitempty"` + // ReferenceHashes records, for each resource the feature configuration depends on (referenced + // ConfigMaps, Secrets and sources, templateResourceRefs), a short hash of its content at the time + // Hash was computed. Comparing it with the current content tells which resource changed when the + // feature has changes not deployed yet (see ClusterSummary Status.PendingFeatures). + // It always describes the configuration Hash was computed from. Not used by the Helm feature: + // HelmReleaseSummaries already records the same information. + // +listType=atomic + // +optional + ReferenceHashes []ReferenceHash `json:"referenceHashes,omitempty"` + + // ReferencesRecorded is true when ReferenceHashes was recorded together with Hash. An empty + // ReferenceHashes then means the feature depends on no resource. It is false for a feature last + // deployed by a version that did not record ReferenceHashes. + // +optional + ReferencesRecorded bool `json:"referencesRecorded,omitempty"` + // The number of consecutive deployment failures. // +optional ConsecutiveFailures uint `json:"consecutiveFailures,omitempty"` @@ -92,6 +108,41 @@ type FeatureSummary struct { DriftHistory *DriftHistory `json:"driftHistory,omitempty"` } +// ReferenceSource tells where a resource a feature depends on is referenced from +// +kubebuilder:validation:Enum:=PolicyRef;KustomizationRef;TemplateResourceRef +type ReferenceSource string + +const ( + // ReferenceSourcePolicyRef is a resource referenced in the PolicyRefs section + ReferenceSourcePolicyRef = ReferenceSource("PolicyRef") + + // ReferenceSourceKustomizationRef is a resource referenced in the KustomizationRefs section + ReferenceSourceKustomizationRef = ReferenceSource("KustomizationRef") + + // ReferenceSourceTemplateResourceRef is a management cluster resource referenced in the + // TemplateResourceRefs section + ReferenceSourceTemplateResourceRef = ReferenceSource("TemplateResourceRef") +) + +// ReferenceHash is a short hash of the content of a resource a feature depends on. +type ReferenceHash struct { + // Source tells where the resource is referenced from + Source ReferenceSource `json:"source"` + + // Kind of the resource + Kind string `json:"kind"` + + // Namespace of the resource. Empty for cluster scoped resources. + // +optional + Namespace string `json:"namespace,omitempty"` + + // Name of the resource + Name string `json:"name"` + + // Hash is a short hash of the content of the resource + Hash string `json:"hash"` +} + // DriftHistory describes the configuration drifts detected on the resources deployed by a feature. type DriftHistory struct { // LastDetectedTime is when the most recent drift was detected. When the component that @@ -306,6 +357,106 @@ type ClusterSummaryStatus struct { // SuspensionReason provides a brief explanation of why the reconciliation is suspended. // +optional SuspensionReason *string `json:"suspensionReason,omitempty"` + + // PendingFeatures lists the features whose desired configuration differs from what is currently + // deployed. It is only populated while reconciliation is suspended (for instance because the + // cluster is paused): in that state nothing is deployed, so this tells which features will be + // redeployed once reconciliation resumes. It is evaluated each time the ClusterSummary is + // reconciled while suspended, so it reflects the state at that moment. Cleared when reconciliation + // resumes. + // +listType=map + // +listMapKey=featureID + // +optional + PendingFeatures []PendingFeature `json:"pendingFeatures,omitempty"` +} + +// PendingFeatureReason explains why a feature is listed in ClusterSummary Status.PendingFeatures +// +kubebuilder:validation:Enum:=ConfigurationChanged;NotDeployed;PendingRemoval;EvaluationFailed +type PendingFeatureReason string + +const ( + // PendingReasonConfigurationChanged indicates the feature is deployed but its desired + // configuration is different from the one deployed + PendingReasonConfigurationChanged = PendingFeatureReason("ConfigurationChanged") + + // PendingReasonNotDeployed indicates the feature is configured but has not been successfully + // deployed yet + PendingReasonNotDeployed = PendingFeatureReason("NotDeployed") + + // PendingReasonPendingRemoval indicates the feature is deployed but it is not configured + // anymore, so it will be removed + PendingReasonPendingRemoval = PendingFeatureReason("PendingRemoval") + + // PendingReasonEvaluationFailed indicates it was not possible to establish whether the + // feature has pending changes. Message contains the error. + PendingReasonEvaluationFailed = PendingFeatureReason("EvaluationFailed") +) + +// PendingFeature describes a feature with changes that are not deployed yet. +type PendingFeature struct { + // FeatureID is an identifier of the feature with pending changes + FeatureID libsveltosv1beta1.FeatureID `json:"featureID"` + + // Reason is why the feature has pending changes + Reason PendingFeatureReason `json:"reason"` + + // Message provides more information. Set when Reason is EvaluationFailed, or when Items does not + // tell the whole story (for instance Items is empty because what changed cannot be attributed + // to a referenced resource). + // +optional + Message *string `json:"message,omitempty"` + + // Items lists what changed in the feature configuration, when it can be established. + // For raw YAML and Kustomize a referenced resource is reported as a whole: which part of it + // changed is not reported. Changes that cannot be attributed to an item (the profile settings, + // or content fetched from a remote URL) are not listed. + // +listType=atomic + // +optional + Items []PendingItem `json:"items,omitempty"` + + // ItemsTruncated is true when more than MaxPendingItems items changed, so Items is not complete. + // +optional + ItemsTruncated bool `json:"itemsTruncated,omitempty"` +} + +const ( + // MaxPendingItems is the maximum number of items reported for a feature + MaxPendingItems = 50 +) + +// PendingChange is what happened to an item since the feature was last deployed +// +kubebuilder:validation:Enum:=Added;Removed;Changed +type PendingChange string + +const ( + // PendingChangeAdded indicates the item is part of the configuration but was not deployed yet + PendingChangeAdded = PendingChange("Added") + + // PendingChangeRemoved indicates the item is not part of the configuration anymore but is still deployed + PendingChangeRemoved = PendingChange("Removed") + + // PendingChangeChanged indicates the item is deployed but its desired content is different + PendingChangeChanged = PendingChange("Changed") +) + +// PendingItem describes one change not deployed yet. +type PendingItem struct { + // Kind of the item: the kind of the referenced resource, or HelmChart + Kind string `json:"kind"` + + // Namespace of the item. For a HelmChart it is the release namespace. + // +optional + Namespace string `json:"namespace,omitempty"` + + // Name of the item. For a HelmChart it is the release name. + Name string `json:"name"` + + // Change is what happened to the item + Change PendingChange `json:"change"` + + // Detail provides more information, for instance what changed in a HelmChart + // +optional + Detail string `json:"detail,omitempty"` } //nolint: lll // marker @@ -314,6 +465,7 @@ type ClusterSummaryStatus struct { // +kubebuilder:subresource:status // +kubebuilder:storageversion // +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp",description="Time duration since creation of ClusterSummary" +// +kubebuilder:printcolumn:name="Pending",type="string",JSONPath=".status.pendingFeatures[*].featureID",description="Features with changes not deployed because reconciliation is suspended" // +kubebuilder:printcolumn:name="HelmCharts",type="string",JSONPath=".status.featureSummaries[?(@.featureID==\"Helm\")].status",description="Indicates whether HelmCharts are all provisioned",priority=2 // +kubebuilder:printcolumn:name="KustomizeRefs",type="string",JSONPath=".status.featureSummaries[?(@.featureID==\"Kustomize\")].status",description="Indicates whether KustomizeRefs are all provisioned",priority=2 // +kubebuilder:printcolumn:name="PolicyRefs",type="string",JSONPath=".status.featureSummaries[?(@.featureID==\"Resources\")].status",description="Indicates whether PolicyRefs are all provisioned",priority=2 diff --git a/api/v1beta1/zz_generated.deepcopy.go b/api/v1beta1/zz_generated.deepcopy.go index 9eb73290..e221219e 100644 --- a/api/v1beta1/zz_generated.deepcopy.go +++ b/api/v1beta1/zz_generated.deepcopy.go @@ -606,6 +606,13 @@ func (in *ClusterSummaryStatus) DeepCopyInto(out *ClusterSummaryStatus) { *out = new(string) **out = **in } + if in.PendingFeatures != nil { + in, out := &in.PendingFeatures, &out.PendingFeatures + *out = make([]PendingFeature, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterSummaryStatus. @@ -798,6 +805,11 @@ func (in *FeatureSummary) DeepCopyInto(out *FeatureSummary) { *out = make([]byte, len(*in)) copy(*out, *in) } + if in.ReferenceHashes != nil { + in, out := &in.ReferenceHashes, &out.ReferenceHashes + *out = make([]ReferenceHash, len(*in)) + copy(*out, *in) + } if in.FailureReason != nil { in, out := &in.FailureReason, &out.FailureReason *out = new(string) @@ -1169,6 +1181,46 @@ func (in *OIDCIdentityMatcher) DeepCopy() *OIDCIdentityMatcher { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PendingFeature) DeepCopyInto(out *PendingFeature) { + *out = *in + if in.Message != nil { + in, out := &in.Message, &out.Message + *out = new(string) + **out = **in + } + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]PendingItem, len(*in)) + copy(*out, *in) + } +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PendingFeature. +func (in *PendingFeature) DeepCopy() *PendingFeature { + if in == nil { + return nil + } + out := new(PendingFeature) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *PendingItem) DeepCopyInto(out *PendingItem) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PendingItem. +func (in *PendingItem) DeepCopy() *PendingItem { + if in == nil { + return nil + } + out := new(PendingItem) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PolicyRef) DeepCopyInto(out *PolicyRef) { *out = *in @@ -1401,6 +1453,21 @@ func (in *ProvenanceVerification) DeepCopy() *ProvenanceVerification { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ReferenceHash) DeepCopyInto(out *ReferenceHash) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ReferenceHash. +func (in *ReferenceHash) DeepCopy() *ReferenceHash { + if in == nil { + return nil + } + out := new(ReferenceHash) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RegistryCredentialsConfig) DeepCopyInto(out *RegistryCredentialsConfig) { *out = *in diff --git a/config/crd/bases/config.projectsveltos.io_clustersummaries.yaml b/config/crd/bases/config.projectsveltos.io_clustersummaries.yaml index 403d1b99..fef53afd 100644 --- a/config/crd/bases/config.projectsveltos.io_clustersummaries.yaml +++ b/config/crd/bases/config.projectsveltos.io_clustersummaries.yaml @@ -19,6 +19,10 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + - description: Features with changes not deployed because reconciliation is suspended + jsonPath: .status.pendingFeatures[*].featureID + name: Pending + type: string - description: Indicates whether HelmCharts are all provisioned jsonPath: .status.featureSummaries[?(@.featureID=="Helm")].status name: HelmCharts @@ -2597,6 +2601,54 @@ spec: description: LastAppliedTime is the time feature was last reconciled format: date-time type: string + referenceHashes: + description: |- + ReferenceHashes records, for each resource the feature configuration depends on (referenced + ConfigMaps, Secrets and sources, templateResourceRefs), a short hash of its content at the time + Hash was computed. Comparing it with the current content tells which resource changed when the + feature has changes not deployed yet (see ClusterSummary Status.PendingFeatures). + It always describes the configuration Hash was computed from. Not used by the Helm feature: + HelmReleaseSummaries already records the same information. + items: + description: ReferenceHash is a short hash of the content + of a resource a feature depends on. + properties: + hash: + description: Hash is a short hash of the content of the + resource + type: string + kind: + description: Kind of the resource + type: string + name: + description: Name of the resource + type: string + namespace: + description: Namespace of the resource. Empty for cluster + scoped resources. + type: string + source: + description: Source tells where the resource is referenced + from + enum: + - PolicyRef + - KustomizationRef + - TemplateResourceRef + type: string + required: + - hash + - kind + - name + - source + type: object + type: array + x-kubernetes-list-type: atomic + referencesRecorded: + description: |- + ReferencesRecorded is true when ReferenceHashes was recorded together with Hash. An empty + ReferenceHashes then means the feature depends on no resource. It is false for a feature last + deployed by a version that did not record ReferenceHashes. + type: boolean resourceSummaryDeployed: description: |- ResourceSummaryDeployed tracks whether a ResourceSummary was deployed @@ -2748,6 +2800,92 @@ spec: If not set, reconciliations will happen as usual. format: date-time type: string + pendingFeatures: + description: |- + PendingFeatures lists the features whose desired configuration differs from what is currently + deployed. It is only populated while reconciliation is suspended (for instance because the + cluster is paused): in that state nothing is deployed, so this tells which features will be + redeployed once reconciliation resumes. It is evaluated each time the ClusterSummary is + reconciled while suspended, so it reflects the state at that moment. Cleared when reconciliation + resumes. + items: + description: PendingFeature describes a feature with changes that + are not deployed yet. + properties: + featureID: + description: FeatureID is an identifier of the feature with + pending changes + enum: + - Resources + - Helm + - Kustomize + type: string + items: + description: |- + Items lists what changed in the feature configuration, when it can be established. + For raw YAML and Kustomize a referenced resource is reported as a whole: which part of it + changed is not reported. Changes that cannot be attributed to an item (the profile settings, + or content fetched from a remote URL) are not listed. + items: + description: PendingItem describes one change not deployed + yet. + properties: + change: + description: Change is what happened to the item + enum: + - Added + - Removed + - Changed + type: string + detail: + description: Detail provides more information, for instance + what changed in a HelmChart + type: string + kind: + description: 'Kind of the item: the kind of the referenced + resource, or HelmChart' + type: string + name: + description: Name of the item. For a HelmChart it is the + release name. + type: string + namespace: + description: Namespace of the item. For a HelmChart it + is the release namespace. + type: string + required: + - change + - kind + - name + type: object + type: array + x-kubernetes-list-type: atomic + itemsTruncated: + description: ItemsTruncated is true when more than MaxPendingItems + items changed, so Items is not complete. + type: boolean + message: + description: |- + Message provides more information. Set when Reason is EvaluationFailed, or when Items does not + tell the whole story (for instance Items is empty because what changed cannot be attributed + to a referenced resource). + type: string + reason: + description: Reason is why the feature has pending changes + enum: + - ConfigurationChanged + - NotDeployed + - PendingRemoval + - EvaluationFailed + type: string + required: + - featureID + - reason + type: object + type: array + x-kubernetes-list-map-keys: + - featureID + x-kubernetes-list-type: map reconciliationSuspended: description: |- ReconciliationSuspended indicates whether the reconciliation loop for this diff --git a/controllers/clustersummary_controller.go b/controllers/clustersummary_controller.go index c13d00cb..8bbd1317 100644 --- a/controllers/clustersummary_controller.go +++ b/controllers/clustersummary_controller.go @@ -619,11 +619,14 @@ func (r *ClusterSummaryReconciler) reconcileNormal(ctx context.Context, clusterSummaryScope.ClusterSummary.Status.ReconciliationSuspended = true suspensionReason := clusterPausedMessage clusterSummaryScope.ClusterSummary.Status.SuspensionReason = &suspensionReason + // Nothing is deployed, but record which features have changes waiting for the cluster to be unpaused + r.updatePendingFeatures(ctx, clusterSummaryScope, logger) return reconcile.Result{}, nil } clusterSummaryScope.ClusterSummary.Status.ReconciliationSuspended = false clusterSummaryScope.ClusterSummary.Status.SuspensionReason = nil + clusterSummaryScope.ClusterSummary.Status.PendingFeatures = nil if result := r.prepareForDeployment(ctx, clusterSummaryScope, logger); result.RequeueAfter > 0 { return result, nil diff --git a/controllers/clustersummary_deployer.go b/controllers/clustersummary_deployer.go index dc0d3783..98b4a1c0 100644 --- a/controllers/clustersummary_deployer.go +++ b/controllers/clustersummary_deployer.go @@ -60,17 +60,19 @@ func startDriftDetectionInMgmtCluster(o deployer.Options) bool { return runInMgtmCluster } -type getCurrentHash func(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, - logger logr.Logger) ([]byte, error) +// getCurrentConfiguration returns the hash of the current configuration of a feature, and the hash of each +// one of the resources the configuration depends on. +type getCurrentConfiguration func(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, + logger logr.Logger) (hash []byte, references []configv1beta1.ReferenceHash, err error) type getPolicyRefs func(clusterSummary *configv1beta1.ClusterSummary) []configv1beta1.PolicyRef type feature struct { - id libsveltosv1beta1.FeatureID - currentHash getCurrentHash - deploy deployer.RequestHandler - undeploy deployer.RequestHandler - getRefs getPolicyRefs + id libsveltosv1beta1.FeatureID + currentConfiguration getCurrentConfiguration + deploy deployer.RequestHandler + undeploy deployer.RequestHandler + getRefs getPolicyRefs } func (r *ClusterSummaryReconciler) deployFeature(ctx context.Context, clusterSummaryScope *scope.ClusterSummaryScope, @@ -99,7 +101,7 @@ func (r *ClusterSummaryReconciler) deployFeature(ctx context.Context, clusterSum } // Get hash of current configuration (at this very precise moment) - currentHash, err := f.currentHash(ctx, r.Client, clusterSummary, logger) + currentHash, references, err := f.currentConfiguration(ctx, r.Client, clusterSummary, logger) if err != nil { var nrErr *configv1beta1.NonRetriableError if !errors.As(err, &nrErr) && !apierrors.IsNotFound(err) { @@ -108,6 +110,8 @@ func (r *ClusterSummaryReconciler) deployFeature(ctx context.Context, clusterSum return err } } + // Whenever currentHash is recorded in the status, so are the references it was computed from + clusterSummaryScope.StageReferenceHashes(f.id, currentHash, references) storedHash := r.getHash(clusterSummaryScope, f.id) isConfigSame := reflect.DeepEqual(storedHash, currentHash) diff --git a/controllers/clustersummary_features.go b/controllers/clustersummary_features.go index 3ab617e5..47f7b5db 100644 --- a/controllers/clustersummary_features.go +++ b/controllers/clustersummary_features.go @@ -52,13 +52,13 @@ func creatFeatureHandlerMaps() { featuresHandlers = make(map[libsveltosv1beta1.FeatureID]feature) featuresHandlers[libsveltosv1beta1.FeatureResources] = feature{id: libsveltosv1beta1.FeatureResources, - currentHash: resourcesHash, deploy: deployResources, undeploy: undeployResources, getRefs: getResourceRefs} + currentConfiguration: resourcesConfiguration, deploy: deployResources, undeploy: undeployResources, getRefs: getResourceRefs} featuresHandlers[libsveltosv1beta1.FeatureHelm] = feature{id: libsveltosv1beta1.FeatureHelm, - currentHash: helmHash, deploy: deployHelmCharts, undeploy: undeployHelmCharts, getRefs: getHelmRefs} + currentConfiguration: helmConfiguration, deploy: deployHelmCharts, undeploy: undeployHelmCharts, getRefs: getHelmRefs} featuresHandlers[libsveltosv1beta1.FeatureKustomize] = feature{id: libsveltosv1beta1.FeatureKustomize, - currentHash: kustomizationHash, deploy: deployKustomizeRefs, undeploy: undeployKustomizeRefs, + currentConfiguration: kustomizationConfiguration, deploy: deployKustomizeRefs, undeploy: undeployKustomizeRefs, getRefs: getKustomizationRefs} } diff --git a/controllers/clustersummary_pending.go b/controllers/clustersummary_pending.go new file mode 100644 index 00000000..3ca363e1 --- /dev/null +++ b/controllers/clustersummary_pending.go @@ -0,0 +1,134 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers + +import ( + "context" + "errors" + "reflect" + + "github.com/go-logr/logr" + apierrors "k8s.io/apimachinery/pkg/api/errors" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + "github.com/projectsveltos/addon-controller/pkg/scope" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" + logs "github.com/projectsveltos/libsveltos/lib/logsettings" +) + +// updatePendingFeatures sets ClusterSummary Status.PendingFeatures: the features whose desired +// configuration differs from what was last deployed. +// It is meant to be called when reconciliation is suspended (for instance cluster is paused). +// Nothing is deployed: for each feature it only does what deployFeature does before deciding whether +// to redeploy, which is comparing the hash of the desired configuration (computed from objects in the +// management cluster only) with the hash stored when the feature was last deployed. +func (r *ClusterSummaryReconciler) updatePendingFeatures(ctx context.Context, + clusterSummaryScope *scope.ClusterSummaryScope, logger logr.Logger) { + + clusterSummary := clusterSummaryScope.ClusterSummary + + // A ClusterSummary in DryRun mode never deploys anything, so there is nothing pending + if clusterSummaryScope.IsDryRunSync() { + clusterSummary.Status.PendingFeatures = nil + return + } + + var pendingFeatures []configv1beta1.PendingFeature + for _, featureID := range featureIDs { + f := getHandlersForFeature(featureID) + pendingFeature := r.getPendingFeature(ctx, clusterSummary, f, logger) + if pendingFeature != nil { + pendingFeatures = append(pendingFeatures, *pendingFeature) + } + } + + clusterSummary.Status.PendingFeatures = pendingFeatures +} + +// getPendingFeature returns a PendingFeature if feature has changes not deployed yet, nil otherwise. +func (r *ClusterSummaryReconciler) getPendingFeature(ctx context.Context, + clusterSummary *configv1beta1.ClusterSummary, f feature, logger logr.Logger, +) *configv1beta1.PendingFeature { + + configured := isFeatureConfigured(clusterSummary, f.id) + featureSummary := getFeatureSummaryForFeatureID(clusterSummary, f.id) + + // Same condition deployFeature is called under: feature is not configured and was never deployed. + if !configured && featureSummary == nil { + return nil + } + + currentHash, currentReferences, err := f.currentConfiguration(ctx, r.Client, clusterSummary, logger) + if err != nil { + // Same errors deployFeature tolerates. Any other error means hash cannot be trusted. + var nrErr *configv1beta1.NonRetriableError + if !errors.As(err, &nrErr) && !apierrors.IsNotFound(err) { + logger.V(logs.LogInfo).Info("failed to evaluate pending changes", "feature", string(f.id), "error", err.Error()) + message := err.Error() + return &configv1beta1.PendingFeature{ + FeatureID: f.id, + Reason: configv1beta1.PendingReasonEvaluationFailed, + Message: &message, + } + } + } + + reason := getPendingReason(configured, featureSummary, currentHash) + if reason == "" { + return nil + } + + pendingFeature := &configv1beta1.PendingFeature{FeatureID: f.id, Reason: reason} + setPendingItems(ctx, pendingFeature, clusterSummary, featureSummary, currentReferences, logger) + return pendingFeature +} + +// getPendingReason returns why a feature has changes not deployed yet. Returns an empty reason if it has none. +func getPendingReason(configured bool, featureSummary *configv1beta1.FeatureSummary, + currentHash []byte) configv1beta1.PendingFeatureReason { + + // Feature never successfully deployed (no hash is stored for a feature that failed before + // computing its hash) + if configured && (featureSummary == nil || len(featureSummary.Hash) == 0) { + return configv1beta1.PendingReasonNotDeployed + } + + if reflect.DeepEqual(featureSummary.Hash, currentHash) { + return "" + } + + if !configured { + return configv1beta1.PendingReasonPendingRemoval + } + + return configv1beta1.PendingReasonConfigurationChanged +} + +// isFeatureConfigured returns true if ClusterSummary Spec has any configuration for the feature. +// Same check done before deploying a feature. +func isFeatureConfigured(clusterSummary *configv1beta1.ClusterSummary, featureID libsveltosv1beta1.FeatureID) bool { + switch featureID { + case libsveltosv1beta1.FeatureResources: + return clusterSummary.Spec.ClusterProfileSpec.PolicyRefs != nil + case libsveltosv1beta1.FeatureHelm: + return clusterSummary.Spec.ClusterProfileSpec.HelmCharts != nil + case libsveltosv1beta1.FeatureKustomize: + return clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs != nil + } + + return false +} diff --git a/controllers/clustersummary_pending_items.go b/controllers/clustersummary_pending_items.go new file mode 100644 index 00000000..1d25a131 --- /dev/null +++ b/controllers/clustersummary_pending_items.go @@ -0,0 +1,314 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers + +import ( + "bytes" + "context" + "fmt" + "sort" + "strings" + + "github.com/Masterminds/semver/v3" + "github.com/go-logr/logr" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" +) + +const ( + helmChartItemKind = "HelmChart" + + messageItemsUnknown = "what changed is not known: the feature was deployed by a version that did not record " + + "the resources it depends on. It will be known after the feature is deployed again" + + messageNoItems = "the change is not in a referenced resource: it is in the profile settings (for instance " + + "syncMode, tier, patches, drift exclusions), in content fetched from a remote URL, or in other " + + "settings of the feature" +) + +// referenceKey identifies a referenced resource. Flat and comparable, so it can be used as a map key. +type referenceKey struct { + source configv1beta1.ReferenceSource + kind string + namespace string + name string +} + +func getReferenceKey(reference *configv1beta1.ReferenceHash) referenceKey { + return referenceKey{ + source: reference.Source, kind: reference.Kind, namespace: reference.Namespace, name: reference.Name, + } +} + +// setPendingItems sets Items (and Message, when Items cannot tell the whole story) of pendingFeature: +// what exactly changed in the feature configuration since it was last deployed. +// featureSummary is what was recorded when the feature was last deployed (nil if it never was). +// currentReferences are the resources the current feature configuration depends on. +func setPendingItems(ctx context.Context, pendingFeature *configv1beta1.PendingFeature, + clusterSummary *configv1beta1.ClusterSummary, featureSummary *configv1beta1.FeatureSummary, + currentReferences []configv1beta1.ReferenceHash, logger logr.Logger) { + + var items []configv1beta1.PendingItem + message := "" + if pendingFeature.FeatureID == libsveltosv1beta1.FeatureHelm { + items, message = getHelmPendingItems(ctx, clusterSummary, logger) + } else { + items, message = getReferencePendingItems(featureSummary, currentReferences) + } + + sortPendingItems(items) + if len(items) > configv1beta1.MaxPendingItems { + items = items[:configv1beta1.MaxPendingItems] + pendingFeature.ItemsTruncated = true + } + + pendingFeature.Items = items + if message != "" { + pendingFeature.Message = &message + } +} + +// getReferencePendingItems returns what changed comparing the resources the feature depended on when it +// was last deployed (recorded in featureSummary) with the ones it depends on now. +// Returns a message when the items do not explain the change. +func getReferencePendingItems(featureSummary *configv1beta1.FeatureSummary, + currentReferences []configv1beta1.ReferenceHash) (items []configv1beta1.PendingItem, message string) { + + // A feature never successfully deployed has no recorded hash and depended on nothing + var deployedReferences []configv1beta1.ReferenceHash + if featureSummary != nil && len(featureSummary.Hash) != 0 { + if !featureSummary.ReferencesRecorded { + return nil, messageItemsUnknown + } + deployedReferences = featureSummary.ReferenceHashes + } + + items = diffReferences(deployedReferences, currentReferences) + if len(items) == 0 { + return nil, messageNoItems + } + + return items, "" +} + +// diffReferences returns the resources that were added, removed or changed. +func diffReferences(deployed, current []configv1beta1.ReferenceHash) []configv1beta1.PendingItem { + deployedHashes := make(map[referenceKey]string, len(deployed)) + for i := range deployed { + deployedHashes[getReferenceKey(&deployed[i])] = deployed[i].Hash + } + + var items []configv1beta1.PendingItem + currentKeys := make(map[referenceKey]bool, len(current)) + for i := range current { + key := getReferenceKey(¤t[i]) + currentKeys[key] = true + + deployedHash, wasDeployed := deployedHashes[key] + switch { + case !wasDeployed: + items = append(items, newReferencePendingItem(¤t[i], configv1beta1.PendingChangeAdded)) + case deployedHash != current[i].Hash: + items = append(items, newReferencePendingItem(¤t[i], configv1beta1.PendingChangeChanged)) + } + } + + for i := range deployed { + if !currentKeys[getReferenceKey(&deployed[i])] { + items = append(items, newReferencePendingItem(&deployed[i], configv1beta1.PendingChangeRemoved)) + } + } + + return items +} + +func newReferencePendingItem(reference *configv1beta1.ReferenceHash, + change configv1beta1.PendingChange) configv1beta1.PendingItem { + + item := configv1beta1.PendingItem{ + Kind: reference.Kind, + Namespace: reference.Namespace, + Name: reference.Name, + Change: change, + } + if reference.Source == configv1beta1.ReferenceSourceTemplateResourceRef { + item.Detail = "referenced in templateResourceRefs" + } + + return item +} + +// getHelmPendingItems returns what changed comparing each helm chart in the ClusterSummary spec with +// what is recorded in Status.HelmReleaseSummaries when the chart was last deployed. +// Returns a message when the items do not explain the change. +func getHelmPendingItems(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary, + logger logr.Logger) (items []configv1beta1.PendingItem, message string) { + + clusterObjects, err := fetchClusterObjects(ctx, getManagementClusterConfig(), getManagementClusterClient(), + clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType, logger) + if err != nil { + return nil, fmt.Sprintf("failed to evaluate what changed: %v", err) + } + mgmtResources, err := collectTemplateResourceRefs(ctx, clusterSummary) + if err != nil { + return nil, fmt.Sprintf("failed to evaluate what changed: %v", err) + } + dCtx := &deploymentContext{clusterSummary: clusterSummary, clusterObjects: clusterObjects, mgmtResources: mgmtResources} + + requestedReleases := make(map[string]bool) + for i := range clusterSummary.Spec.ClusterProfileSpec.HelmCharts { + chart, err := getInstantiatedChartIdentity(ctx, dCtx, &clusterSummary.Spec.ClusterProfileSpec.HelmCharts[i], logger) + if err != nil { + return nil, fmt.Sprintf("failed to evaluate what changed: %v", err) + } + requestedReleases[getReleaseKey(chart.ReleaseNamespace, chart.ReleaseName)] = true + + item, err := getHelmChartPendingItem(ctx, dCtx, chart, logger) + if err != nil { + return nil, fmt.Sprintf("failed to evaluate what changed: %v", err) + } + if item != nil { + items = append(items, *item) + } + } + + // A release the ClusterSummary manages but does not request anymore is removed on next deployment + for i := range clusterSummary.Status.HelmReleaseSummaries { + summary := &clusterSummary.Status.HelmReleaseSummaries[i] + if summary.Status == configv1beta1.HelmChartStatusManaging && + !requestedReleases[getReleaseKey(summary.ReleaseNamespace, summary.ReleaseName)] { + + items = append(items, configv1beta1.PendingItem{ + Kind: helmChartItemKind, Namespace: summary.ReleaseNamespace, Name: summary.ReleaseName, + Change: configv1beta1.PendingChangeRemoved, + }) + } + } + + if len(items) == 0 { + return nil, messageNoItems + } + + return items, "" +} + +func getReleaseKey(releaseNamespace, releaseName string) string { + return fmt.Sprintf("%s/%s", releaseNamespace, releaseName) +} + +// getHelmChartPendingItem returns what changed for chart (whose identity is already instantiated). +// Returns nil if nothing that can be attributed to the chart changed. +func getHelmChartPendingItem(ctx context.Context, dCtx *deploymentContext, chart *configv1beta1.HelmChart, + logger logr.Logger) (*configv1beta1.PendingItem, error) { + + item := &configv1beta1.PendingItem{ + Kind: helmChartItemKind, Namespace: chart.ReleaseNamespace, Name: chart.ReleaseName, + } + + // An entry is created before the chart is deployed. Hashes and version are only recorded once it is. + summary := getHelmChartSummary(chart, dCtx.clusterSummary) + if summary == nil || (len(summary.ValuesHash) == 0 && summary.ChartVersion == "") { + item.Change = configv1beta1.PendingChangeAdded + if summary != nil && summary.Status == configv1beta1.HelmChartStatusConflict { + item.Detail = summary.ConflictMessage + } + return item, nil + } + + details, err := getHelmChartChanges(ctx, dCtx, chart, summary, logger) + if err != nil { + return nil, err + } + if len(details) == 0 { + return nil, nil + } + + item.Change = configv1beta1.PendingChangeChanged + item.Detail = strings.Join(details, "; ") + return item, nil +} + +// getHelmChartChanges compares chart with what was recorded in summary when it was last deployed. +func getHelmChartChanges(ctx context.Context, dCtx *deploymentContext, chart *configv1beta1.HelmChart, + summary *configv1beta1.HelmChartSummary, logger logr.Logger) ([]string, error) { + + var changes []string + + // Chart identity is not recorded for charts coming from a Flux source + if !isReferencingFluxSource(chart) { + if summary.ChartName != "" && summary.ChartName != chart.ChartName { + changes = append(changes, fmt.Sprintf("chart: %s -> %s", summary.ChartName, chart.ChartName)) + } + if isChartVersionDifferent(summary.ChartVersion, chart.ChartVersion) { + changes = append(changes, fmt.Sprintf("version: %s -> %s", summary.ChartVersion, chart.ChartVersion)) + } + if summary.RepoURL != "" && summary.RepoURL != chart.RepositoryURL { + changes = append(changes, "repository changed") + } + } + + valuesHash, err := getHelmChartValuesHash(ctx, getManagementClusterClient(), chart, dCtx.clusterSummary, + dCtx.mgmtResources, logger) + if err != nil { + return nil, err + } + if len(summary.ValuesHash) != 0 && !bytes.Equal(summary.ValuesHash, valuesHash) { + changes = append(changes, "values changed") + } + + patchesHash, err := getHelmChartPatchesHash(ctx, dCtx.clusterSummary, logger) + if err != nil { + return nil, err + } + if !bytes.Equal(summary.PatchesHash, patchesHash) { + changes = append(changes, "patches changed") + } + + return changes, nil +} + +// isChartVersionDifferent returns true if the version requested is known to differ from the one deployed. +// The version requested can be a constraint (for instance ">=1.2.0") or empty (latest): in such case the +// versions cannot be compared and this returns false. +func isChartVersionDifferent(deployedVersion, requestedVersion string) bool { + deployed, err := semver.NewVersion(deployedVersion) + if err != nil { + return false + } + requested, err := semver.NewVersion(requestedVersion) + if err != nil { + return false + } + + return !deployed.Equal(requested) +} + +// sortPendingItems sorts items so the result does not depend on the order resources were collected in. +// This keeps the status stable when nothing changed. +func sortPendingItems(items []configv1beta1.PendingItem) { + sort.Slice(items, func(i, j int) bool { + a, b := &items[i], &items[j] + if a.Kind != b.Kind { + return a.Kind < b.Kind + } + if a.Namespace != b.Namespace { + return a.Namespace < b.Namespace + } + return a.Name < b.Name + }) +} diff --git a/controllers/clustersummary_pending_test.go b/controllers/clustersummary_pending_test.go new file mode 100644 index 00000000..a050b03f --- /dev/null +++ b/controllers/clustersummary_pending_test.go @@ -0,0 +1,598 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers_test + +import ( + "context" + "errors" + + "github.com/go-logr/logr" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/klog/v2/textlogger" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + "github.com/projectsveltos/addon-controller/controllers" + "github.com/projectsveltos/addon-controller/lib/clusterops" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" +) + +var _ = Describe("ClusterSummary pending features", func() { + var logger logr.Logger + var clusterProfile *configv1beta1.ClusterProfile + var clusterSummary *configv1beta1.ClusterSummary + var configMap *corev1.ConfigMap + var cluster *clusterv1.Cluster + + BeforeEach(func() { + logger = textlogger.NewLogger(textlogger.NewConfig()) + + clusterProfile = &configv1beta1.ClusterProfile{ + ObjectMeta: metav1.ObjectMeta{ + Name: clusterProfileNamePrefix + randomString(), + }, + } + + clusterName := randomString() + clusterSummary = &configv1beta1.ClusterSummary{ + ObjectMeta: metav1.ObjectMeta{ + Name: clusterops.GetClusterSummaryName(configv1beta1.ClusterProfileKind, + clusterProfile.Name, clusterName, false), + Namespace: randomString(), + }, + Spec: configv1beta1.ClusterSummarySpec{ + ClusterNamespace: randomString(), + ClusterName: clusterName, + ClusterType: libsveltosv1beta1.ClusterTypeCapi, + }, + } + + // The Cluster must exist: referenced resources are only part of the hash once their namespace + // can be instantiated for the Cluster + cluster = &clusterv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: clusterSummary.Spec.ClusterName, + Namespace: clusterSummary.Spec.ClusterNamespace, + }, + } + + configMap = createConfigMapWithPolicy(randomString(), randomString(), randomString()) + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{ + { + Namespace: configMap.Namespace, + Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + }, + } + }) + + // deployedResourcesFeatureSummary returns the FeatureSummary left by a successful deployment + // of the Resources feature with the configuration currently in the fake client. + deployedResourcesFeatureSummary := func(c client.Client) configv1beta1.FeatureSummary { + hash, references, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + + return configv1beta1.FeatureSummary{ + FeatureID: libsveltosv1beta1.FeatureResources, + Hash: hash, + ReferenceHashes: references, + ReferencesRecorded: true, + Status: libsveltosv1beta1.FeatureStatusProvisioned, + } + } + + // addConfigMapReference creates a ConfigMap in c and makes the ClusterSummary reference it + addConfigMapReference := func(c client.Client) *corev1.ConfigMap { + newConfigMap := createConfigMapWithPolicy(randomString(), randomString(), randomString()) + Expect(c.Create(context.TODO(), newConfigMap)).To(Succeed()) + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = append(clusterSummary.Spec.ClusterProfileSpec.PolicyRefs, + configv1beta1.PolicyRef{ + Namespace: newConfigMap.Namespace, + Name: newConfigMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + }) + return newConfigMap + } + + configMapItem := func(cm *corev1.ConfigMap, change configv1beta1.PendingChange) configv1beta1.PendingItem { + return configv1beta1.PendingItem{ + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), Namespace: cm.Namespace, Name: cm.Name, + Change: change, + } + } + + runUpdatePendingFeatures := func(c client.Client) { + reconciler := getClusterSummaryReconciler(c, nil) + clusterSummaryScope := getClusterSummaryScope(c, logger, clusterProfile, clusterSummary) + controllers.UpdatePendingFeatures(reconciler, context.TODO(), clusterSummaryScope, logger) + } + + It("reports nothing when no feature is configured or deployed", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = nil + + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + It("reports nothing when the deployed configuration is the desired one", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + It("reports ConfigurationChanged when a referenced ConfigMap changed after the deployment", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + currentConfigMap := &corev1.ConfigMap{} + Expect(c.Get(context.TODO(), client.ObjectKeyFromObject(configMap), currentConfigMap)).To(Succeed()) + currentConfigMap.Data["policy0.yaml"] = randomString() + Expect(c.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].FeatureID).To(Equal(libsveltosv1beta1.FeatureResources)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(clusterSummary.Status.PendingFeatures[0].Message).To(BeNil()) + }) + + It("reports ConfigurationChanged when the ClusterSummary spec changed after the deployment", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + clusterSummary.Spec.ClusterProfileSpec.Tier = 50 + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + }) + + It("reports only the features with changes", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = []configv1beta1.HelmChart{ + { + RepositoryURL: testHTTPRepoURL, + RepositoryName: randomString(), + ChartName: randomString(), + ChartVersion: outdatedCheckChartVersion, + ReleaseName: randomString(), + ReleaseNamespace: randomString(), + }, + } + + // helmHash resolves the Cluster through the management cluster client rather than the client + // passed in. So the Cluster has to exist there too, not only in the fake client. + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: clusterSummary.Spec.ClusterNamespace}} + Expect(testEnv.Create(context.TODO(), ns)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, ns)).To(Succeed()) + mgmtCluster := &clusterv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: clusterSummary.Spec.ClusterNamespace, + Name: clusterSummary.Spec.ClusterName, + }, + } + Expect(testEnv.Create(context.TODO(), mgmtCluster)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, mgmtCluster)).To(Succeed()) + + helmHash, err := controllers.HelmHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{ + deployedResourcesFeatureSummary(c), + {FeatureID: libsveltosv1beta1.FeatureHelm, Hash: helmHash, Status: libsveltosv1beta1.FeatureStatusProvisioned}, + } + + clusterSummary.Spec.ClusterProfileSpec.HelmCharts[0].ChartVersion = v2_0_0 + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].FeatureID).To(Equal(libsveltosv1beta1.FeatureHelm)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + }) + + It("reports NotDeployed when a configured feature was never deployed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].FeatureID).To(Equal(libsveltosv1beta1.FeatureResources)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonNotDeployed)) + }) + + It("reports NotDeployed when the feature failed before a hash was stored", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{ + {FeatureID: libsveltosv1beta1.FeatureResources, Status: libsveltosv1beta1.FeatureStatusFailed}, + } + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonNotDeployed)) + }) + + It("reports PendingRemoval when a deployed feature is not configured anymore", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = nil + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].FeatureID).To(Equal(libsveltosv1beta1.FeatureResources)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonPendingRemoval)) + }) + + It("does not report a feature already removed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = nil + + // Hash recorded when the feature was removed is the one of an empty configuration + hash, err := controllers.ResourcesHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{ + {FeatureID: libsveltosv1beta1.FeatureResources, Hash: hash, Status: libsveltosv1beta1.FeatureStatusRemoved}, + } + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + It("reports EvaluationFailed with the error when the desired configuration cannot be evaluated", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + failingClient := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster). + WithInterceptorFuncs(interceptor.Funcs{ + Get: func(ctx context.Context, c client.WithWatch, key client.ObjectKey, obj client.Object, + opts ...client.GetOption) error { + + if _, ok := obj.(*corev1.ConfigMap); ok { + return errors.New("injected failure") + } + return c.Get(ctx, key, obj, opts...) + }, + }).Build() + + runUpdatePendingFeatures(failingClient) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonEvaluationFailed)) + Expect(clusterSummary.Status.PendingFeatures[0].Message).ToNot(BeNil()) + Expect(*clusterSummary.Status.PendingFeatures[0].Message).To(ContainSubstring("injected failure")) + }) + + It("reports nothing in DryRun mode and drops what was reported before", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Spec.ClusterProfileSpec.SyncMode = configv1beta1.SyncModeDryRun + clusterSummary.Status.PendingFeatures = []configv1beta1.PendingFeature{ + {FeatureID: libsveltosv1beta1.FeatureResources, Reason: configv1beta1.PendingReasonNotDeployed}, + } + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + It("drops what was reported before when nothing is pending anymore", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + clusterSummary.Status.PendingFeatures = []configv1beta1.PendingFeature{ + {FeatureID: libsveltosv1beta1.FeatureResources, Reason: configv1beta1.PendingReasonConfigurationChanged}, + } + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + Context("items", func() { + It("lists the ConfigMap that changed, and not the ones that did not", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + unchangedConfigMap := addConfigMapReference(c) + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + currentConfigMap := &corev1.ConfigMap{} + Expect(c.Get(context.TODO(), client.ObjectKeyFromObject(configMap), currentConfigMap)).To(Succeed()) + currentConfigMap.Data["policy0.yaml"] = randomString() + Expect(c.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(Equal([]configv1beta1.PendingItem{ + configMapItem(configMap, configv1beta1.PendingChangeChanged)})) + Expect(pending.Items).ToNot(ContainElement(configMapItem(unchangedConfigMap, configv1beta1.PendingChangeChanged))) + Expect(pending.ItemsTruncated).To(BeFalse()) + Expect(pending.Message).To(BeNil()) + }) + + It("lists a ConfigMap that was added to the references", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + addedConfigMap := addConfigMapReference(c) + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Items).To(Equal([]configv1beta1.PendingItem{ + configMapItem(addedConfigMap, configv1beta1.PendingChangeAdded)})) + }) + + It("lists a ConfigMap that was removed from the references", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + removedConfigMap := addConfigMapReference(c) + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = clusterSummary.Spec.ClusterProfileSpec.PolicyRefs[:1] + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Items).To(Equal([]configv1beta1.PendingItem{ + configMapItem(removedConfigMap, configv1beta1.PendingChangeRemoved)})) + }) + + It("lists every referenced ConfigMap as added when the feature was never deployed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonNotDeployed)) + Expect(clusterSummary.Status.PendingFeatures[0].Items).To(Equal([]configv1beta1.PendingItem{ + configMapItem(configMap, configv1beta1.PendingChangeAdded)})) + }) + + It("lists every ConfigMap as removed when the feature is not configured anymore", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = nil + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Reason).To(Equal(configv1beta1.PendingReasonPendingRemoval)) + Expect(clusterSummary.Status.PendingFeatures[0].Items).To(Equal([]configv1beta1.PendingItem{ + configMapItem(configMap, configv1beta1.PendingChangeRemoved)})) + }) + + It("says the change is not in a referenced resource when only the profile settings changed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + clusterSummary.Spec.ClusterProfileSpec.Tier = 50 + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(BeEmpty()) + Expect(pending.Message).ToNot(BeNil()) + Expect(*pending.Message).To(ContainSubstring("not in a referenced resource")) + }) + + It("says what changed is not known for a feature deployed before references were recorded", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + deployed := deployedResourcesFeatureSummary(c) + deployed.ReferenceHashes = nil + deployed.ReferencesRecorded = false + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployed} + + currentConfigMap := &corev1.ConfigMap{} + Expect(c.Get(context.TODO(), client.ObjectKeyFromObject(configMap), currentConfigMap)).To(Succeed()) + currentConfigMap.Data["policy0.yaml"] = randomString() + Expect(c.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(BeEmpty()) + Expect(pending.Message).ToNot(BeNil()) + Expect(*pending.Message).To(ContainSubstring("not known")) + }) + + It("lists at most MaxPendingItems items and says the list is truncated", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + + for i := 0; i < configv1beta1.MaxPendingItems+10; i++ { + addConfigMapReference(c) + } + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(HaveLen(configv1beta1.MaxPendingItems)) + Expect(pending.ItemsTruncated).To(BeTrue()) + }) + + It("reports the same items every time nothing changed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{deployedResourcesFeatureSummary(c)} + for i := 0; i < 5; i++ { + addConfigMapReference(c) + } + + runUpdatePendingFeatures(c) + first := clusterSummary.Status.PendingFeatures + runUpdatePendingFeatures(c) + + Expect(first).ToNot(BeEmpty()) + Expect(clusterSummary.Status.PendingFeatures).To(Equal(first)) + }) + }) + + Context("helm items", func() { + var chart configv1beta1.HelmChart + + BeforeEach(func() { + chart = configv1beta1.HelmChart{ + RepositoryURL: testHTTPRepoURL, + RepositoryName: randomString(), + ChartName: randomString(), + ChartVersion: outdatedCheckChartVersion, + ReleaseName: randomString(), + ReleaseNamespace: randomString(), + } + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = nil + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = []configv1beta1.HelmChart{chart} + + // Chart identity and values are instantiated using the Cluster in the management cluster + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: clusterSummary.Spec.ClusterNamespace}} + Expect(testEnv.Create(context.TODO(), ns)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, ns)).To(Succeed()) + mgmtCluster := &clusterv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: clusterSummary.Spec.ClusterNamespace, + Name: clusterSummary.Spec.ClusterName, + }, + } + Expect(testEnv.Create(context.TODO(), mgmtCluster)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, mgmtCluster)).To(Succeed()) + }) + + // deployHelm records, as a successful deployment does, the hash of the Helm feature and the + // release summary of the chart + deployHelm := func(c client.Client) { + hash, err := controllers.HelmHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + deployedValuesHash, err := controllers.GetHelmChartValuesHash(context.TODO(), c, &chart, clusterSummary, + nil, logger) + Expect(err).To(BeNil()) + clusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{ + {FeatureID: libsveltosv1beta1.FeatureHelm, Hash: hash, Status: libsveltosv1beta1.FeatureStatusProvisioned}, + } + clusterSummary.Status.HelmReleaseSummaries = []configv1beta1.HelmChartSummary{ + { + ReleaseName: chart.ReleaseName, ReleaseNamespace: chart.ReleaseNamespace, + Status: configv1beta1.HelmChartStatusManaging, ChartName: chart.ChartName, + RepoURL: chart.RepositoryURL, ChartVersion: chart.ChartVersion, + ValuesHash: deployedValuesHash, + }, + } + } + + helmItem := func(change configv1beta1.PendingChange, detail string) configv1beta1.PendingItem { + return configv1beta1.PendingItem{ + Kind: "HelmChart", Namespace: chart.ReleaseNamespace, Name: chart.ReleaseName, + Change: change, Detail: detail, + } + } + + It("lists the chart as added when it was never deployed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonNotDeployed)) + Expect(pending.Items).To(Equal([]configv1beta1.PendingItem{helmItem(configv1beta1.PendingChangeAdded, "")})) + }) + + It("reports nothing when the deployed chart is the requested one", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + deployHelm(c) + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(BeEmpty()) + }) + + It("lists the version change of a chart", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + deployHelm(c) + + clusterSummary.Spec.ClusterProfileSpec.HelmCharts[0].ChartVersion = v2_0_0 + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(Equal([]configv1beta1.PendingItem{ + helmItem(configv1beta1.PendingChangeChanged, "version: "+outdatedCheckChartVersion+" -> "+v2_0_0)})) + }) + + It("lists a values change of a chart", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + deployHelm(c) + + clusterSummary.Spec.ClusterProfileSpec.HelmCharts[0].Values = "replicas: 3" + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + Expect(clusterSummary.Status.PendingFeatures[0].Items).To(Equal([]configv1beta1.PendingItem{ + helmItem(configv1beta1.PendingChangeChanged, "values changed")})) + }) + + It("does not compare the version when a constraint is requested", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + deployHelm(c) + + clusterSummary.Spec.ClusterProfileSpec.HelmCharts[0].ChartVersion = ">=1.0.0" + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Items).To(BeEmpty()) + Expect(pending.Message).ToNot(BeNil()) + }) + + It("lists a chart that is not requested anymore as removed", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + deployHelm(c) + + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = []configv1beta1.HelmChart{} + + runUpdatePendingFeatures(c) + + Expect(clusterSummary.Status.PendingFeatures).To(HaveLen(1)) + pending := clusterSummary.Status.PendingFeatures[0] + Expect(pending.Reason).To(Equal(configv1beta1.PendingReasonConfigurationChanged)) + Expect(pending.Items).To(Equal([]configv1beta1.PendingItem{helmItem(configv1beta1.PendingChangeRemoved, "")})) + }) + }) +}) diff --git a/controllers/export_test.go b/controllers/export_test.go index f178bcf1..5b5a2361 100644 --- a/controllers/export_test.go +++ b/controllers/export_test.go @@ -93,6 +93,7 @@ var ( UndeployFeature = (*ClusterSummaryReconciler).undeployFeature GetCurrentReferences = (*ClusterSummaryReconciler).getCurrentReferences IsPaused = (*ClusterSummaryReconciler).isPaused + UpdatePendingFeatures = (*ClusterSummaryReconciler).updatePendingFeatures IsReady = (*ClusterSummaryReconciler).isReady ShouldReconcile = (*ClusterSummaryReconciler).shouldReconcile UpdateChartMap = (*ClusterSummaryReconciler).updateChartMap @@ -174,11 +175,13 @@ var ( AdjustNamespace = adjustNamespace ResourcesHash = resourcesHash + ResourcesConfiguration = resourcesConfiguration GetResourceRefs = getResourceRefs PersistResourceReportsOnError = persistResourceReportsOnError UndeployKustomizeRefs = undeployKustomizeRefs KustomizationHash = kustomizationHash + KustomizationConfiguration = kustomizationConfiguration GetKustomizeReferenceResourceHash = getKustomizeReferenceResourceHash GetHashFromRemoteKustomizeURL = getHashFromRemoteKustomizeURL PrepareFileSystemWithRemoteURL = prepareFileSystemWithRemoteURL diff --git a/controllers/handlers_helm.go b/controllers/handlers_helm.go index bac99313..cc25699a 100644 --- a/controllers/handlers_helm.go +++ b/controllers/handlers_helm.go @@ -1055,6 +1055,15 @@ func uninstallHelmCharts(ctx context.Context, c client.Client, clusterSummary *c return releaseReports, nil } +// helmConfiguration returns the hash of the ClusterSummary HelmCharts. No ReferenceHash is returned: for +// the Helm feature what changed is established comparing with ClusterSummary Status.HelmReleaseSummaries. +func helmConfiguration(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, + logger logr.Logger) ([]byte, []configv1beta1.ReferenceHash, error) { + + hash, err := helmHash(ctx, c, clusterSummary, logger) + return hash, nil, err +} + func helmHash(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, logger logr.Logger) ([]byte, error) { diff --git a/controllers/handlers_kustomize.go b/controllers/handlers_kustomize.go index eb08d17b..a8068fb2 100644 --- a/controllers/handlers_kustomize.go +++ b/controllers/handlers_kustomize.go @@ -367,9 +367,24 @@ func undeployKustomizeRefs(ctx context.Context, c client.Client, func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, logger logr.Logger) ([]byte, error) { + hash, _, err := kustomizationConfiguration(ctx, c, clusterSummary, logger) + return hash, err +} + +// kustomizationConfiguration returns the hash of the ClusterSummary KustomizationRefs, and the hash of +// each one of the resources it was computed from. The latter is what tells, when the former changes, +// which resource changed. +func kustomizationConfiguration(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, + logger logr.Logger) ([]byte, []configv1beta1.ReferenceHash, error) { + config, err := getClusterProfileSpecHash(ctx, clusterSummary, logger) if err != nil { - return nil, err + return nil, nil, err + } + + references, err := getTemplateResourceReferenceHashes(ctx, clusterSummary) + if err != nil { + return nil, nil, err } h := sha256.New() @@ -377,7 +392,7 @@ func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *con sortedKustomizationRefs := getSortedKustomizationRefs(clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs) raw, err := json.Marshal(sortedKustomizationRefs) if err != nil { - return nil, err + return nil, nil, err } hash := sha256.Sum256(raw) config += hex.EncodeToString((hash[:])) @@ -385,16 +400,16 @@ func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *con clusterObjects, err := fetchClusterObjects(ctx, getManagementClusterConfig(), getManagementClusterClient(), clusterSummary.Spec.ClusterNamespace, clusterSummary.Spec.ClusterName, clusterSummary.Spec.ClusterType, logger) if err != nil { - return nil, err + return nil, nil, err } for i := range sortedKustomizationRefs { kustomizationRef := &sortedKustomizationRefs[i] - result, err := getHashFromKustomizationRef(ctx, c, clusterSummary, + result, referencedObject, err := getHashFromKustomizationRef(ctx, c, clusterSummary, kustomizationRef, logger) if err != nil { - return nil, err + return nil, nil, err } if result == nil { continue @@ -407,10 +422,17 @@ func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *con if err != nil { logger.V(logs.LogInfo).Info( fmt.Sprintf("failed to get hash from referenced ConfigMap/Secret in ValuesFrom %v", err)) - return nil, err + return nil, nil, err } config += valueFromHash + + // Content fetched from a remote URL is part of the hash but is not itemized: the URL + // might carry credentials and must not end up in the status. + if referencedObject != nil { + references = append(references, newReferenceHash(configv1beta1.ReferenceSourceKustomizationRef, + referencedObject, string(result)+valueFromHash)) + } } for i := range clusterSummary.Spec.ClusterProfileSpec.ValidateHealths { @@ -418,7 +440,7 @@ func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *con if h.FeatureID == libsveltosv1beta1.FeatureKustomize { raw, err := json.Marshal(h) if err != nil { - return nil, err + return nil, nil, err } hash := sha256.Sum256(raw) config += hex.EncodeToString((hash[:])) @@ -426,19 +448,20 @@ func kustomizationHash(ctx context.Context, c client.Client, clusterSummary *con } h.Write([]byte(config)) - return h.Sum(nil), nil + return h.Sum(nil), references, nil } func getHashFromKustomizationRef(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, - kustomizationRef *configv1beta1.KustomizationRef, logger logr.Logger) ([]byte, error) { + kustomizationRef *configv1beta1.KustomizationRef, logger logr.Logger) ([]byte, *corev1.ObjectReference, error) { if kustomizationRef.RemoteURL != nil { - return getHashFromRemoteKustomizeURL(ctx, kustomizationRef.RemoteURL, clusterSummary, logger) + hash, err := getHashFromRemoteKustomizeURL(ctx, kustomizationRef.RemoteURL, clusterSummary, logger) + return hash, nil, err } c, err := getReferenceClient(c, clusterSummary) if err != nil { - return nil, err + return nil, nil, err } var result string @@ -448,7 +471,7 @@ func getHashFromKustomizationRef(ctx context.Context, c client.Client, clusterSu logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to instantiate namespace for %s: %v", kustomizationRef.Namespace, err)) // Ignore template instantiation error - return nil, nil + return nil, nil, nil } name, err := libsveltostemplate.GetReferenceResourceName(ctx, c, clusterSummary.Spec.ClusterNamespace, @@ -457,37 +480,37 @@ func getHashFromKustomizationRef(ctx context.Context, c client.Client, clusterSu logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to instantiate name for %s: %v", kustomizationRef.Name, err)) // Ignore template instantiation error - return nil, nil + return nil, nil, nil } if kustomizationRef.Kind == string(libsveltosv1beta1.ConfigMapReferencedResourceKind) { configMap, err := getConfigMap(ctx, c, types.NamespacedName{Namespace: namespace, Name: name}) if err != nil { logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get ConfigMap %v", err)) - return nil, err + return nil, nil, err } if configMap == nil { - return nil, nil + return nil, nil, nil } result += getConfigMapHash(configMap) } else if kustomizationRef.Kind == string(libsveltosv1beta1.SecretReferencedResourceKind) { secret, err := getSecret(ctx, c, types.NamespacedName{Namespace: namespace, Name: name}) if err != nil { logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get Secret %v", err)) - return nil, err + return nil, nil, err } if secret == nil { - return nil, nil + return nil, nil, nil } result += getSecretHash(secret) } else { source, err := getSource(ctx, c, namespace, name, kustomizationRef.Kind) if err != nil { logger.V(logs.LogInfo).Info(fmt.Sprintf("failed to get source %v", err)) - return nil, err + return nil, nil, err } if source == nil { - return nil, nil + return nil, nil, nil } s := source.(sourcev1.Source) if s.GetArtifact() != nil { @@ -498,7 +521,8 @@ func getHashFromKustomizationRef(ctx context.Context, c client.Client, clusterSu } } - return []byte(result), nil + referencedObject := &corev1.ObjectReference{Kind: kustomizationRef.Kind, Namespace: namespace, Name: name} + return []byte(result), referencedObject, nil } // getHashFromRemoteKustomizeURL fetches the content referenced by a KustomizationRef's diff --git a/controllers/handlers_resources.go b/controllers/handlers_resources.go index 8476337a..5a142762 100644 --- a/controllers/handlers_resources.go +++ b/controllers/handlers_resources.go @@ -564,20 +564,36 @@ func pullModeUndeployResources(ctx context.Context, c client.Client, clusterSumm func resourcesHash(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, logger logr.Logger) ([]byte, error) { + hash, _, err := resourcesConfiguration(ctx, c, clusterSummary, logger) + return hash, err +} + +// resourcesConfiguration returns the hash of all the ClusterSummary referenced ResourceRefs, and the +// hash of each one of the resources it was computed from. The latter is what tells, when the former +// changes, which resource changed. +func resourcesConfiguration(ctx context.Context, c client.Client, clusterSummary *configv1beta1.ClusterSummary, + logger logr.Logger) ([]byte, []configv1beta1.ReferenceHash, error) { + config, err := getClusterProfileSpecHash(ctx, clusterSummary, logger) if err != nil { - return nil, err + return nil, nil, err } + templateReferences, err := getTemplateResourceReferenceHashes(ctx, clusterSummary) + if err != nil { + return nil, nil, err + } + references := templateReferences + c, err = getReferenceClient(c, clusterSummary) if err != nil { - return nil, err + return nil, nil, err } sortedPolicyRefs := getSortedPolicyRefs(clusterSummary.Spec.ClusterProfileSpec.PolicyRefs) raw, err := json.Marshal(sortedPolicyRefs) if err != nil { - return nil, err + return nil, nil, err } hash := sha256.Sum256(raw) config += hex.EncodeToString((hash[:])) @@ -594,28 +610,35 @@ func resourcesHash(ctx context.Context, c client.Client, clusterSummary *configv configmap := &corev1.ConfigMap{} err = c.Get(ctx, types.NamespacedName{Namespace: reference.Namespace, Name: reference.Name}, configmap) if err == nil { - config += getConfigMapHash(configmap) + content := getConfigMapHash(configmap) + config += content config += fmt.Sprintf("%d", referencedObjectTiers[*reference]) + references = append(references, newReferenceHash(configv1beta1.ReferenceSourcePolicyRef, reference, content)) } } else if reference.Kind == string(libsveltosv1beta1.SecretReferencedResourceKind) { secret := &corev1.Secret{} err = c.Get(ctx, types.NamespacedName{Namespace: reference.Namespace, Name: reference.Name}, secret) if err == nil { - config += getSecretHash(secret) + content := getSecretHash(secret) + config += content config += fmt.Sprintf("%d", referencedObjectTiers[*reference]) + references = append(references, newReferenceHash(configv1beta1.ReferenceSourcePolicyRef, reference, content)) } } else { var source client.Object source, err = getSource(ctx, c, reference.Namespace, reference.Name, reference.Kind) if err == nil && source != nil { + content := "" s := source.(sourcev1.Source) if s.GetArtifact() != nil { - config += s.GetArtifact().Revision + content += s.GetArtifact().Revision } if source.GetAnnotations() != nil { - config += getDataSectionHash(source.GetAnnotations()) + content += getDataSectionHash(source.GetAnnotations()) } + config += content config += fmt.Sprintf("%d", referencedObjectTiers[*reference]) + references = append(references, newReferenceHash(configv1beta1.ReferenceSourcePolicyRef, reference, content)) } } if err != nil { @@ -626,32 +649,46 @@ func resourcesHash(ctx context.Context, c client.Client, clusterSummary *configv } logger.Error(err, fmt.Sprintf("failed to get %s %s/%s", reference.Kind, reference.Namespace, reference.Name)) - return nil, err + return nil, nil, err } } + validateHealthsHash, err := getResourcesValidateHealthsHash(clusterSummary) + if err != nil { + return nil, nil, err + } + config += validateHealthsHash + + // The content of resources fetched from a URL is part of the hash but is not itemized: the URL + // might carry credentials and must not end up in the status. + urlHash, err := urlPolicyRefsHash(ctx, clusterSummary, logger) + if err != nil { + return nil, nil, err + } + config += urlHash + + h := sha256.New() + h.Write([]byte(config)) + return h.Sum(nil), references, nil +} + +// getResourcesValidateHealthsHash returns the hash of the ValidateHealths applying to the Resources feature +func getResourcesValidateHealthsHash(clusterSummary *configv1beta1.ClusterSummary) (string, error) { + result := "" for i := range clusterSummary.Spec.ClusterProfileSpec.ValidateHealths { h := &clusterSummary.Spec.ClusterProfileSpec.ValidateHealths[i] if h.FeatureID == libsveltosv1beta1.FeatureResources { raw, err := json.Marshal(h) if err != nil { - return nil, err + return "", err } hash := sha256.Sum256(raw) - config += hex.EncodeToString((hash[:])) + result += hex.EncodeToString((hash[:])) } } - urlHash, err := urlPolicyRefsHash(ctx, clusterSummary, logger) - if err != nil { - return nil, err - } - config += urlHash - - h := sha256.New() - h.Write([]byte(config)) - return h.Sum(nil), nil + return result, nil } // urlPolicyRefsHash fetches each URL-based PolicyRef and returns a hash string diff --git a/controllers/profile_utils.go b/controllers/profile_utils.go index 94bd8b08..e7b07473 100644 --- a/controllers/profile_utils.go +++ b/controllers/profile_utils.go @@ -714,6 +714,10 @@ func createClusterSummary(ctx context.Context, c client.Client, profileScope *sc // updateClusterSummaries for each Sveltos/Cluster currently matching ClusterProfile/Profile: // - creates corresponding ClusterSummary if one does not exist already // - updates (eventually) corresponding ClusterSummary if one already exists +// When MaxUpdate is set, ClusterSummaries of paused clusters are updated last: only once all ClusterSummaries +// of clusters that are not paused have been updated and are provisioned. A paused cluster is never programmed, +// so it does not take one of the MaxUpdate slots. Updating its ClusterSummary only makes the new configuration +// visible (ClusterSummary.Status.PendingFeatures), it does not deploy anything. // Return an error if due to MaxUpdate not all ClusterSummaries are synced func updateClusterSummaries(ctx context.Context, c client.Client, profileScope *scope.ProfileScope) error { currentHash := getProfileSpecHash(profileScope) @@ -738,6 +742,7 @@ func updateClusterSummaries(ctx context.Context, c client.Client, profileScope * matchingClusterSummaryDeleted := false skippedUpdate := false + var pausedClusters []corev1.ObjectReference // Consider matchingCluster number and MaxUpdate, walk remaining matching clusters. If more clusters can be // updated, update ClusterSummary and add it to UpdatingClusters for i := range profileScope.GetStatus().MatchingClusterRefs { @@ -772,6 +777,12 @@ func updateClusterSummaries(ctx context.Context, c client.Client, profileScope * continue } + // Cluster is paused: its ClusterSummary is updated once all other clusters are done + if outcome == updateDeferred { + pausedClusters = append(pausedClusters, *cluster) + continue + } + if !updatingClusters.Has(cluster) { updatingClusters.Insert(cluster) profileScope.GetStatus().UpdatingClusters.Clusters = @@ -793,6 +804,11 @@ func updateClusterSummaries(ctx context.Context, c client.Client, profileScope * return fmt.Errorf("some clusterSummaries are being deleted. Must reconcile again") } + err := updateClusterSummariesOfPausedClusters(ctx, c, profileScope, pausedClusters, updatingClusters) + if err != nil { + return err + } + // If all ClusterSummaries have been updated, reset Updated and Updating profileScope.GetStatus().UpdatedClusters = configv1beta1.Clusters{} profileScope.GetStatus().UpdatingClusters = configv1beta1.Clusters{} @@ -810,10 +826,15 @@ const ( // updateThrottled: maxUpdate clusters are already being updated. The cluster must wait. updateThrottled - // updateIgnored: nothing was done for the cluster, for instance because it is paused or not ready. + // updateIgnored: nothing was done for the cluster because it is not ready. // The cluster is not counted as being updated. ClusterProfile/Profile reconciles again when the // cluster changes. updateIgnored + + // updateDeferred: nothing was done for the cluster yet because it is paused and maxUpdate is set. + // The cluster is not counted as being updated. Its ClusterSummary is updated once all the clusters + // that are not paused have been updated and are provisioned. + updateDeferred ) func updateClusterSummaryInstanceForCluster(ctx context.Context, c client.Client, cluster *corev1.ObjectReference, @@ -835,8 +856,8 @@ func updateClusterSummaryInstanceForCluster(ctx context.Context, c client.Client maxUpdate := getMaxUpdate(profileScope) if maxUpdate != 0 { - // maxUpdate is set. Skip paused clusters (which would not be updated anyhow as set to paused) - // and try to pcik any non paused cluster + // maxUpdate is set. A paused cluster is not programmed, so it must not take one of the maxUpdate slots. + // Defer it and try to pick any non paused cluster isClusterPaused, err := clusterproxy.IsClusterPaused(ctx, c, cluster.Namespace, cluster.Name, clusterproxy.GetClusterType(cluster)) if err != nil { @@ -845,8 +866,8 @@ func updateClusterSummaryInstanceForCluster(ctx context.Context, c client.Client } if isClusterPaused { // Profile will react to a cluster switching from paused to unpaused - logger.V(logs.LogDebug).Info("Cluster is paused and maxUpdate is set. Ignore this cluster.") - return updateIgnored, nil + logger.V(logs.LogDebug).Info("Cluster is paused and maxUpdate is set. Defer this cluster.") + return updateDeferred, nil } } @@ -856,17 +877,65 @@ func updateClusterSummaryInstanceForCluster(ctx context.Context, c client.Client return updateThrottled, nil } - // ClusterProfile does not look at whether Cluster is paused or not. + // ClusterProfile does not look at whether Cluster is paused or not (when maxUpdate is not set). // If a Cluster exists and it is a match, ClusterSummary is created (and ClusterSummary.Spec kept in sync if mode is // continuous). // ClusterSummary won't program cluster in paused state. - err = patchClusterSummary(ctx, c, profileScope, cluster, logger) + return updateDone, syncClusterSummary(ctx, c, profileScope, cluster, logger) +} + +// syncClusterSummary creates or updates the ClusterSummary for the cluster, and tracks whether it failed +func syncClusterSummary(ctx context.Context, c client.Client, profileScope *scope.ProfileScope, + cluster *corev1.ObjectReference, logger logr.Logger) error { + + err := patchClusterSummary(ctx, c, profileScope, cluster, logger) if err != nil { profileScope.SetFailedClusters(cluster, err) } else { profileScope.ClearFailedClusters(cluster) } - return updateDone, err + return err +} + +// updateClusterSummariesOfPausedClusters creates or updates the ClusterSummary of each paused cluster +// (only paused clusters deferred because maxUpdate is set are passed). This is done only once no other +// cluster is being updated, so the new configuration reaches clusters that are not paused first. +// The ClusterSummaries of paused clusters are not tracked in UpdatingClusters: nothing is deployed +// to them, so they would never be provisioned. +func updateClusterSummariesOfPausedClusters(ctx context.Context, c client.Client, profileScope *scope.ProfileScope, + pausedClusters []corev1.ObjectReference, updatingClusters *libsveltosset.Set) error { + + if len(pausedClusters) == 0 { + return nil + } + + if updatingClusters.Len() != 0 { + return fmt.Errorf("%d clusters still being updated. Paused clusters are updated afterwards", + updatingClusters.Len()) + } + + clusterSummaryDeleted := false + for i := range pausedClusters { + cluster := &pausedClusters[i] + logger := profileScope.WithValues("cluster", + fmt.Sprintf("%s:%s/%s", cluster.Kind, cluster.Namespace, cluster.Name)) + + err := syncClusterSummary(ctx, c, profileScope, cluster, logger) + if err != nil { + var clusterSummaryDeletedError *ClusterSummaryDeletedError + if errors.As(err, &clusterSummaryDeletedError) { + clusterSummaryDeleted = true + continue + } + return err + } + } + + if clusterSummaryDeleted { + return fmt.Errorf("some clusterSummaries are being deleted. Must reconcile again") + } + + return nil } func patchClusterSummary(ctx context.Context, c client.Client, profileScope *scope.ProfileScope, diff --git a/controllers/profile_utils_test.go b/controllers/profile_utils_test.go index 4635e61e..f5aa9350 100644 --- a/controllers/profile_utils_test.go +++ b/controllers/profile_utils_test.go @@ -1204,7 +1204,7 @@ var _ = Describe("Profile: Reconciler", func() { Expect(len(clusterSummaryList.Items)).To(Equal(0)) }) - It("updateClusterSummaries does not create ClusterSummary for matching Paused Cluster", func() { + It("updateClusterSummaries creates ClusterSummary for a matching paused Cluster when MaxUpdate is set and no other cluster is updating", func() { maxUpdate := int32(3) clusterProfile.Spec.MaxUpdate = &intstr.IntOrString{Type: intstr.Int, IntVal: maxUpdate} clusterProfile.Status.MatchingClusterRefs = []corev1.ObjectReference{ @@ -1240,9 +1240,15 @@ var _ = Describe("Profile: Reconciler", func() { err = controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope) Expect(err).To(BeNil()) + // ClusterSummary is created so what is pending is visible. Nothing is deployed as cluster is paused. clusterSummaryList := &configv1beta1.ClusterSummaryList{} Expect(c.List(context.TODO(), clusterSummaryList)).To(BeNil()) - Expect(len(clusterSummaryList.Items)).To(Equal(0)) + Expect(clusterSummaryList.Items).To(HaveLen(1)) + Expect(clusterSummaryList.Items[0].Spec.ClusterName).To(Equal(matchingCluster.Name)) + + // A paused cluster is never tracked as being updated + Expect(clusterProfile.Status.UpdatingClusters.Clusters).To(BeEmpty()) + Expect(clusterProfile.Status.UpdatedClusters.Clusters).To(BeEmpty()) }) It("updateClusterSummaries does not let a paused cluster hold the only maxUpdate slot", func() { @@ -1286,7 +1292,9 @@ var _ = Describe("Profile: Reconciler", func() { }) Expect(err).To(BeNil()) - Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).To(Succeed()) + // Cluster which is not paused takes the slot. Paused cluster has to wait for it: reports + // the paused cluster is not updated yet + Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).ToNot(Succeed()) // Only the cluster which is not paused gets a ClusterSummary clusterSummaryList := &configv1beta1.ClusterSummaryList{} @@ -1298,6 +1306,95 @@ var _ = Describe("Profile: Reconciler", func() { for _, cluster := range clusterProfile.Status.UpdatingClusters.Clusters { Expect(cluster.Name).ToNot(Equal(matchingCluster.Name)) } + + // ClusterSummary of the cluster not paused is provisioned (profile has nothing to deploy), so + // paused cluster gets updated too + Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).To(Succeed()) + + Expect(c.List(context.TODO(), clusterSummaryList)).To(Succeed()) + Expect(clusterSummaryList.Items).To(HaveLen(2)) + + // Nothing left to update: lists are reset. Paused cluster never took a slot + Expect(clusterProfile.Status.UpdatingClusters.Clusters).To(BeEmpty()) + Expect(clusterProfile.Status.UpdatedClusters.Clusters).To(BeEmpty()) + }) + + It("updateClusterSummaries updates paused clusters only once clusters not paused are provisioned", func() { + clusterProfile.Spec.MaxUpdate = &intstr.IntOrString{Type: intstr.Int, IntVal: 1} + clusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{ + {RepositoryURL: randomString(), ChartName: randomString(), ChartVersion: randomString(), + ReleaseName: randomString(), ReleaseNamespace: randomString()}, + } + pausedClusterRef := corev1.ObjectReference{ + Namespace: matchingCluster.Namespace, + Name: matchingCluster.Name, + Kind: clusterKind, + APIVersion: clusterv1.GroupVersion.String(), + } + activeClusterRef := corev1.ObjectReference{ + Namespace: nonMatchingCluster.Namespace, + Name: nonMatchingCluster.Name, + Kind: clusterKind, + APIVersion: clusterv1.GroupVersion.String(), + } + clusterProfile.Status.MatchingClusterRefs = []corev1.ObjectReference{pausedClusterRef, activeClusterRef} + + initialized := true + paused := true + matchingCluster.Status.Initialization.ControlPlaneInitialized = &initialized + matchingCluster.Spec.Paused = &paused + nonMatchingCluster.Status.Initialization.ControlPlaneInitialized = &initialized + nonMatchingCluster.Status.Conditions = matchingCluster.Status.Conditions + + initObjects := []client.Object{ + clusterProfile, + nonMatchingCluster, + matchingCluster, + } + + c := fake.NewClientBuilder().WithScheme(scheme). + WithStatusSubresource(append(initObjects, &configv1beta1.ClusterSummary{})...). + WithObjects(initObjects...).Build() + + clusterProfileScope, err := scope.NewProfileScope(scope.ProfileScopeParams{ + Client: c, + Logger: logger, + Profile: clusterProfile, + ControllerName: testControllerNameProfile, + }) + Expect(err).To(BeNil()) + + // Cluster not paused is updated. It cannot be provisioned yet: paused cluster must wait + Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).ToNot(Succeed()) + clusterSummaryList := &configv1beta1.ClusterSummaryList{} + Expect(c.List(context.TODO(), clusterSummaryList)).To(Succeed()) + Expect(clusterSummaryList.Items).To(HaveLen(1)) + Expect(clusterSummaryList.Items[0].Spec.ClusterName).To(Equal(activeClusterRef.Name)) + Expect(clusterProfile.Status.UpdatingClusters.Clusters).To(HaveLen(1)) + + // Still not provisioned: paused cluster keeps waiting + Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).ToNot(Succeed()) + Expect(c.List(context.TODO(), clusterSummaryList)).To(Succeed()) + Expect(clusterSummaryList.Items).To(HaveLen(1)) + + By("Marking the ClusterSummary of the cluster not paused as provisioned") + activeClusterSummary := &clusterSummaryList.Items[0] + activeClusterSummary.Status.FeatureSummaries = []configv1beta1.FeatureSummary{ + {FeatureID: libsveltosv1beta1.FeatureHelm, Status: libsveltosv1beta1.FeatureStatusProvisioned}, + } + Expect(c.Status().Update(context.TODO(), activeClusterSummary)).To(Succeed()) + + Expect(controllers.UpdateClusterSummaries(context.TODO(), c, clusterProfileScope)).To(Succeed()) + + By("Verifying ClusterSummary for the paused cluster is now created with the profile spec") + Expect(c.List(context.TODO(), clusterSummaryList)).To(Succeed()) + Expect(clusterSummaryList.Items).To(HaveLen(2)) + for i := range clusterSummaryList.Items { + Expect(clusterSummaryList.Items[i].Spec.ClusterProfileSpec.HelmCharts).To(HaveLen(1)) + } + + // Paused cluster never took a slot + Expect(clusterProfile.Status.UpdatingClusters.Clusters).To(BeEmpty()) }) It("updateClusterSummaries creates ClusterSummary for each matching CAPI Cluster", func() { diff --git a/controllers/reference_hashes.go b/controllers/reference_hashes.go new file mode 100644 index 00000000..bb3200af --- /dev/null +++ b/controllers/reference_hashes.go @@ -0,0 +1,102 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "sort" + + corev1 "k8s.io/api/core/v1" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" +) + +const ( + // shortHashLength is the number of hex characters kept of the hash of a referenced resource. + // A short hash is enough: it is used to tell which resource changed after the hash of the whole + // configuration already told that something changed. If the hashes of two different contents ever + // collided, the change would still be reported, just not attributed to the resource. + shortHashLength = 8 +) + +// getShortHash returns a short hash of content +func getShortHash(content string) string { + hash := sha256.Sum256([]byte(content)) + return hex.EncodeToString(hash[:])[:shortHashLength] +} + +// newReferenceHash returns the ReferenceHash of a referenced resource, given its content. +func newReferenceHash(source configv1beta1.ReferenceSource, reference *corev1.ObjectReference, + content string) configv1beta1.ReferenceHash { + + return configv1beta1.ReferenceHash{ + Source: source, + Kind: reference.Kind, + Namespace: reference.Namespace, + Name: reference.Name, + Hash: getShortHash(content), + } +} + +// getTemplateResourceReferenceHashes returns the ReferenceHash of each resource in the management cluster +// referenced in the TemplateResourceRefs section. Their content is part of the hash of every feature. +func getTemplateResourceReferenceHashes(ctx context.Context, clusterSummary *configv1beta1.ClusterSummary, +) ([]configv1beta1.ReferenceHash, error) { + + mgmtResources, err := collectTemplateResourceRefs(ctx, clusterSummary) + if err != nil { + return nil, err + } + + references := make([]configv1beta1.ReferenceHash, 0, len(mgmtResources)) + for _, resource := range mgmtResources { + content, err := getUnstructuredHash(resource) + if err != nil { + return nil, err + } + + reference := &corev1.ObjectReference{ + Kind: resource.GetKind(), Namespace: resource.GetNamespace(), Name: resource.GetName(), + } + references = append(references, + newReferenceHash(configv1beta1.ReferenceSourceTemplateResourceRef, reference, content)) + } + + sortReferenceHashes(references) + + return references, nil +} + +// sortReferenceHashes sorts references so the result does not depend on the order resources were +// collected in. This keeps the status stable when nothing changed. +func sortReferenceHashes(references []configv1beta1.ReferenceHash) { + sort.Slice(references, func(i, j int) bool { + a, b := &references[i], &references[j] + if a.Source != b.Source { + return a.Source < b.Source + } + if a.Kind != b.Kind { + return a.Kind < b.Kind + } + if a.Namespace != b.Namespace { + return a.Namespace < b.Namespace + } + return a.Name < b.Name + }) +} diff --git a/controllers/reference_hashes_test.go b/controllers/reference_hashes_test.go new file mode 100644 index 00000000..3390a396 --- /dev/null +++ b/controllers/reference_hashes_test.go @@ -0,0 +1,257 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers_test + +import ( + "context" + "encoding/hex" + + "github.com/go-logr/logr" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/klog/v2/textlogger" + clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + "github.com/projectsveltos/addon-controller/controllers" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" +) + +// The hash of the configuration of a feature is stored in the status of every ClusterSummary. +// If a new version computes a different hash for an unchanged configuration, every ClusterSummary is +// redeployed after an upgrade. Those specs pin the hash, so such a change cannot go unnoticed. +// If a spec fails because the hash was changed on purpose, accept that all ClusterSummaries will be +// redeployed on upgrade and update the expected value. +const kustomizePath = "./overlay" + +var _ = Describe("Hash of the configuration of a feature", func() { + const ( + pinnedResourcesHash = "ee94eff728853199d0b80e049a522e114c95e560b865ccb0d28812e0323efe08" + pinnedKustomizationHash = "b1cad9e6212912efd69fc9da4b16eadd7fbe77490b6d31f3fd0adf153d8467fd" + ) + + var logger logr.Logger + var clusterSummary *configv1beta1.ClusterSummary + var configMap *corev1.ConfigMap + var cluster *clusterv1.Cluster + + BeforeEach(func() { + logger = textlogger.NewLogger(textlogger.NewConfig()) + + clusterSummary = &configv1beta1.ClusterSummary{ + ObjectMeta: metav1.ObjectMeta{Name: "pinned-clustersummary", Namespace: randomString()}, + Spec: configv1beta1.ClusterSummarySpec{ + ClusterNamespace: randomString(), + ClusterName: randomString(), + ClusterType: libsveltosv1beta1.ClusterTypeCapi, + }, + } + cluster = &clusterv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: clusterSummary.Spec.ClusterName, + Namespace: clusterSummary.Spec.ClusterNamespace, + }, + } + configMap = &corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Name: "pinned-configmap", Namespace: "pinned-namespace"}, + Data: map[string]string{ + "policy0.yaml": "apiVersion: v1\nkind: Namespace\nmetadata:\n name: pinned\n", + }, + } + reference := configv1beta1.PolicyRef{ + Namespace: configMap.Namespace, + Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Tier: 7, + } + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{reference} + clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs = []configv1beta1.KustomizationRef{ + { + Namespace: reference.Namespace, + Name: reference.Name, + Kind: reference.Kind, + Tier: reference.Tier, + Path: kustomizePath, + }, + } + clusterSummary.Spec.ClusterProfileSpec.Tier = 3 + }) + + It("is the one computed by previous versions for Resources", func() { + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + hash, err := controllers.ResourcesHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(hex.EncodeToString(hash)).To(Equal(pinnedResourcesHash)) + }) + + It("is the one computed by previous versions for Kustomize", func() { + // kustomizationHash fetches the Cluster through the management cluster client + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: clusterSummary.Spec.ClusterNamespace}} + Expect(testEnv.Create(context.TODO(), ns)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, ns)).To(Succeed()) + mgmtCluster := cluster.DeepCopy() + Expect(testEnv.Create(context.TODO(), mgmtCluster)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, mgmtCluster)).To(Succeed()) + + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + hash, err := controllers.KustomizationHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(hex.EncodeToString(hash)).To(Equal(pinnedKustomizationHash)) + }) +}) + +var _ = Describe("References of the configuration of a feature", func() { + var logger logr.Logger + var clusterSummary *configv1beta1.ClusterSummary + var configMap *corev1.ConfigMap + var cluster *clusterv1.Cluster + + BeforeEach(func() { + logger = textlogger.NewLogger(textlogger.NewConfig()) + + clusterSummary = &configv1beta1.ClusterSummary{ + ObjectMeta: metav1.ObjectMeta{Name: randomString(), Namespace: randomString()}, + Spec: configv1beta1.ClusterSummarySpec{ + ClusterNamespace: randomString(), + ClusterName: randomString(), + ClusterType: libsveltosv1beta1.ClusterTypeCapi, + }, + } + cluster = &clusterv1.Cluster{ + ObjectMeta: metav1.ObjectMeta{ + Name: clusterSummary.Spec.ClusterName, + Namespace: clusterSummary.Spec.ClusterNamespace, + }, + } + configMap = createConfigMapWithPolicy(randomString(), randomString(), randomString()) + }) + + It("Resources: has the hash of each referenced ConfigMap, and changes when its content changes", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{ + { + Namespace: configMap.Namespace, Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + }, + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + hash, references, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(references).To(HaveLen(1)) + Expect(references[0].Source).To(Equal(configv1beta1.ReferenceSourcePolicyRef)) + Expect(references[0].Kind).To(Equal(string(libsveltosv1beta1.ConfigMapReferencedResourceKind))) + Expect(references[0].Namespace).To(Equal(configMap.Namespace)) + Expect(references[0].Name).To(Equal(configMap.Name)) + Expect(references[0].Hash).To(HaveLen(8)) + + // Same hash as the one computed without the references + onlyHash, err := controllers.ResourcesHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(onlyHash).To(Equal(hash)) + + currentConfigMap := &corev1.ConfigMap{} + Expect(c.Get(context.TODO(), client.ObjectKeyFromObject(configMap), currentConfigMap)).To(Succeed()) + currentConfigMap.Data["policy0.yaml"] = randomString() + Expect(c.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + newHash, newReferences, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(newHash).ToNot(Equal(hash)) + Expect(newReferences).To(HaveLen(1)) + Expect(newReferences[0].Hash).ToNot(Equal(references[0].Hash)) + }) + + It("Resources: does not change the references when a setting of the profile changes", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{ + { + Namespace: configMap.Namespace, Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + }, + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + hash, references, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + + clusterSummary.Spec.ClusterProfileSpec.Tier = 50 + + newHash, newReferences, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(newHash).ToNot(Equal(hash)) + Expect(newReferences).To(Equal(references)) + }) + + It("Resources: does not have a reference for a ConfigMap that does not exist", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{ + { + Namespace: configMap.Namespace, Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + }, + } + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(cluster).Build() + + _, references, err := controllers.ResourcesConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(references).To(BeEmpty()) + }) + + It("Kustomize: has the hash of each referenced ConfigMap, and changes when its content changes", func() { + clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs = []configv1beta1.KustomizationRef{ + { + Namespace: configMap.Namespace, Name: configMap.Name, + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), Path: kustomizePath, + }, + } + // kustomizationHash fetches the Cluster through the management cluster client + ns := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: clusterSummary.Spec.ClusterNamespace}} + Expect(testEnv.Create(context.TODO(), ns)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, ns)).To(Succeed()) + mgmtCluster := cluster.DeepCopy() + Expect(testEnv.Create(context.TODO(), mgmtCluster)).To(Succeed()) + Expect(waitForObject(context.TODO(), testEnv.Client, mgmtCluster)).To(Succeed()) + + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(configMap, cluster).Build() + + hash, references, err := controllers.KustomizationConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(references).To(HaveLen(1)) + Expect(references[0].Source).To(Equal(configv1beta1.ReferenceSourceKustomizationRef)) + Expect(references[0].Namespace).To(Equal(configMap.Namespace)) + Expect(references[0].Name).To(Equal(configMap.Name)) + + onlyHash, err := controllers.KustomizationHash(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(onlyHash).To(Equal(hash)) + + currentConfigMap := &corev1.ConfigMap{} + Expect(c.Get(context.TODO(), client.ObjectKeyFromObject(configMap), currentConfigMap)).To(Succeed()) + currentConfigMap.Data["policy0.yaml"] = randomString() + Expect(c.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + newHash, newReferences, err := controllers.KustomizationConfiguration(context.TODO(), c, clusterSummary, logger) + Expect(err).To(BeNil()) + Expect(newHash).ToNot(Equal(hash)) + Expect(newReferences).To(HaveLen(1)) + Expect(newReferences[0].Hash).ToNot(Equal(references[0].Hash)) + }) +}) diff --git a/controllers/remote_access_test.go b/controllers/remote_access_test.go new file mode 100644 index 00000000..fc79b0be --- /dev/null +++ b/controllers/remote_access_test.go @@ -0,0 +1,231 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 controllers_test + +import ( + "context" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + "k8s.io/klog/v2/textlogger" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + "github.com/projectsveltos/addon-controller/controllers" + "github.com/projectsveltos/addon-controller/controllers/chartmanager" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" +) + +const gitRepositoryKind = "GitRepository" + +var _ = Describe("Remote access of a ClusterSummary", func() { + var clusterSummary *configv1beta1.ClusterSummary + + localPolicyRef := func() configv1beta1.PolicyRef { + return configv1beta1.PolicyRef{ + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Namespace: randomString(), + Name: randomString(), + DeploymentType: configv1beta1.DeploymentTypeLocal, + } + } + + remotePolicyRef := func() configv1beta1.PolicyRef { + ref := localPolicyRef() + ref.DeploymentType = configv1beta1.DeploymentTypeRemote + return ref + } + + makeTenant := func() { + clusterSummary.Labels = map[string]string{ + libsveltosv1beta1.ServiceAccountNamespaceLabel: randomString(), + libsveltosv1beta1.ServiceAccountNameLabel: randomString(), + } + } + + BeforeEach(func() { + clusterSummary = &configv1beta1.ClusterSummary{} + clusterSummary.Name = randomString() + clusterSummary.Namespace = randomString() + clusterSummary.Spec.ClusterNamespace = randomString() + clusterSummary.Spec.ClusterName = randomString() + clusterSummary.Spec.ClusterType = libsveltosv1beta1.ClusterTypeCapi + }) + + Context("needsRemoteAccess", func() { + It("is true for helm charts, which are always deployed in the managed cluster", func() { + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureHelm)).To(BeTrue()) + }) + + It("is false for policyRefs that are all deployed in the management cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef(), localPolicyRef()} + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeFalse()) + }) + + It("is true when at least one policyRef is deployed in the managed cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef(), remotePolicyRef()} + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeTrue()) + }) + + It("is true when a policyRef does not set the deployment type (defaults to Remote)", func() { + ref := localPolicyRef() + ref.DeploymentType = "" + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{ref} + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeTrue()) + }) + + It("is false for kustomizationRefs that are all deployed in the management cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs = []configv1beta1.KustomizationRef{ + {Kind: gitRepositoryKind, Namespace: randomString(), Name: randomString(), + DeploymentType: configv1beta1.DeploymentTypeLocal}, + } + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureKustomize)).To(BeFalse()) + }) + + It("is true when at least one kustomizationRef is deployed in the managed cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs = []configv1beta1.KustomizationRef{ + {Kind: gitRepositoryKind, Namespace: randomString(), Name: randomString(), + DeploymentType: configv1beta1.DeploymentTypeLocal}, + {Kind: gitRepositoryKind, Namespace: randomString(), Name: randomString(), + DeploymentType: configv1beta1.DeploymentTypeRemote}, + } + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureKustomize)).To(BeTrue()) + }) + + It("only looks at the refs of the feature", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef()} + clusterSummary.Spec.ClusterProfileSpec.KustomizationRefs = []configv1beta1.KustomizationRef{ + {Kind: gitRepositoryKind, Namespace: randomString(), Name: randomString(), + DeploymentType: configv1beta1.DeploymentTypeRemote}, + } + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeFalse()) + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureKustomize)).To(BeTrue()) + }) + + It("is true when checks must run against the managed cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef()} + + clusterSummary.Spec.ClusterProfileSpec.PreDeployChecks = []libsveltosv1beta1.ValidateHealth{ + {Name: randomString(), FeatureID: libsveltosv1beta1.FeatureResources}, + } + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeTrue()) + + clusterSummary.Spec.ClusterProfileSpec.PreDeployChecks = nil + clusterSummary.Spec.ClusterProfileSpec.ValidateHealths = []libsveltosv1beta1.ValidateHealth{ + {Name: randomString(), FeatureID: libsveltosv1beta1.FeatureResources}, + } + Expect(controllers.NeedsRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeTrue()) + }) + }) + + Context("skipRemoteAccess", func() { + It("is true for a tenant deploying only in the management cluster", func() { + makeTenant() + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef()} + Expect(controllers.SkipRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeTrue()) + }) + + It("is false for a tenant deploying in the managed cluster", func() { + makeTenant() + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{remotePolicyRef()} + Expect(controllers.SkipRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeFalse()) + }) + + It("is false for a tenant deploying helm charts", func() { + makeTenant() + Expect(controllers.SkipRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureHelm)).To(BeFalse()) + }) + + It("is false for a platform admin, even when deploying only in the management cluster", func() { + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef()} + Expect(controllers.SkipRemoteAccess(clusterSummary, libsveltosv1beta1.FeatureResources)).To(BeFalse()) + }) + }) + + Context("skipRemoteAccessToUndeployHelm", func() { + newHelmChart := func() configv1beta1.HelmChart { + return configv1beta1.HelmChart{ + RepositoryURL: randomString(), ReleaseName: randomString(), ReleaseNamespace: randomString(), + } + } + + It("is true for a tenant that never deployed a helm chart", func() { + makeTenant() + + skip, err := controllers.SkipRemoteAccessToUndeployHelm(context.TODO(), testEnv.Client, clusterSummary) + Expect(err).To(BeNil()) + Expect(skip).To(BeTrue()) + }) + + It("is false for a tenant referencing helm charts", func() { + makeTenant() + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = []configv1beta1.HelmChart{newHelmChart()} + + skip, err := controllers.SkipRemoteAccessToUndeployHelm(context.TODO(), testEnv.Client, clusterSummary) + Expect(err).To(BeNil()) + Expect(skip).To(BeFalse()) + }) + + It("is false for a tenant with helm releases still listed in the status", func() { + makeTenant() + clusterSummary.Status.HelmReleaseSummaries = []configv1beta1.HelmChartSummary{ + {ReleaseName: randomString(), ReleaseNamespace: randomString()}, + } + + skip, err := controllers.SkipRemoteAccessToUndeployHelm(context.TODO(), testEnv.Client, clusterSummary) + Expect(err).To(BeNil()) + Expect(skip).To(BeFalse()) + }) + + It("is false for a tenant whose helm chart was removed from the spec after being deployed", func() { + makeTenant() + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = []configv1beta1.HelmChart{newHelmChart()} + + // The chart was deployed: the ClusterSummary is registered as the manager of the release + manager, err := chartmanager.GetChartManagerInstance(context.TODO(), testEnv.Client) + Expect(err).To(BeNil()) + manager.RegisterClusterSummaryForCharts(clusterSummary) + + // The chart is removed from the spec and the status does not list it anymore. The release is + // still in the managed cluster: it must be found and uninstalled using the tenant identity. + clusterSummary.Spec.ClusterProfileSpec.HelmCharts = nil + clusterSummary.Status.HelmReleaseSummaries = nil + + skip, err := controllers.SkipRemoteAccessToUndeployHelm(context.TODO(), testEnv.Client, clusterSummary) + Expect(err).To(BeNil()) + Expect(skip).To(BeFalse()) + }) + + It("is false for a platform admin", func() { + skip, err := controllers.SkipRemoteAccessToUndeployHelm(context.TODO(), testEnv.Client, clusterSummary) + Expect(err).To(BeNil()) + Expect(skip).To(BeFalse()) + }) + }) + + Context("getRestConfig", func() { + It("returns no restConfig, and no error, for a tenant deploying only in the management cluster", func() { + makeTenant() + clusterSummary.Spec.ClusterProfileSpec.PolicyRefs = []configv1beta1.PolicyRef{localPolicyRef()} + + config, _, err := controllers.GetRestConfig(context.TODO(), clusterSummary, + libsveltosv1beta1.FeatureResources, textlogger.NewLogger(textlogger.NewConfig())) + Expect(err).To(BeNil()) + Expect(config).To(BeNil()) + }) + }) +}) diff --git a/lib/crd/clustersummaries.go b/lib/crd/clustersummaries.go index 2cd9ccaa..d3f1b3c6 100644 --- a/lib/crd/clustersummaries.go +++ b/lib/crd/clustersummaries.go @@ -38,6 +38,10 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + - description: Features with changes not deployed because reconciliation is suspended + jsonPath: .status.pendingFeatures[*].featureID + name: Pending + type: string - description: Indicates whether HelmCharts are all provisioned jsonPath: .status.featureSummaries[?(@.featureID=="Helm")].status name: HelmCharts @@ -2616,6 +2620,54 @@ spec: description: LastAppliedTime is the time feature was last reconciled format: date-time type: string + referenceHashes: + description: |- + ReferenceHashes records, for each resource the feature configuration depends on (referenced + ConfigMaps, Secrets and sources, templateResourceRefs), a short hash of its content at the time + Hash was computed. Comparing it with the current content tells which resource changed when the + feature has changes not deployed yet (see ClusterSummary Status.PendingFeatures). + It always describes the configuration Hash was computed from. Not used by the Helm feature: + HelmReleaseSummaries already records the same information. + items: + description: ReferenceHash is a short hash of the content + of a resource a feature depends on. + properties: + hash: + description: Hash is a short hash of the content of the + resource + type: string + kind: + description: Kind of the resource + type: string + name: + description: Name of the resource + type: string + namespace: + description: Namespace of the resource. Empty for cluster + scoped resources. + type: string + source: + description: Source tells where the resource is referenced + from + enum: + - PolicyRef + - KustomizationRef + - TemplateResourceRef + type: string + required: + - hash + - kind + - name + - source + type: object + type: array + x-kubernetes-list-type: atomic + referencesRecorded: + description: |- + ReferencesRecorded is true when ReferenceHashes was recorded together with Hash. An empty + ReferenceHashes then means the feature depends on no resource. It is false for a feature last + deployed by a version that did not record ReferenceHashes. + type: boolean resourceSummaryDeployed: description: |- ResourceSummaryDeployed tracks whether a ResourceSummary was deployed @@ -2767,6 +2819,92 @@ spec: If not set, reconciliations will happen as usual. format: date-time type: string + pendingFeatures: + description: |- + PendingFeatures lists the features whose desired configuration differs from what is currently + deployed. It is only populated while reconciliation is suspended (for instance because the + cluster is paused): in that state nothing is deployed, so this tells which features will be + redeployed once reconciliation resumes. It is evaluated each time the ClusterSummary is + reconciled while suspended, so it reflects the state at that moment. Cleared when reconciliation + resumes. + items: + description: PendingFeature describes a feature with changes that + are not deployed yet. + properties: + featureID: + description: FeatureID is an identifier of the feature with + pending changes + enum: + - Resources + - Helm + - Kustomize + type: string + items: + description: |- + Items lists what changed in the feature configuration, when it can be established. + For raw YAML and Kustomize a referenced resource is reported as a whole: which part of it + changed is not reported. Changes that cannot be attributed to an item (the profile settings, + or content fetched from a remote URL) are not listed. + items: + description: PendingItem describes one change not deployed + yet. + properties: + change: + description: Change is what happened to the item + enum: + - Added + - Removed + - Changed + type: string + detail: + description: Detail provides more information, for instance + what changed in a HelmChart + type: string + kind: + description: 'Kind of the item: the kind of the referenced + resource, or HelmChart' + type: string + name: + description: Name of the item. For a HelmChart it is the + release name. + type: string + namespace: + description: Namespace of the item. For a HelmChart it + is the release namespace. + type: string + required: + - change + - kind + - name + type: object + type: array + x-kubernetes-list-type: atomic + itemsTruncated: + description: ItemsTruncated is true when more than MaxPendingItems + items changed, so Items is not complete. + type: boolean + message: + description: |- + Message provides more information. Set when Reason is EvaluationFailed, or when Items does not + tell the whole story (for instance Items is empty because what changed cannot be attributed + to a referenced resource). + type: string + reason: + description: Reason is why the feature has pending changes + enum: + - ConfigurationChanged + - NotDeployed + - PendingRemoval + - EvaluationFailed + type: string + required: + - featureID + - reason + type: object + type: array + x-kubernetes-list-map-keys: + - featureID + x-kubernetes-list-type: map reconciliationSuspended: description: |- ReconciliationSuspended indicates whether the reconciliation loop for this diff --git a/manifest/manifest.yaml b/manifest/manifest.yaml index 8e7f6074..e0829b15 100644 --- a/manifest/manifest.yaml +++ b/manifest/manifest.yaml @@ -6826,6 +6826,10 @@ spec: jsonPath: .metadata.creationTimestamp name: Age type: date + - description: Features with changes not deployed because reconciliation is suspended + jsonPath: .status.pendingFeatures[*].featureID + name: Pending + type: string - description: Indicates whether HelmCharts are all provisioned jsonPath: .status.featureSummaries[?(@.featureID=="Helm")].status name: HelmCharts @@ -9404,6 +9408,54 @@ spec: description: LastAppliedTime is the time feature was last reconciled format: date-time type: string + referenceHashes: + description: |- + ReferenceHashes records, for each resource the feature configuration depends on (referenced + ConfigMaps, Secrets and sources, templateResourceRefs), a short hash of its content at the time + Hash was computed. Comparing it with the current content tells which resource changed when the + feature has changes not deployed yet (see ClusterSummary Status.PendingFeatures). + It always describes the configuration Hash was computed from. Not used by the Helm feature: + HelmReleaseSummaries already records the same information. + items: + description: ReferenceHash is a short hash of the content + of a resource a feature depends on. + properties: + hash: + description: Hash is a short hash of the content of the + resource + type: string + kind: + description: Kind of the resource + type: string + name: + description: Name of the resource + type: string + namespace: + description: Namespace of the resource. Empty for cluster + scoped resources. + type: string + source: + description: Source tells where the resource is referenced + from + enum: + - PolicyRef + - KustomizationRef + - TemplateResourceRef + type: string + required: + - hash + - kind + - name + - source + type: object + type: array + x-kubernetes-list-type: atomic + referencesRecorded: + description: |- + ReferencesRecorded is true when ReferenceHashes was recorded together with Hash. An empty + ReferenceHashes then means the feature depends on no resource. It is false for a feature last + deployed by a version that did not record ReferenceHashes. + type: boolean resourceSummaryDeployed: description: |- ResourceSummaryDeployed tracks whether a ResourceSummary was deployed @@ -9555,6 +9607,92 @@ spec: If not set, reconciliations will happen as usual. format: date-time type: string + pendingFeatures: + description: |- + PendingFeatures lists the features whose desired configuration differs from what is currently + deployed. It is only populated while reconciliation is suspended (for instance because the + cluster is paused): in that state nothing is deployed, so this tells which features will be + redeployed once reconciliation resumes. It is evaluated each time the ClusterSummary is + reconciled while suspended, so it reflects the state at that moment. Cleared when reconciliation + resumes. + items: + description: PendingFeature describes a feature with changes that + are not deployed yet. + properties: + featureID: + description: FeatureID is an identifier of the feature with + pending changes + enum: + - Resources + - Helm + - Kustomize + type: string + items: + description: |- + Items lists what changed in the feature configuration, when it can be established. + For raw YAML and Kustomize a referenced resource is reported as a whole: which part of it + changed is not reported. Changes that cannot be attributed to an item (the profile settings, + or content fetched from a remote URL) are not listed. + items: + description: PendingItem describes one change not deployed + yet. + properties: + change: + description: Change is what happened to the item + enum: + - Added + - Removed + - Changed + type: string + detail: + description: Detail provides more information, for instance + what changed in a HelmChart + type: string + kind: + description: 'Kind of the item: the kind of the referenced + resource, or HelmChart' + type: string + name: + description: Name of the item. For a HelmChart it is the + release name. + type: string + namespace: + description: Namespace of the item. For a HelmChart it + is the release namespace. + type: string + required: + - change + - kind + - name + type: object + type: array + x-kubernetes-list-type: atomic + itemsTruncated: + description: ItemsTruncated is true when more than MaxPendingItems + items changed, so Items is not complete. + type: boolean + message: + description: |- + Message provides more information. Set when Reason is EvaluationFailed, or when Items does not + tell the whole story (for instance Items is empty because what changed cannot be attributed + to a referenced resource). + type: string + reason: + description: Reason is why the feature has pending changes + enum: + - ConfigurationChanged + - NotDeployed + - PendingRemoval + - EvaluationFailed + type: string + required: + - featureID + - reason + type: object + type: array + x-kubernetes-list-map-keys: + - featureID + x-kubernetes-list-type: map reconciliationSuspended: description: |- ReconciliationSuspended indicates whether the reconciliation loop for this diff --git a/pkg/scope/clustersummary.go b/pkg/scope/clustersummary.go index 69038af3..de8b084f 100644 --- a/pkg/scope/clustersummary.go +++ b/pkg/scope/clustersummary.go @@ -17,6 +17,7 @@ limitations under the License. package scope import ( + "bytes" "context" "github.com/go-logr/logr" @@ -70,6 +71,16 @@ type ClusterSummaryScope struct { Profile client.Object ClusterSummary *configv1beta1.ClusterSummary controllerName string + + // stagedReferences holds, per feature, the ReferenceHashes computed together with a configuration hash + // but not yet recorded in the status. See StageReferenceHashes. + stagedReferences map[libsveltosv1beta1.FeatureID]stagedReferenceHashes +} + +// stagedReferenceHashes are the ReferenceHashes computed together with hash +type stagedReferenceHashes struct { + hash []byte + references []configv1beta1.ReferenceHash } // PatchObject persists the cluster configuration and status. @@ -101,26 +112,69 @@ func (s *ClusterSummaryScope) initializeFeatureStatusSummary() { } } +// StageReferenceHashes remembers the ReferenceHashes computed together with hash, the hash of the +// configuration of the feature. SetFeatureStatus records them, with the hash, when it stores that +// same hash. Staging them, instead of passing them to SetFeatureStatus, keeps the references always +// consistent with the hash they were computed from. +func (s *ClusterSummaryScope) StageReferenceHashes(featureID libsveltosv1beta1.FeatureID, hash []byte, + references []configv1beta1.ReferenceHash) { + + if s.stagedReferences == nil { + s.stagedReferences = make(map[libsveltosv1beta1.FeatureID]stagedReferenceHashes) + } + s.stagedReferences[featureID] = stagedReferenceHashes{hash: hash, references: references} +} + +// syncReferenceHashes makes the ReferenceHashes of featureSummary consistent with its Hash, which is +// being changed from previousHash. They are replaced by the staged ones if those were computed from the +// hash being stored. Otherwise they are dropped if the hash changed: they describe a configuration +// that is not the one the hash is about anymore. +func (s *ClusterSummaryScope) syncReferenceHashes(featureSummary *configv1beta1.FeatureSummary, previousHash []byte) { + staged, ok := s.stagedReferences[featureSummary.FeatureID] + if ok && len(staged.hash) != 0 && bytes.Equal(staged.hash, featureSummary.Hash) { + featureSummary.ReferenceHashes = staged.references + featureSummary.ReferencesRecorded = true + return + } + + if !bytes.Equal(previousHash, featureSummary.Hash) { + featureSummary.ReferenceHashes = nil + featureSummary.ReferencesRecorded = false + } +} + +// updateFeatureSummary sets status and hash of an existing FeatureSummary +func (s *ClusterSummaryScope) updateFeatureSummary(featureSummary *configv1beta1.FeatureSummary, + status libsveltosv1beta1.FeatureStatus, hash []byte, failed *bool) { + + previousHash := featureSummary.Hash + featureSummary.Status = status + featureSummary.Hash = hash + s.syncReferenceHashes(featureSummary, previousHash) + + // In DryRun mode we always get an error back. Do not increase ConsecutiveFailures + if s.ClusterSummary.Spec.ClusterProfileSpec.SyncMode == configv1beta1.SyncModeDryRun || failed == nil { + return + } + + if *failed { + featureSummary.ConsecutiveFailures++ + } else { + featureSummary.ConsecutiveFailures = 0 + } +} + // SetFeatureStatus sets the feature status. func (s *ClusterSummaryScope) SetFeatureStatus(featureID libsveltosv1beta1.FeatureID, status libsveltosv1beta1.FeatureStatus, hash []byte, failed *bool) { for i := range s.ClusterSummary.Status.FeatureSummaries { - if s.ClusterSummary.Status.FeatureSummaries[i].FeatureID == featureID { - s.ClusterSummary.Status.FeatureSummaries[i].Status = status - s.ClusterSummary.Status.FeatureSummaries[i].Hash = hash - if s.ClusterSummary.Spec.ClusterProfileSpec.SyncMode != configv1beta1.SyncModeDryRun { - // In DryRun mode we always get an error back. Do not increase ConsecutiveFailures - if failed != nil { - if *failed { - s.ClusterSummary.Status.FeatureSummaries[i].ConsecutiveFailures++ - } else { - s.ClusterSummary.Status.FeatureSummaries[i].ConsecutiveFailures = 0 - } - } - } - return + if s.ClusterSummary.Status.FeatureSummaries[i].FeatureID != featureID { + continue } + + s.updateFeatureSummary(&s.ClusterSummary.Status.FeatureSummaries[i], status, hash, failed) + return } s.initializeFeatureStatusSummary() @@ -130,15 +184,15 @@ func (s *ClusterSummaryScope) SetFeatureStatus(featureID libsveltosv1beta1.Featu consecutiveFailures = 1 } - s.ClusterSummary.Status.FeatureSummaries = append( - s.ClusterSummary.Status.FeatureSummaries, - configv1beta1.FeatureSummary{ - FeatureID: featureID, - Status: status, - Hash: hash, - ConsecutiveFailures: consecutiveFailures, - }, - ) + featureSummary := configv1beta1.FeatureSummary{ + FeatureID: featureID, + Status: status, + Hash: hash, + ConsecutiveFailures: consecutiveFailures, + } + s.syncReferenceHashes(&featureSummary, nil) + + s.ClusterSummary.Status.FeatureSummaries = append(s.ClusterSummary.Status.FeatureSummaries, featureSummary) } // ResetConsecutiveFailures reset status consecutiveFailures diff --git a/pkg/scope/clustersummary_test.go b/pkg/scope/clustersummary_test.go index 094bd244..0758efc2 100644 --- a/pkg/scope/clustersummary_test.go +++ b/pkg/scope/clustersummary_test.go @@ -494,4 +494,94 @@ var _ = Describe("ClusterSummaryScope", func() { scope.SetDependenciesMessage(nil) Expect(clusterSummary.Status.Dependencies).To(BeNil()) }) + + Context("reference hashes", func() { + var clusterSummaryScope *scope.ClusterSummaryScope + var references []configv1beta1.ReferenceHash + + BeforeEach(func() { + var err error + clusterSummaryScope, err = scope.NewClusterSummaryScope(&scope.ClusterSummaryScopeParams{ + Client: c, + Profile: clusterProfile, + ClusterSummary: clusterSummary, + Logger: textlogger.NewLogger(textlogger.NewConfig()), + }) + Expect(err).ToNot(HaveOccurred()) + + references = []configv1beta1.ReferenceHash{ + { + Source: configv1beta1.ReferenceSourcePolicyRef, Kind: "ConfigMap", + Namespace: randomString(), Name: randomString(), Hash: "0a1b2c3d", + }, + } + }) + + setStatus := func(hash []byte) { + failed := false + clusterSummaryScope.SetFeatureStatus(libsveltosv1beta1.FeatureResources, + libsveltosv1beta1.FeatureStatusProvisioned, hash, &failed) + } + + It("records the staged references when the hash they were computed from is stored", func() { + hash := []byte(randomString()) + clusterSummaryScope.StageReferenceHashes(libsveltosv1beta1.FeatureResources, hash, references) + + setStatus(hash) + + Expect(clusterSummary.Status.FeatureSummaries).To(HaveLen(1)) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(Equal(references)) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeTrue()) + }) + + It("records that the feature depends on nothing when no reference was staged for a hash", func() { + hash := []byte(randomString()) + clusterSummaryScope.StageReferenceHashes(libsveltosv1beta1.FeatureResources, hash, nil) + + setStatus(hash) + + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(BeEmpty()) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeTrue()) + }) + + It("does not record references when none was staged", func() { + setStatus([]byte(randomString())) + + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(BeEmpty()) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeFalse()) + }) + + It("does not record references staged for a different hash", func() { + clusterSummaryScope.StageReferenceHashes(libsveltosv1beta1.FeatureResources, []byte(randomString()), references) + + setStatus([]byte(randomString())) + + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(BeEmpty()) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeFalse()) + }) + + It("keeps the references while the hash does not change", func() { + hash := []byte(randomString()) + clusterSummaryScope.StageReferenceHashes(libsveltosv1beta1.FeatureResources, hash, references) + setStatus(hash) + + // Status updated (for instance deployment in progress) without staging references again + provisioning := libsveltosv1beta1.FeatureStatusProvisioning + clusterSummaryScope.SetFeatureStatus(libsveltosv1beta1.FeatureResources, provisioning, hash, nil) + + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(Equal(references)) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeTrue()) + }) + + It("drops the references when the hash changes without new references", func() { + hash := []byte(randomString()) + clusterSummaryScope.StageReferenceHashes(libsveltosv1beta1.FeatureResources, hash, references) + setStatus(hash) + + setStatus(nil) + + Expect(clusterSummary.Status.FeatureSummaries[0].ReferenceHashes).To(BeEmpty()) + Expect(clusterSummary.Status.FeatureSummaries[0].ReferencesRecorded).To(BeFalse()) + }) + }) }) diff --git a/test/fv/paused_pending_items_test.go b/test/fv/paused_pending_items_test.go new file mode 100644 index 00000000..cb34f39e --- /dev/null +++ b/test/fv/paused_pending_items_test.go @@ -0,0 +1,463 @@ +/* +Copyright 2026. projectsveltos.io. All rights reserved. + +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 fv_test + +import ( + "context" + "fmt" + "strings" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/util/retry" + + configv1beta1 "github.com/projectsveltos/addon-controller/api/v1beta1" + "github.com/projectsveltos/addon-controller/lib/clusterops" + libsveltosv1beta1 "github.com/projectsveltos/libsveltos/api/v1beta1" +) + +const ( + // pendingHelmChartKind is the Kind of the PendingItem reported for a Helm chart + pendingHelmChartKind = "HelmChart" + + // pendingKustomizePath is the path, in the kustomize ConfigMap created by Makefile, of the overlay deployed + pendingKustomizePath = "./overlays/production/" +) + +// While a cluster is paused its ClusterSummary does not deploy anything. Those tests verify the +// ClusterSummary tells what is pending (Status.PendingFeatures), item by item, for each feature. +// Each test deploys with the cluster not paused, pauses it, changes the configuration, verifies what +// is reported and finally either reverts the change or unpauses the cluster. +var _ = Describe("Paused cluster pending items", Serial, func() { + const ( + namePrefix = "paused-items-" + ) + + BeforeEach(func() { + // Whatever happens, never leave the cluster paused: it would break the tests running after + DeferCleanup(func() { + setClusterPausedField(false) + }) + }) + + It("Resources: reports which ConfigMap changed, was added or was removed", Label("FV", "PULLMODE", "EXTENDED"), func() { + changedNamespace, removedNamespace, addedNamespace := randomString(), randomString(), randomString() + + Byf("Creating three ConfigMaps, each with a Namespace") + changedConfigMap := createConfigMapWithPolicy(defaultNamespace, namePrefix+randomString(), + fmt.Sprintf(devNamespace, changedNamespace)) + unchangedConfigMap := createConfigMapWithPolicy(defaultNamespace, namePrefix+randomString(), + fmt.Sprintf(devNamespace, randomString())) + removedConfigMap := createConfigMapWithPolicy(defaultNamespace, namePrefix+randomString(), + fmt.Sprintf(devNamespace, removedNamespace)) + addedConfigMap := createConfigMapWithPolicy(defaultNamespace, namePrefix+randomString(), + fmt.Sprintf(devNamespace, addedNamespace)) + for _, cm := range []*corev1.ConfigMap{changedConfigMap, unchangedConfigMap, removedConfigMap, addedConfigMap} { + Expect(k8sClient.Create(context.TODO(), cm)).To(Succeed()) + } + + Byf("Creating a ClusterProfile referencing the first three ConfigMaps") + clusterProfile := getClusterProfile(namePrefix, map[string]string{key: value}) + clusterProfile.Spec.SyncMode = configv1beta1.SyncModeContinuous + clusterProfile.Spec.PolicyRefs = getConfigMapPolicyRefs(changedConfigMap, unchangedConfigMap, removedConfigMap) + Expect(k8sClient.Create(context.TODO(), clusterProfile)).To(Succeed()) + verifyClusterProfileMatches(clusterProfile) + clusterSummary := verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + &clusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + + Byf("Waiting for Resources to be deployed") + verifyFeatureStatusIsProvisioned(clusterSummary.Namespace, clusterSummary.Name, libsveltosv1beta1.FeatureResources) + + Byf("Verifying the ConfigMaps the deployment depends on are recorded") + Eventually(func() []string { + return getRecordedReferenceNames(clusterSummary, libsveltosv1beta1.FeatureResources) + }, timeout, pollingInterval).Should(ConsistOf( + changedConfigMap.Name, unchangedConfigMap.Name, removedConfigMap.Name)) + + Byf("Setting Cluster as paused") + setClusterPausedField(true) + + Byf("Changing a ConfigMap, adding one to the references and removing one") + currentConfigMap := &corev1.ConfigMap{} + Expect(k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: changedConfigMap.Namespace, Name: changedConfigMap.Name}, currentConfigMap)).To(Succeed()) + currentConfigMap = updateConfigMapWithPolicy(currentConfigMap, fmt.Sprintf(devNamespace, randomString())) + Expect(k8sClient.Update(context.TODO(), currentConfigMap)).To(Succeed()) + + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.PolicyRefs = getConfigMapPolicyRefs(changedConfigMap, unchangedConfigMap, addedConfigMap) + }) + currentClusterProfile := &configv1beta1.ClusterProfile{} + Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) + verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + ¤tClusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + + Byf("Verifying only the ConfigMaps that changed are reported as pending") + verifyPendingFeature(clusterSummary, libsveltosv1beta1.FeatureResources, + configv1beta1.PendingReasonConfigurationChanged, + configMapItem(changedConfigMap, configv1beta1.PendingChangeChanged), + configMapItem(addedConfigMap, configv1beta1.PendingChangeAdded), + configMapItem(removedConfigMap, configv1beta1.PendingChangeRemoved)) + + Byf("Verifying nothing was deployed while paused") + workloadClient, err := getKindWorkloadClusterKubeconfig() + Expect(err).To(BeNil()) + Consistently(func() bool { + err := workloadClient.Get(context.TODO(), types.NamespacedName{Name: addedNamespace}, &corev1.Namespace{}) + return apierrors.IsNotFound(err) + }, timeout/4, pollingInterval).Should(BeTrue()) + + Byf("Setting Cluster as unpaused") + setClusterPausedField(false) + + Byf("Verifying the pending changes are deployed") + Eventually(func() error { + return workloadClient.Get(context.TODO(), types.NamespacedName{Name: addedNamespace}, &corev1.Namespace{}) + }, timeout, pollingInterval).Should(BeNil()) + Eventually(func() bool { + err := workloadClient.Get(context.TODO(), types.NamespacedName{Name: removedNamespace}, &corev1.Namespace{}) + return apierrors.IsNotFound(err) + }, timeout, pollingInterval).Should(BeTrue()) + + Byf("Verifying nothing is pending anymore and the ConfigMaps now deployed are recorded") + verifyNoPendingFeature(clusterSummary) + Eventually(func() []string { + return getRecordedReferenceNames(clusterSummary, libsveltosv1beta1.FeatureResources) + }, timeout, pollingInterval).Should(ConsistOf( + changedConfigMap.Name, unchangedConfigMap.Name, addedConfigMap.Name)) + + deleteClusterProfile(clusterProfile) + }) + + It("Resources: reports no item when only a profile setting changed", Label("FV", "PULLMODE", "EXTENDED"), func() { + configMap := createConfigMapWithPolicy(defaultNamespace, namePrefix+randomString(), + fmt.Sprintf(devNamespace, randomString())) + Expect(k8sClient.Create(context.TODO(), configMap)).To(Succeed()) + + clusterProfile := getClusterProfile(namePrefix, map[string]string{key: value}) + clusterProfile.Spec.SyncMode = configv1beta1.SyncModeContinuous + clusterProfile.Spec.PolicyRefs = getConfigMapPolicyRefs(configMap) + Expect(k8sClient.Create(context.TODO(), clusterProfile)).To(Succeed()) + verifyClusterProfileMatches(clusterProfile) + clusterSummary := verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + &clusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + verifyFeatureStatusIsProvisioned(clusterSummary.Namespace, clusterSummary.Name, libsveltosv1beta1.FeatureResources) + + Byf("Setting Cluster as paused") + setClusterPausedField(true) + + Byf("Changing a setting of the ClusterProfile: no referenced resource changes") + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.ContinueOnConflict = true + }) + currentClusterProfile := &configv1beta1.ClusterProfile{} + Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) + verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + ¤tClusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + + Byf("Verifying the feature is pending, with no item but a message saying why") + Eventually(func() bool { + pending := getPendingFeature(clusterSummary, libsveltosv1beta1.FeatureResources) + return pending != nil && + pending.Reason == configv1beta1.PendingReasonConfigurationChanged && + len(pending.Items) == 0 && + pending.Message != nil + }, timeout, pollingInterval).Should(BeTrue()) + + Byf("Reverting the change: nothing is pending anymore") + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.ContinueOnConflict = false + }) + verifyNoPendingFeature(clusterSummary) + + Byf("Setting Cluster as unpaused") + setClusterPausedField(false) + + deleteClusterProfile(clusterProfile) + }) + + It("Helm: reports which chart changed (version and values) or was removed", Label("FV", "PULLMODE", "EXTENDED"), func() { + chart := configv1beta1.HelmChart{ + RepositoryURL: kyvernoRepoURL, + RepositoryName: kyvernoNamespace, + ChartName: kyvernoChartName, + ChartVersion: kyvernoVersion391, + ReleaseName: kyvernoLatestRelease, + ReleaseNamespace: kyvernoNamespace, + HelmChartAction: configv1beta1.HelmChartActionInstall, + } + chartItem := func(change configv1beta1.PendingChange) configv1beta1.PendingItem { + return configv1beta1.PendingItem{ + Kind: pendingHelmChartKind, Namespace: chart.ReleaseNamespace, Name: chart.ReleaseName, Change: change, + } + } + + Byf("Creating a ClusterProfile deploying the chart") + clusterProfile := getClusterProfile(namePrefix, map[string]string{key: value}) + clusterProfile.Spec.SyncMode = configv1beta1.SyncModeContinuous + clusterProfile.Spec.HelmCharts = []configv1beta1.HelmChart{chart} + Expect(k8sClient.Create(context.TODO(), clusterProfile)).To(Succeed()) + verifyClusterProfileMatches(clusterProfile) + clusterSummary := verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + &clusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + verifyFeatureStatusIsProvisioned(clusterSummary.Namespace, clusterSummary.Name, libsveltosv1beta1.FeatureHelm) + + Byf("Setting Cluster as paused") + setClusterPausedField(true) + + Byf("Changing chart version and values") + changedChart := chart + changedChart.ChartVersion = kyvernoVersion390 + changedChart.Values = "replicaCount: 2" + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.HelmCharts = []configv1beta1.HelmChart{changedChart} + }) + + Byf("Verifying the chart is reported with what changed") + Eventually(func() bool { + pending := getPendingFeature(clusterSummary, libsveltosv1beta1.FeatureHelm) + if pending == nil || pending.Reason != configv1beta1.PendingReasonConfigurationChanged || + len(pending.Items) != 1 { + + return false + } + item := pending.Items[0] + return item.Kind == pendingHelmChartKind && item.Namespace == chart.ReleaseNamespace && + item.Name == chart.ReleaseName && item.Change == configv1beta1.PendingChangeChanged && + containsAll(item.Detail, "version: ", kyvernoVersion390, "values changed") + }, timeout, pollingInterval).Should(BeTrue()) + + Byf("Removing the chart from the ClusterProfile") + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.HelmCharts = nil + }) + + Byf("Verifying the chart is reported as to be removed") + verifyPendingFeature(clusterSummary, libsveltosv1beta1.FeatureHelm, + configv1beta1.PendingReasonPendingRemoval, chartItem(configv1beta1.PendingChangeRemoved)) + + Byf("Putting the chart back as it was deployed: nothing is pending anymore") + updateClusterProfile(clusterProfile.Name, func(cp *configv1beta1.ClusterProfile) { + cp.Spec.HelmCharts = []configv1beta1.HelmChart{chart} + }) + verifyNoPendingFeature(clusterSummary) + + Byf("Setting Cluster as unpaused") + setClusterPausedField(false) + + deleteClusterProfile(clusterProfile) + }) + + It("Kustomize: reports the kustomization to be redeployed when its values change", Label("FV", "PULLMODE", "EXTENDED"), func() { + const kustomizeConfigMapName = "kustomize" + + Byf("Verifying ConfigMap kustomize exists. It is created by Makefile") + kustomizeConfigMap := &corev1.ConfigMap{} + Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Namespace: defaultNamespace, Name: kustomizeConfigMapName}, + kustomizeConfigMap)).To(Succeed()) + + valuesNamespace := randomString() + Expect(k8sClient.Create(context.TODO(), + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: valuesNamespace}})).To(Succeed()) + labelsValues := `customLabels: + %s: "%s"` + valuesConfigMap := createConfigMapWithPolicy(valuesNamespace, randomString(), fmt.Sprintf(labelsValues, "team", "blue")) + Expect(k8sClient.Create(context.TODO(), valuesConfigMap)).To(Succeed()) + + Byf("Creating a ClusterProfile with a kustomization taking its values from a ConfigMap") + clusterProfile := getClusterProfile(namePrefix, map[string]string{key: value}) + clusterProfile.Spec.SyncMode = configv1beta1.SyncModeContinuous + clusterProfile.Spec.KustomizationRefs = []configv1beta1.KustomizationRef{ + { + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Namespace: defaultNamespace, + Name: kustomizeConfigMapName, + Path: pendingKustomizePath, + TargetNamespace: randomString(), + ValuesFrom: []configv1beta1.ValueFrom{ + { + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Namespace: valuesConfigMap.Namespace, + Name: valuesConfigMap.Name, + }, + }, + }, + } + Expect(k8sClient.Create(context.TODO(), clusterProfile)).To(Succeed()) + verifyClusterProfileMatches(clusterProfile) + clusterSummary := verifyClusterSummary(clusterops.ClusterProfileLabelName, clusterProfile.Name, + &clusterProfile.Spec, kindWorkloadCluster.GetNamespace(), kindWorkloadCluster.GetName(), getClusterType()) + verifyFeatureStatusIsProvisioned(clusterSummary.Namespace, clusterSummary.Name, libsveltosv1beta1.FeatureKustomize) + + Byf("Verifying the ConfigMap the deployment depends on is recorded") + Eventually(func() []string { + return getRecordedReferenceNames(clusterSummary, libsveltosv1beta1.FeatureKustomize) + }, timeout, pollingInterval).Should(ConsistOf(kustomizeConfigMapName)) + + Byf("Setting Cluster as paused") + setClusterPausedField(true) + + Byf("Changing the values") + currentValuesConfigMap := &corev1.ConfigMap{} + Expect(k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: valuesConfigMap.Namespace, Name: valuesConfigMap.Name}, currentValuesConfigMap)).To(Succeed()) + currentValuesConfigMap = updateConfigMapWithPolicy(currentValuesConfigMap, fmt.Sprintf(labelsValues, "team", "red")) + Expect(k8sClient.Update(context.TODO(), currentValuesConfigMap)).To(Succeed()) + + Byf("Verifying the kustomization is reported as changed") + verifyPendingFeature(clusterSummary, libsveltosv1beta1.FeatureKustomize, + configv1beta1.PendingReasonConfigurationChanged, + configMapItem(kustomizeConfigMap, configv1beta1.PendingChangeChanged)) + + Byf("Reverting the values: nothing is pending anymore") + Expect(k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: valuesConfigMap.Namespace, Name: valuesConfigMap.Name}, currentValuesConfigMap)).To(Succeed()) + currentValuesConfigMap = updateConfigMapWithPolicy(currentValuesConfigMap, fmt.Sprintf(labelsValues, "team", "blue")) + Expect(k8sClient.Update(context.TODO(), currentValuesConfigMap)).To(Succeed()) + verifyNoPendingFeature(clusterSummary) + + Byf("Setting Cluster as unpaused") + setClusterPausedField(false) + + deleteClusterProfile(clusterProfile) + }) +}) + +// getConfigMapPolicyRefs returns a PolicyRef for each ConfigMap +func getConfigMapPolicyRefs(configMaps ...*corev1.ConfigMap) []configv1beta1.PolicyRef { + policyRefs := make([]configv1beta1.PolicyRef, 0, len(configMaps)) + for _, cm := range configMaps { + policyRefs = append(policyRefs, configv1beta1.PolicyRef{ + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Namespace: cm.Namespace, + Name: cm.Name, + }) + } + + return policyRefs +} + +// configMapItem returns the PendingItem expected for configMap +func configMapItem(configMap *corev1.ConfigMap, change configv1beta1.PendingChange) configv1beta1.PendingItem { + return configv1beta1.PendingItem{ + Kind: string(libsveltosv1beta1.ConfigMapReferencedResourceKind), + Namespace: configMap.Namespace, + Name: configMap.Name, + Change: change, + } +} + +// updateClusterProfile applies mutate to the ClusterProfile, retrying on conflict +func updateClusterProfile(name string, mutate func(clusterProfile *configv1beta1.ClusterProfile)) { + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + currentClusterProfile := &configv1beta1.ClusterProfile{} + if err := k8sClient.Get(context.TODO(), types.NamespacedName{Name: name}, currentClusterProfile); err != nil { + return err + } + mutate(currentClusterProfile) + return k8sClient.Update(context.TODO(), currentClusterProfile) + }) + Expect(err).To(BeNil()) +} + +// getPendingFeature returns the PendingFeature reported for featureID, nil if there is none +func getPendingFeature(clusterSummary *configv1beta1.ClusterSummary, + featureID libsveltosv1beta1.FeatureID) *configv1beta1.PendingFeature { + + currentClusterSummary := &configv1beta1.ClusterSummary{} + err := k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name}, currentClusterSummary) + if err != nil { + return nil + } + + for i := range currentClusterSummary.Status.PendingFeatures { + if currentClusterSummary.Status.PendingFeatures[i].FeatureID == featureID { + return ¤tClusterSummary.Status.PendingFeatures[i] + } + } + + return nil +} + +// verifyPendingFeature verifies featureID is reported as pending, with reason and exactly the items passed in +func verifyPendingFeature(clusterSummary *configv1beta1.ClusterSummary, featureID libsveltosv1beta1.FeatureID, + reason configv1beta1.PendingFeatureReason, items ...configv1beta1.PendingItem) { + + Eventually(func() *configv1beta1.PendingFeature { + return getPendingFeature(clusterSummary, featureID) + }, timeout, pollingInterval).Should(And( + Not(BeNil()), + HaveField("Reason", reason), + HaveField("Items", ConsistOf(items)), + HaveField("ItemsTruncated", false), + )) +} + +// verifyNoPendingFeature verifies the ClusterSummary does not report any pending feature +func verifyNoPendingFeature(clusterSummary *configv1beta1.ClusterSummary) { + Eventually(func() bool { + currentClusterSummary := &configv1beta1.ClusterSummary{} + err := k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name}, currentClusterSummary) + return err == nil && len(currentClusterSummary.Status.PendingFeatures) == 0 + }, timeout, pollingInterval).Should(BeTrue()) +} + +// getRecordedReferenceNames returns the names of the resources the last deployment of featureID depends on. +// Returns nil if they were not recorded. +func getRecordedReferenceNames(clusterSummary *configv1beta1.ClusterSummary, + featureID libsveltosv1beta1.FeatureID) []string { + + currentClusterSummary := &configv1beta1.ClusterSummary{} + err := k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name}, currentClusterSummary) + if err != nil { + return nil + } + + for i := range currentClusterSummary.Status.FeatureSummaries { + featureSummary := ¤tClusterSummary.Status.FeatureSummaries[i] + if featureSummary.FeatureID != featureID || !featureSummary.ReferencesRecorded { + continue + } + + names := make([]string, 0, len(featureSummary.ReferenceHashes)) + for j := range featureSummary.ReferenceHashes { + names = append(names, featureSummary.ReferenceHashes[j].Name) + } + return names + } + + return nil +} + +// containsAll returns true if s contains every one of the substrings +func containsAll(s string, substrings ...string) bool { + for _, substring := range substrings { + if !strings.Contains(s, substring) { + return false + } + } + + return true +} diff --git a/test/fv/paused_test.go b/test/fv/paused_test.go index 6de5291b..935148b6 100644 --- a/test/fv/paused_test.go +++ b/test/fv/paused_test.go @@ -105,6 +105,28 @@ var _ = Describe("Feature", Serial, func() { return apierrors.IsNotFound(err) }, timeout/2, pollingInterval).Should(BeTrue()) + Byf("Verifying ClusterSummary %s reports Resources as pending as cluster is paused", clusterSummary.Name) + Eventually(func() bool { + currentClusterSummary := &configv1beta1.ClusterSummary{} + err = k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name}, currentClusterSummary) + if err != nil { + return false + } + if len(currentClusterSummary.Status.PendingFeatures) != 1 { + return false + } + // The ConfigMap is what is pending + pending := currentClusterSummary.Status.PendingFeatures[0] + return pending.FeatureID == libsveltosv1beta1.FeatureResources && + pending.Reason == configv1beta1.PendingReasonNotDeployed && + len(pending.Items) == 1 && + pending.Items[0].Kind == string(libsveltosv1beta1.ConfigMapReferencedResourceKind) && + pending.Items[0].Namespace == configMap.Namespace && + pending.Items[0].Name == configMap.Name && + pending.Items[0].Change == configv1beta1.PendingChangeAdded + }, timeout, pollingInterval).Should(BeTrue()) + Byf("Setting Cluster as unpaused") setClusterPausedField(false) @@ -117,6 +139,14 @@ var _ = Describe("Feature", Serial, func() { Byf("Verifying ClusterSummary %s status is set to Deployed for Resources feature", clusterSummary.Name) verifyFeatureStatusIsProvisioned(kindWorkloadCluster.GetNamespace(), clusterSummary.Name, libsveltosv1beta1.FeatureResources) + Byf("Verifying ClusterSummary %s does not report pending features anymore", clusterSummary.Name) + Eventually(func() bool { + currentClusterSummary := &configv1beta1.ClusterSummary{} + err = k8sClient.Get(context.TODO(), + types.NamespacedName{Namespace: clusterSummary.Namespace, Name: clusterSummary.Name}, currentClusterSummary) + return err == nil && len(currentClusterSummary.Status.PendingFeatures) == 0 + }, timeout, pollingInterval).Should(BeTrue()) + Byf("Changing clusterprofile to not reference configmap anymore") Expect(k8sClient.Get(context.TODO(), types.NamespacedName{Name: clusterProfile.Name}, currentClusterProfile)).To(Succeed()) currentClusterProfile.Spec.PolicyRefs = []configv1beta1.PolicyRef{}