Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions config/crds/v1/all-crds.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10673,6 +10673,9 @@ spec:
- jsonPath: .metadata.creationTimestamp
name: Age
type: date
- jsonPath: .spec.weight
name: Weight
type: integer
name: v1alpha1
schema:
openAPIV3Schema:
Expand Down Expand Up @@ -10932,6 +10935,13 @@ spec:
- secretName
type: object
type: array
weight:
default: 0
description: |-
Weight determines the priority of this policy when multiple policies target the same resource.
Lower weight values take precedence. Defaults to 0.
format: int32
type: integer
type: object
status:
properties:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ spec:
- jsonPath: .metadata.creationTimestamp
name: Age
type: date
- jsonPath: .spec.weight
name: Weight
type: integer
name: v1alpha1
schema:
openAPIV3Schema:
Expand Down Expand Up @@ -288,6 +291,13 @@ spec:
- secretName
type: object
type: array
weight:
default: 0
description: |-
Weight determines the priority of this policy when multiple policies target the same resource.
Lower weight values take precedence. Defaults to 0.
format: int32
type: integer
type: object
status:
properties:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10743,6 +10743,9 @@ spec:
- jsonPath: .metadata.creationTimestamp
name: Age
type: date
- jsonPath: .spec.weight
name: Weight
type: integer
name: v1alpha1
schema:
openAPIV3Schema:
Expand Down Expand Up @@ -11002,6 +11005,13 @@ spec:
- secretName
type: object
type: array
weight:
default: 0
description: |-
Weight determines the priority of this policy when multiple policies target the same resource.
Lower weight values take precedence. Defaults to 0.
format: int32
type: integer
type: object
status:
properties:
Expand Down
1 change: 1 addition & 0 deletions docs/reference/api-reference/main.md
Original file line number Diff line number Diff line change
Expand Up @@ -2068,6 +2068,7 @@ StackConfigPolicy represents a StackConfigPolicy resource in a Kubernetes cluste
| Field | Description |
| --- | --- |
| *`resourceSelector`* __[LabelSelector](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.32/#labelselector-v1-meta)__ | |
| *`weight`* __integer__ | Weight determines the priority of this policy when multiple policies target the same resource.<br>Lower weight values take precedence. Defaults to 0. |
| *`secureSettings`* __[SecretSource](#secretsource) array__ | Deprecated: SecureSettings only applies to Elasticsearch and is deprecated. It must be set per application instead. |
| *`elasticsearch`* __[ElasticsearchConfigPolicySpec](#elasticsearchconfigpolicyspec)__ | |
| *`kibana`* __[KibanaConfigPolicySpec](#kibanaconfigpolicyspec)__ | |
Expand Down
53 changes: 53 additions & 0 deletions pkg/apis/stackconfigpolicy/v1alpha1/stackconfigpolicy_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func init() {
// +kubebuilder:printcolumn:name="Ready",type="string",JSONPath=".status.readyCount",description="Resources configured"
// +kubebuilder:printcolumn:name="Phase",type="string",JSONPath=".status.phase"
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp"
// +kubebuilder:printcolumn:name="Weight",type="integer",JSONPath=".spec.weight"
// +kubebuilder:subresource:status
// +kubebuilder:storageversion
type StackConfigPolicy struct {
Expand All @@ -55,6 +56,10 @@ type StackConfigPolicyList struct {

type StackConfigPolicySpec struct {
ResourceSelector metav1.LabelSelector `json:"resourceSelector,omitempty"`
// Weight determines the priority of this policy when multiple policies target the same resource.
// Lower weight values take precedence. Defaults to 0.
// +kubebuilder:default=0
Weight int32 `json:"weight,omitempty"`
// Deprecated: SecureSettings only applies to Elasticsearch and is deprecated. It must be set per application instead.
SecureSettings []commonv1.SecretSource `json:"secureSettings,omitempty"`
Elasticsearch ElasticsearchConfigPolicySpec `json:"elasticsearch,omitempty"`
Expand Down Expand Up @@ -94,6 +99,54 @@ type ElasticsearchConfigPolicySpec struct {
SecureSettings []commonv1.SecretSource `json:"secureSettings,omitempty"`
}

// GetElasticsearchNamespacedSecureSettings returns the Elasticsearch secure settings from this policy
// as NamespacedSecretSources, with each secret source namespaced to the policy's namespace.
// Returns nil if the policy is nil or has no Elasticsearch secure settings defined.
func (p *StackConfigPolicy) GetElasticsearchNamespacedSecureSettings() []commonv1.NamespacedSecretSource {
if p == nil {
return nil
}

ssLen := len(p.Spec.Elasticsearch.SecureSettings)
if ssLen == 0 {
return nil
}
pNs := p.GetNamespace()
ssNsn := make([]commonv1.NamespacedSecretSource, ssLen)
for idx, ss := range p.Spec.Elasticsearch.SecureSettings {
ssNsn[idx] = commonv1.NamespacedSecretSource{
Namespace: pNs,
SecretName: ss.SecretName,
Entries: ss.Entries,
}
}
return ssNsn
}

// GetKibanaNamespacedSecureSettings returns the Kibana secure settings from this policy
// as NamespacedSecretSources, with each secret source namespaced to the policy's namespace.
// Returns nil if the policy is nil or has no Kibana secure settings defined.
func (p *StackConfigPolicy) GetKibanaNamespacedSecureSettings() []commonv1.NamespacedSecretSource {
if p == nil {
return nil
}

ssLen := len(p.Spec.Kibana.SecureSettings)
if ssLen == 0 {
return nil
}
pNs := p.GetNamespace()
ssNsn := make([]commonv1.NamespacedSecretSource, ssLen)
for idx, ss := range p.Spec.Kibana.SecureSettings {
ssNsn[idx] = commonv1.NamespacedSecretSource{
Namespace: pNs,
SecretName: ss.SecretName,
Entries: ss.Entries,
}
}
return ssNsn
}

type KibanaConfigPolicySpec struct {
// Config holds the settings that go into kibana.yml.
// +kubebuilder:pruning:PreserveUnknownFields
Expand Down
109 changes: 83 additions & 26 deletions pkg/controller/common/reconciler/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ package reconciler

import (
"context"
"encoding/json"
"reflect"
"strings"

corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
Expand All @@ -28,6 +30,7 @@ const (
SoftOwnerNamespaceLabel = "eck.k8s.elastic.co/owner-namespace"
SoftOwnerNameLabel = "eck.k8s.elastic.co/owner-name"
SoftOwnerKindLabel = "eck.k8s.elastic.co/owner-kind"
SoftOwnerRefsAnnotation = "eck.k8s.elastic.co/owner-refs"
)

func WithPostUpdate(f func()) func(p *Params) {
Expand Down Expand Up @@ -92,6 +95,49 @@ func SoftOwnerRefFromLabels(labels map[string]string) (SoftOwnerRef, bool) {
return SoftOwnerRef{Namespace: namespace, Name: name, Kind: kind}, true
}

// SoftOwnerRefs returns the soft owner references of the given object.
func SoftOwnerRefs(obj metav1.Object) ([]SoftOwnerRef, error) {
// Check if this Secret has a soft-owner kind label set
ownerKind, exists := obj.GetLabels()[SoftOwnerKindLabel]
if !exists {
// Not a soft-owned secret
return nil, nil
}

// Check for multi-policy ownership (annotation-based)
if ownerRefsBytes, exists := obj.GetAnnotations()[SoftOwnerRefsAnnotation]; exists {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its a bit awkward that some of the multi-ref functionality is here and some is in ownership.go?

Maybe move all the code here and make it generic?

// In pkg/controller/common/reconciler/secret.go

// SetMultipleSoftOwners adds multiple soft owner references to an object
func SetMultipleSoftOwners(obj metav1.Object, ownerKind string, owners []types.NamespacedName) error

// AddSoftOwner adds a soft owner to an object (handles single->multi transition)
func AddSoftOwner(obj metav1.Object, owner SoftOwnerRef) error

// RemoveSoftOwner removes a soft owner from an object
func RemoveSoftOwner(obj metav1.Object, owner types.NamespacedName) (remainingCount int, err error)

// IsSoftOwnedBy checks if an object is soft-owned by the given owner
func IsSoftOwnedBy(obj metav1.Object, ownerKind string, owner types.NamespacedName) (bool, error)

// SoftOwnerRefs already exists and reads them
func SoftOwnerRefs(obj metav1.Object) ([]SoftOwnerRef, error)

and then call it from the stack config controller, maybe with small wrappers to make the transformation from SCP to NamespacedName where necessary:

func setMultipleSoftOwners(secret *corev1.Secret, policies []policyv1alpha1.StackConfigPolicy) error {
    owners := make([]types.NamespacedName, len(policies))
    for i, p := range policies {
        owners[i] = k8s.ExtractNamespacedName(&p)
    }
    return reconciler.SetMultipleSoftOwners(secret, policyv1alpha1.Kind, owners)
}

// Multi-policy soft owned secret - parse the JSON map of owners
var ownerRefs map[string]struct{}
if err := json.Unmarshal([]byte(ownerRefsBytes), &ownerRefs); err != nil {
return nil, err
}

// Convert the map keys (namespaced name strings) back to NamespacedName objects
var ownerRefsNsn []SoftOwnerRef
for nsnStr := range ownerRefs {
// Split the string format "namespace/name" into components
nsnComponents := strings.Split(nsnStr, string(types.Separator))
if len(nsnComponents) != 2 {
// Skip malformed entries
continue
}
ownerRefsNsn = append(ownerRefsNsn, SoftOwnerRef{Namespace: nsnComponents[0], Name: nsnComponents[1], Kind: ownerKind})
}

return ownerRefsNsn, nil
}

// Fall back to single-policy ownership (label-based)
currentOwner, referenced := SoftOwnerRefFromLabels(obj.GetLabels())
if !referenced {
// No soft owner found in labels
return nil, nil
}

// Return the single owner as a slice with one element
return []SoftOwnerRef{currentOwner}, nil
}

// ReconcileSecretNoOwnerRef should be called to reconcile a Secret for which we explicitly don't want
// an owner reference to be set, and want existing ownerReferences from previous operator versions to be removed,
// because of this k8s bug: https://github.com/kubernetes/kubernetes/issues/65200 (fixed in k8s 1.20).
Expand Down Expand Up @@ -200,43 +246,54 @@ func GarbageCollectAllSoftOwnedOrphanSecrets(ctx context.Context, c k8s.Client,
var secrets corev1.SecretList
if err := c.List(ctx,
&secrets,
client.HasLabels{SoftOwnerNamespaceLabel, SoftOwnerNameLabel, SoftOwnerKindLabel},
client.HasLabels{SoftOwnerKindLabel},
); err != nil {
return err
}
// remove any secret whose owner doesn't exist
for i := range secrets.Items {
secret := secrets.Items[i]
softOwner, referenced := SoftOwnerRefFromLabels(secret.Labels)
if !referenced {
continue
}
if restrictedToOwnerNamespace(softOwner.Kind) && softOwner.Namespace != secret.Namespace {
// Secret references an owner in a different namespace: this likely results
// from a "manual" copy of the secret in another namespace, not handled by the operator.
// We don't want to touch that secret.
continue
softOwners, err := SoftOwnerRefs(&secret)
if err != nil {
return err
}
owner, managed := ownerKinds[softOwner.Kind]
if !managed {
if len(softOwners) == 0 {
continue
}
owner = k8s.DeepCopyObject(owner)
err := c.Get(ctx, types.NamespacedName{Namespace: softOwner.Namespace, Name: softOwner.Name}, owner)
if err != nil {
if apierrors.IsNotFound(err) {
// owner doesn't exit anymore
ulog.FromContext(ctx).Info("Deleting secret as part of garbage collection",
"namespace", secret.Namespace, "secret_name", secret.Name,
"owner_kind", softOwner.Kind, "owner_namespace", softOwner.Namespace, "owner_name", softOwner.Name,
)
options := client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &secret.UID}}
if err := c.Delete(ctx, &secret, &options); err != nil && !apierrors.IsNotFound(err) {
return err
}

missingOwners := make(map[types.NamespacedName]client.Object)
for _, softOwner := range softOwners {
if restrictedToOwnerNamespace(softOwner.Kind) && softOwner.Namespace != secret.Namespace {
// Secret references an owner in a different namespace: this likely results
// from a "manual" copy of the secret in another namespace, not handled by the operator.
// We don't want to touch that secret.
continue
}
return err
owner, managed := ownerKinds[softOwner.Kind]
if !managed {
continue
}
owner = k8s.DeepCopyObject(owner)
err := c.Get(ctx, types.NamespacedName{Namespace: softOwner.Namespace, Name: softOwner.Name}, owner)
if err != nil {
if apierrors.IsNotFound(err) {
// owner doesn't exit anymore
ulog.FromContext(ctx).Info("Deleting secret as part of garbage collection",
"namespace", secret.Namespace, "secret_name", secret.Name,
"owner_kind", softOwner.Kind, "owner_namespace", softOwner.Namespace, "owner_name", softOwner.Name,
)
missingOwners[types.NamespacedName{Namespace: softOwner.Namespace, Name: softOwner.Name}] = owner
continue
}
return err
}
}

if len(missingOwners) == len(softOwners) {
options := client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &secret.UID}}
if err := c.Delete(ctx, &secret, &options); err != nil && !apierrors.IsNotFound(err) {
return err
}
}
// owner still exists, keep the secret
}
Expand Down
Loading