Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add new .status.observedSHA256 #164 #165

Merged
merged 1 commit into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions api/v1beta1/keycloakrealm_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,9 @@ type KeycloakRealmStatus struct {
// ObservedGeneration is the last generation reconciled by the controller
ObservedGeneration int64 `json:"observedGeneration,omitempty"`

// ObservedSHA256 is a SHA256 hash over the realm and all sub resources
ObservedSHA256 string `json:"observedSHA256,omitempty"`

// LastExececutionOutput failed requests
// +optional
LastExececutionOutput string `json:"lastExececutionOutput,omitempty"`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9179,6 +9179,10 @@ spec:
by the controller
format: int64
type: integer
observedSHA256:
description: ObservedSHA256 is a SHA256 hash over the realm and all
sub resources
type: string
reconciler:
description: Reconciler is the reconciler pod while a reconciliation
is in progress
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9179,6 +9179,10 @@ spec:
by the controller
format: int64
type: integer
observedSHA256:
description: ObservedSHA256 is a SHA256 hash over the realm and all
sub resources
type: string
reconciler:
description: Reconciler is the reconciler pod while a reconciliation
is in progress
Expand Down
15 changes: 14 additions & 1 deletion internal/controllers/keycloakrealm_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package controllers

import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -251,6 +252,10 @@ func (r *KeycloakRealmReconciler) podReconcile(ctx context.Context, realm infrav
return realm, ctrl.Result{}, err
}

checksumSha := sha256.New()
checksumSha.Write([]byte(raw))
checksum := fmt.Sprintf("%x", checksumSha.Sum(nil))

pod := &corev1.Pod{}
secret := &corev1.Secret{}

Expand All @@ -271,6 +276,11 @@ func (r *KeycloakRealmReconciler) podReconcile(ctx context.Context, realm infrav
needUpdate = specVersion != fmt.Sprintf("%d", realm.Generation)
}

specChecksum, ok := pod.Annotations["keycloak-controller/realm-checksum"]
if !needUpdate && podErr == nil && ok {
needUpdate = specChecksum != checksum
}

if !ok {
needUpdate = true
}
Expand Down Expand Up @@ -356,7 +366,7 @@ func (r *KeycloakRealmReconciler) podReconcile(ctx context.Context, realm infrav
}

ready := conditions.Get(&realm, infrav1beta1.ConditionReady)
if ready != nil && ready.Status == metav1.ConditionTrue && (realm.Spec.Interval == nil || time.Since(ready.LastTransitionTime.Time) < realm.Spec.Interval.Duration) && realm.Generation == ready.ObservedGeneration {
if ready != nil && ready.Status == metav1.ConditionTrue && (realm.Spec.Interval == nil || time.Since(ready.LastTransitionTime.Time) < realm.Spec.Interval.Duration) && checksum == realm.Status.ObservedSHA256 && realm.Generation == ready.ObservedGeneration {
logger.V(1).Info("skip reconcilation, last transition time too recent")
return realm, ctrl.Result{}, nil
}
Expand Down Expand Up @@ -404,7 +414,10 @@ func (r *KeycloakRealmReconciler) podReconcile(ctx context.Context, realm infrav
if template.Annotations == nil {
template.Annotations = make(map[string]string)
}

realm.Status.ObservedSHA256 = checksum
template.Annotations["keycloak-controller/realm-spec-version"] = fmt.Sprintf("%d", realm.Generation)
template.Annotations["keycloak-controller/realm-checksum"] = checksum

usernameField := "username"
passwordField := "password"
Expand Down
133 changes: 133 additions & 0 deletions internal/controllers/keycloakrealm_controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ var _ = Describe("KeycloakRealm controller", func() {
Expect(pod.Spec.Containers[0].Image).Should(Equal("test:latest-22.0.1"))
Expect(pod.Spec.Containers[0].Env).Should(Equal(envs))
Expect(reconciledInstance.Status.SubResourceCatalog).Should(HaveLen(0))
Expect(reconciledInstance.Status.ObservedSHA256).Should(HaveLen(64))

By("validating the realm secret")
secret := corev1.Secret{}
Expand Down Expand Up @@ -1555,4 +1556,136 @@ var _ = Describe("KeycloakRealm controller", func() {
}, timeout, interval).Should(BeTrue())
})
})

When("a realm with an interval > 0 is triggered if a user is changed", func() {
realmName := fmt.Sprintf("realm-%s", rand.String(5))
userName := fmt.Sprintf("user-%s", rand.String(5))

It("recreates the reconciler with a new secret", func() {
By("creating a new KeycloakRealm")
ctx := context.Background()

authSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: fmt.Sprintf("auth-%s", rand.String(5)),
Namespace: "default",
},
StringData: map[string]string{
"username": "kc-user",
"password": "kc-password",
},
}

Expect(k8sClient.Create(ctx, authSecret)).Should(Succeed())

user := &v1beta1.KeycloakUser{
ObjectMeta: metav1.ObjectMeta{
Name: userName,
Namespace: "default",
Labels: map[string]string{
"trigger-checksum-users": "yes",
},
},
Spec: v1beta1.KeycloakUserSpec{},
}
Expect(k8sClient.Create(ctx, user)).Should(Succeed())

realm := &v1beta1.KeycloakRealm{
ObjectMeta: metav1.ObjectMeta{
Name: realmName,
Namespace: "default",
},
Spec: v1beta1.KeycloakRealmSpec{
Interval: &metav1.Duration{Duration: time.Second * 100},
Version: "22.0.1",
AuthSecret: v1beta1.SecretReference{
Name: authSecret.Name,
},
ResourceSelector: &metav1.LabelSelector{
MatchLabels: map[string]string{
"trigger-checksum-users": "yes",
},
},
},
}
Expect(k8sClient.Create(ctx, realm)).Should(Succeed())

By("waiting for the reconciliation")
instanceLookupKey := types.NamespacedName{Name: realmName, Namespace: "default"}
reconciledInstance := &v1beta1.KeycloakRealm{}

expectedStatus := &v1beta1.KeycloakRealmStatus{
ObservedGeneration: 1,
Conditions: []metav1.Condition{
{
Type: v1beta1.ConditionReady,
Status: metav1.ConditionUnknown,
Reason: "Progressing",
Message: "Reconciliation in progress",
},
{
Type: v1beta1.ConditionReconciling,
Status: metav1.ConditionTrue,
Reason: "Progressing",
},
},
}

Eventually(func() bool {
err := k8sClient.Get(ctx, instanceLookupKey, reconciledInstance)
if err != nil {
return false
}

return needStatus(reconciledInstance, expectedStatus)
}, timeout, interval).Should(BeTrue())

By("validating the realm secret")
secret := corev1.Secret{}
Eventually(func() error {
return k8sClient.Get(ctx, types.NamespacedName{
Name: reconciledInstance.Status.Reconciler,
Namespace: reconciledInstance.Namespace,
}, &secret)
}, timeout, interval).Should(BeNil())

Expect(string(secret.Data["realm.json"])).Should(Equal(fmt.Sprintf(`{"realm":"%s","users":[{"username":"%s"}],"components":null,"requiredActions":null}`, realm.Name, userName)))

beforeUpdateStatus := reconciledInstance.Status

user.Spec.User.Enabled = true
Expect(k8sClient.Update(ctx, user)).Should(Succeed())

Eventually(func() bool {
err := k8sClient.Get(ctx, instanceLookupKey, reconciledInstance)
if err != nil {
return false
}

return needStatus(reconciledInstance, expectedStatus) && reconciledInstance.Status.Reconciler != beforeUpdateStatus.Reconciler
}, timeout, interval).Should(BeTrue())

By("making sure the resource catalog is correct")
catalog := []v1beta1.ResourceReference{
{
Kind: "KeycloakUser",
Name: userName,
APIVersion: v1beta1.GroupVersion.String(),
},
}

Expect(reconciledInstance.Status.SubResourceCatalog).Should(Equal(catalog))

By("validating the realm secret")
secret = corev1.Secret{}
Eventually(func() error {
return k8sClient.Get(ctx, types.NamespacedName{
Name: reconciledInstance.Status.Reconciler,
Namespace: reconciledInstance.Namespace,
}, &secret)
}, timeout, interval).Should(BeNil())

Expect(string(secret.Data["realm.json"])).Should(Equal(fmt.Sprintf(`{"realm":"%s","users":[{"username":"%s","enabled":true}],"components":null,"requiredActions":null}`, realm.Name, userName)))
})
})
})
Loading