Skip to content
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
105 changes: 105 additions & 0 deletions pkg/controller/controllerring/add_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
Copyright 2025 Tim Ebert.

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 controllerring_test

import (
"time"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
coordinationv1 "k8s.io/api/coordination/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/utils/clock/testing"
"k8s.io/utils/ptr"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"

. "github.com/timebertt/kubernetes-controller-sharding/pkg/controller/controllerring"
)

var _ = Describe("Reconciler", func() {
var r *Reconciler

BeforeEach(func() {
r = &Reconciler{}
})

Describe("#LeasePredicate", func() {
var (
p predicate.Predicate
obj, objOld *coordinationv1.Lease

fakeClock *testing.FakePassiveClock
)

BeforeEach(func() {
fakeClock = testing.NewFakePassiveClock(time.Now())
r.Clock = fakeClock

p = r.LeasePredicate()

obj = &coordinationv1.Lease{
ObjectMeta: metav1.ObjectMeta{
Name: "foo-0",
},
Spec: coordinationv1.LeaseSpec{
HolderIdentity: ptr.To("foo-0"),
LeaseDurationSeconds: ptr.To[int32](10),
AcquireTime: ptr.To(metav1.NewMicroTime(fakeClock.Now().Add(-5 * time.Minute))),
RenewTime: ptr.To(metav1.NewMicroTime(fakeClock.Now().Add(-2 * time.Second))),
},
}
metav1.SetMetaDataLabel(&obj.ObjectMeta, "alpha.sharding.timebertt.dev/controllerring", "foo")
objOld = obj.DeepCopy()
})

It("should ignore leases with empty label", func() {
metav1.SetMetaDataLabel(&obj.ObjectMeta, "alpha.sharding.timebertt.dev/controllerring", "")
objOld = obj.DeepCopy()

Expect(p.Create(event.CreateEvent{Object: obj})).To(BeFalse())
Expect(p.Update(event.UpdateEvent{ObjectOld: objOld, ObjectNew: obj})).To(BeFalse())
Expect(p.Delete(event.DeleteEvent{Object: obj})).To(BeFalse())
})

It("should react on create events", func() {
Expect(p.Create(event.CreateEvent{Object: obj})).To(BeTrue())
})

It("should react on delete events", func() {
Expect(p.Delete(event.DeleteEvent{Object: obj})).To(BeTrue())
})

It("should react when shard state changed to available", func() {
objOld.Spec.HolderIdentity = nil
Expect(p.Update(event.UpdateEvent{ObjectOld: objOld, ObjectNew: obj})).To(BeTrue())
})

It("should react when shard state changed to unavailable", func() {
obj.Spec.HolderIdentity = nil
Expect(p.Update(event.UpdateEvent{ObjectOld: objOld, ObjectNew: obj})).To(BeTrue())
})

It("should ignore when shard state hasn't changed", func() {
Expect(p.Update(event.UpdateEvent{ObjectOld: objOld, ObjectNew: obj})).To(BeFalse())

obj.Spec.HolderIdentity = nil
objOld.Spec.HolderIdentity = nil
Expect(p.Update(event.UpdateEvent{ObjectOld: objOld, ObjectNew: obj})).To(BeFalse())
})
})
})
29 changes: 29 additions & 0 deletions pkg/controller/controllerring/controllerring_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
Copyright 2025 Tim Ebert.

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 controllerring_test

import (
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestControllerRing(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "ControllerRing Controller Suite")
}
26 changes: 19 additions & 7 deletions pkg/controller/controllerring/reconciler.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req reconcile.Request) (reco
}

func (r *Reconciler) updateStatusSuccess(ctx context.Context, controllerRing, before *shardingv1alpha1.ControllerRing) error {
if err := r.optionallyUpdateStatus(ctx, controllerRing, before, func(ready *metav1.Condition) {
if err := r.OptionallyUpdateStatus(ctx, controllerRing, before, func(ready *metav1.Condition) {
ready.Status = metav1.ConditionTrue
ready.Reason = "ReconciliationSucceeded"
ready.Message = "ControllerRing was successfully reconciled"
Expand All @@ -109,7 +109,7 @@ func (r *Reconciler) updateStatusError(ctx context.Context, log logr.Logger, rec

r.Recorder.Event(controllerRing, corev1.EventTypeWarning, "ReconciliationFailed", message)

if err := r.optionallyUpdateStatus(ctx, controllerRing, before, func(ready *metav1.Condition) {
if err := r.OptionallyUpdateStatus(ctx, controllerRing, before, func(ready *metav1.Condition) {
ready.Status = metav1.ConditionFalse
ready.Reason = "ReconciliationFailed"
ready.Message = message
Expand All @@ -122,7 +122,7 @@ func (r *Reconciler) updateStatusError(ctx context.Context, log logr.Logger, rec
return reconcileError
}

func (r *Reconciler) optionallyUpdateStatus(ctx context.Context, controllerRing, before *shardingv1alpha1.ControllerRing, mutate func(ready *metav1.Condition)) error {
func (r *Reconciler) OptionallyUpdateStatus(ctx context.Context, controllerRing, before *shardingv1alpha1.ControllerRing, mutate func(ready *metav1.Condition)) error {
// always update status with the latest observed generation, no matter if reconciliation succeeded or not
controllerRing.Status.ObservedGeneration = controllerRing.Generation
readyCondition := metav1.Condition{
Expand All @@ -141,6 +141,15 @@ func (r *Reconciler) optionallyUpdateStatus(ctx context.Context, controllerRing,
}

func (r *Reconciler) reconcileWebhooks(ctx context.Context, controllerRing *shardingv1alpha1.ControllerRing) error {
webhookConfig, err := r.WebhookConfigForControllerRing(controllerRing)
if err != nil {
return err
}

return r.Client.Patch(ctx, webhookConfig, client.Apply)
}

func (r *Reconciler) WebhookConfigForControllerRing(controllerRing *shardingv1alpha1.ControllerRing) (*admissionregistrationv1.MutatingWebhookConfiguration, error) {
webhookConfig := &admissionregistrationv1.MutatingWebhookConfiguration{
TypeMeta: metav1.TypeMeta{
APIVersion: admissionregistrationv1.SchemeGroupVersion.String(),
Expand All @@ -154,11 +163,16 @@ func (r *Reconciler) reconcileWebhooks(ctx context.Context, controllerRing *shar
},
Annotations: maps.Clone(r.Config.Webhook.Config.Annotations),
},
Webhooks: []admissionregistrationv1.MutatingWebhook{r.WebhookForControllerRing(controllerRing)},
}
if err := controllerutil.SetControllerReference(controllerRing, webhookConfig, r.Client.Scheme()); err != nil {
return fmt.Errorf("error setting controller reference: %w", err)
return nil, fmt.Errorf("error setting controller reference: %w", err)
}

return webhookConfig, nil
}

func (r *Reconciler) WebhookForControllerRing(controllerRing *shardingv1alpha1.ControllerRing) admissionregistrationv1.MutatingWebhook {
webhook := admissionregistrationv1.MutatingWebhook{
Name: "sharder.sharding.timebertt.dev",
ClientConfig: *r.Config.Webhook.Config.ClientConfig.DeepCopy(),
Expand Down Expand Up @@ -207,9 +221,7 @@ func (r *Reconciler) reconcileWebhooks(ctx context.Context, controllerRing *shar
}
}

webhookConfig.Webhooks = []admissionregistrationv1.MutatingWebhook{webhook}

return r.Client.Patch(ctx, webhookConfig, client.Apply)
return webhook
}

// RuleForResource returns the sharder's webhook rule for the given resource.
Expand Down
Loading
Loading