From aa95a2316b08e95cac1e24f340bb35355433aeb3 Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 1 Dec 2026 21:34:24 -0500 Subject: [PATCH 1/2] fix(router): Stop VIP binding status writes conflicting with health On a node whose ServiceVIPBindings use a FailClosed health check, the servicevipbinding controller logged a reconcile error every few minutes, enough to keep the reconcile error-floor alert firing. Each error was a conflict on the binding's status write. Retries succeeded, so traffic was unaffected. The backend health checker in the same router patches status.health after every FailClosed probe, because lastProbeTime changes each time. reconcileBind then wrote the whole status with a resourceVersion-checked Update from its cached copy, on every reconcile, whether or not anything changed. Any health patch that landed between the read and the write made it fail. Each health patch also re-ran the binding and, through the peer watch, every other binding on the node, so a node with a few bindings reconciled several times a second. reconcileBind now writes status only when it changes, as a merge patch of the fields it owns. The patch has no resourceVersion, so it cannot conflict with the health patch, and the health checker's own patch never touches the Bound condition. These are the only two writers of this status. A retry on conflict would hide the race and keep the redundant write, so it was not used. The For watch and the peer watch now drop updates that change only the status. Updates still pass when the generation, labels, annotations, finalizers or deletion timestamp change, and resyncs pass so the periodic datapath re-check still runs. Peer conflict resolution reads only spec and deletion state, so peers lose nothing. The backend health guide claimed one health patch per transition. It now says FailClosed patches once per probe interval, documents lastProbeTime and states the Bound write contract. Fixes #1380 --- docs/gateway/backend-health.md | 10 +- .../servicevipbinding_controller.go | 46 ++++- .../servicevipbinding_status_test.go | 191 ++++++++++++++++++ 3 files changed, 240 insertions(+), 7 deletions(-) create mode 100644 internal/controller/servicevipbinding_status_test.go diff --git a/docs/gateway/backend-health.md b/docs/gateway/backend-health.md index 215aa3ece..a26665091 100644 --- a/docs/gateway/backend-health.md +++ b/docs/gateway/backend-health.md @@ -102,13 +102,21 @@ only by `galactic-router` on the backend's node: | `attachmentUID` | The `VPCAttachment` incarnation the decision is about | | `port` | The port that was probed | | `lastTransitionTime` | When `state` last changed | +| `lastProbeTime` | When the last probe finished; set only for `FailClosed` services | A backend has one binding per VIP family it serves, and each carries the same decision. A gateway reads a family's decision from that family's binding. The router writes `status.health` only when the decision changes, with a merge patch of that field alone, so it never rewrites the `Bound` condition the same -process sets. The write volume is one patch per binding per transition. +process sets. For a `FailClosed` service, `lastProbeTime` also changes after +every probe, so the write volume is one patch per binding per probe interval; +otherwise it is one patch per binding per transition. + +The `Bound` condition is written the same way: only when it changes, with a +merge patch of the fields the binding reconciler owns. Neither write carries a +`resourceVersion`, so the two never conflict, and an update that changes only +the status does not trigger another reconcile of the binding or its peers. ### Identity diff --git a/internal/controller/servicevipbinding_controller.go b/internal/controller/servicevipbinding_controller.go index 283492c58..a210ccc56 100644 --- a/internal/controller/servicevipbinding_controller.go +++ b/internal/controller/servicevipbinding_controller.go @@ -14,6 +14,7 @@ import ( "strings" "time" + "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" @@ -187,9 +188,15 @@ func (r *ServiceVIPBindingReconciler) Reconcile(ctx context.Context, req ctrl.Re } // reconcileBind applies binding's desired bind and translation state and records -// the outcome on the Bound condition. The status update happens whether or not -// the bind succeeded, and the error is returned afterward so controller-runtime +// the outcome on the Bound condition. The status is written whether or not the +// bind succeeded, and the error is returned afterward so controller-runtime // requeues. +// +// The status is written only when it changes, as a merge patch without a +// resourceVersion. BackendHealthReconciler patches status.health on every +// fail-closed probe, so an optimistic-lock update from the cached copy would +// keep failing with a conflict. The patch carries only the fields this +// reconciler owns, so it never overwrites status.health. func (r *ServiceVIPBindingReconciler) reconcileBind(ctx context.Context, binding *bgpv1alpha1.ServiceVIPBinding) error { bindErr := r.applyBind(ctx, binding) @@ -216,8 +223,10 @@ func (r *ServiceVIPBindingReconciler) reconcileBind(ctx context.Context, binding } setBindingCondition(bindingCopy, cond) bindingCopy.Status.ObservedGeneration = binding.Generation - if err := r.Status().Update(ctx, bindingCopy); err != nil { - return fmt.Errorf("update ServiceVIPBinding %s/%s status: %w", binding.Namespace, binding.Name, err) + if !equality.Semantic.DeepEqual(binding.Status, bindingCopy.Status) { + if err := r.Status().Patch(ctx, bindingCopy, client.MergeFrom(binding)); err != nil { + return fmt.Errorf("patch ServiceVIPBinding %s/%s status: %w", binding.Namespace, binding.Name, err) + } } if bindErr != nil { @@ -945,16 +954,41 @@ func vrfInstanceTargetsRouter(vrf *bgpv1alpha1.BGPVRFInstance, router *bgpv1alph func (r *ServiceVIPBindingReconciler) SetupWithManager(mgr ctrl.Manager) error { r.APIReader = mgr.GetAPIReader() return ctrl.NewControllerManagedBy(mgr). - For(&bgpv1alpha1.ServiceVIPBinding{}). + For(&bgpv1alpha1.ServiceVIPBinding{}, builder.WithPredicates(bindingChangePredicate())). Watches(&bgpv1alpha1.NetworkService{}, handler.EnqueueRequestsFromMapFunc(r.bindingAuthorityRequests)). Watches(&bgpv1alpha1.NetworkServiceAddress{}, handler.EnqueueRequestsFromMapFunc(r.bindingAuthorityRequests)). - Watches(&bgpv1alpha1.ServiceVIPBinding{}, handler.EnqueueRequestsFromMapFunc(r.nodePeerRequests)). + Watches(&bgpv1alpha1.ServiceVIPBinding{}, handler.EnqueueRequestsFromMapFunc(r.nodePeerRequests), + builder.WithPredicates(bindingChangePredicate())). Watches(&bgpv1alpha1.BGPAdvertisement{}, handler.EnqueueRequestsFromMapFunc(r.advertisementRequests), builder.WithPredicates(bindingAdvertisementPredicate())). Named("servicevipbinding"). Complete(r) } +// bindingChangePredicate drops ServiceVIPBinding updates that change only the +// status. The reconciler and its peers read only the spec and metadata, and +// BackendHealthReconciler patches status.health on every fail-closed probe, so +// passing those updates would re-run this binding and every peer on the node +// once per probe. An update passes when the generation, labels, annotations, +// finalizers or deletion timestamp change, and a resync, which repeats the same +// resourceVersion, passes so the periodic re-check of the datapath still runs. +func bindingChangePredicate() predicate.Predicate { + return predicate.Funcs{ + UpdateFunc: func(e event.UpdateEvent) bool { + if e.ObjectOld == nil || e.ObjectNew == nil { + return true + } + oldObj, newObj := e.ObjectOld, e.ObjectNew + return oldObj.GetResourceVersion() == newObj.GetResourceVersion() || + oldObj.GetGeneration() != newObj.GetGeneration() || + !reflect.DeepEqual(oldObj.GetLabels(), newObj.GetLabels()) || + !reflect.DeepEqual(oldObj.GetAnnotations(), newObj.GetAnnotations()) || + !reflect.DeepEqual(oldObj.GetFinalizers(), newObj.GetFinalizers()) || + !oldObj.GetDeletionTimestamp().Equal(newObj.GetDeletionTimestamp()) + }, + } +} + // bindingAdvertisementPredicate passes BGPAdvertisement events that can change // whether a binding's backend address is advertised: a create or delete of one // buildBackendSIDIndex keeps, or a spec change where either side is kept. diff --git a/internal/controller/servicevipbinding_status_test.go b/internal/controller/servicevipbinding_status_test.go new file mode 100644 index 000000000..a8a9e75ed --- /dev/null +++ b/internal/controller/servicevipbinding_status_test.go @@ -0,0 +1,191 @@ +// Copyright 2026 Datum Cloud, Inc. +// +// SPDX-License-Identifier: AGPL-3.0-or-later + +package controller + +import ( + "context" + "net" + "testing" + "time" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" + "sigs.k8s.io/controller-runtime/pkg/event" + + bgpv1alpha1 "go.datum.net/galactic/api/network/v1alpha1" + "go.datum.net/galactic/internal/healthprobe" +) + +// statusWriteCounter counts status subresource writes and, when beforeWrite is +// set, runs it once before the first write lands. +type statusWriteCounter struct { + writes int + beforeWrite func(ctx context.Context, c client.Client, obj client.Object) error +} + +func (s *statusWriteCounter) funcs() interceptor.Funcs { + before := func(ctx context.Context, c client.Client, obj client.Object) error { + s.writes++ + if s.beforeWrite == nil { + return nil + } + hook := s.beforeWrite + s.beforeWrite = nil + return hook(ctx, c, obj) + } + return interceptor.Funcs{ + SubResourceUpdate: func(ctx context.Context, c client.Client, sub string, obj client.Object, + opts ...client.SubResourceUpdateOption, + ) error { + if err := before(ctx, c, obj); err != nil { + return err + } + return c.SubResource(sub).Update(ctx, obj, opts...) + }, + SubResourcePatch: func(ctx context.Context, c client.Client, sub string, obj client.Object, + patch client.Patch, opts ...client.SubResourcePatchOption, + ) error { + if err := before(ctx, c, obj); err != nil { + return err + } + return c.SubResource(sub).Patch(ctx, obj, patch, opts...) + }, + } +} + +func newStatusTestReconciler(t *testing.T, counter *statusWriteCounter) (*ServiceVIPBindingReconciler, client.Client) { + t.Helper() + router, adv, vrf := newBackendFixtures(testVPCRef) + fakeClient := fake.NewClientBuilder(). + WithScheme(newRuleTestScheme(t)). + WithStatusSubresource(&bgpv1alpha1.ServiceVIPBinding{}). + WithObjects(router, adv, vrf, newVethTestBinding()). + WithInterceptorFuncs(counter.funcs()). + Build() + stubVIPFns(t, + func(net.IP) error { return nil }, + func(net.IP) error { return nil }, + func(net.IP) error { return nil }, + ) + r := &ServiceVIPBindingReconciler{ + Client: fakeClient, NodeName: testComputeNodeName, VIPTranslationTable: &fakeVIPTable{}, + } + return r, fakeClient +} + +// TestServiceVIPBindingReconciler_StatusSurvivesHealthPatch checks that a +// status.health patch landing between the reconciler's read and its status +// write neither fails the reconcile nor is lost. +func TestServiceVIPBindingReconciler_StatusSurvivesHealthPatch(t *testing.T) { + counter := &statusWriteCounter{} + counter.beforeWrite = func(ctx context.Context, c client.Client, obj client.Object) error { + current := &bgpv1alpha1.ServiceVIPBinding{} + if err := c.Get(ctx, client.ObjectKeyFromObject(obj), current); err != nil { + return err + } + base := current.DeepCopy() + current.Status.Health = &bgpv1alpha1.ServiceVIPBindingHealth{ + State: bgpv1alpha1.BackendHealthHealthy, + Reason: healthprobe.ReasonProbeSucceeded, + } + return c.Status().Patch(ctx, current, client.MergeFrom(base)) + } + r, fakeClient := newStatusTestReconciler(t, counter) + + if _, err := r.Reconcile(context.Background(), ctrl.Request{NamespacedName: bindingKey()}); err != nil { + t.Fatalf("Reconcile: %v", err) + } + + got := &bgpv1alpha1.ServiceVIPBinding{} + if err := fakeClient.Get(context.Background(), bindingKey(), got); err != nil { + t.Fatalf("get: %v", err) + } + if !meta.IsStatusConditionTrue(got.Status.Conditions, bgpv1alpha1.ConditionTypeBound) { + t.Errorf("Bound condition = %+v, want True", got.Status.Conditions) + } + if got.Status.Health == nil || got.Status.Health.Reason != healthprobe.ReasonProbeSucceeded { + t.Errorf("status.health = %+v, want the concurrent health patch kept", got.Status.Health) + } +} + +// TestServiceVIPBindingReconciler_UnchangedStatusNotWritten checks that +// reconciling a binding whose status is already current writes nothing. +func TestServiceVIPBindingReconciler_UnchangedStatusNotWritten(t *testing.T) { + counter := &statusWriteCounter{} + r, _ := newStatusTestReconciler(t, counter) + req := ctrl.Request{NamespacedName: bindingKey()} + + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("first Reconcile: %v", err) + } + if counter.writes != 1 { + t.Fatalf("status writes after first reconcile = %d, want 1", counter.writes) + } + for i := range 2 { + if _, err := r.Reconcile(context.Background(), req); err != nil { + t.Fatalf("Reconcile %d: %v", i+2, err) + } + } + if counter.writes != 1 { + t.Errorf("status writes after 3 reconciles of an unchanged binding = %d, want 1", counter.writes) + } +} + +func TestBindingChangePredicate(t *testing.T) { + base := newVethTestBinding() + base.ResourceVersion = "10" + base.Generation = 1 + base.Labels = map[string]string{"a": "b"} + + now := metav1.NewTime(time.Unix(1700000000, 0)) + tests := []struct { + name string + mutate func(b *bgpv1alpha1.ServiceVIPBinding) + want bool + }{ + {name: "resync", mutate: func(*bgpv1alpha1.ServiceVIPBinding) {}, want: true}, + {name: "status only", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.Status.Health = &bgpv1alpha1.ServiceVIPBindingHealth{LastProbeTime: now} + }, want: false}, + {name: "spec", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.Generation = 2 + }, want: true}, + {name: "labels", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.Labels = map[string]string{"a": "c"} + }, want: true}, + {name: "annotations", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.Annotations = map[string]string{"x": "y"} + }, want: true}, + {name: "finalizers", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.Finalizers = []string{serviceVIPBindingFinalizer} + }, want: true}, + {name: "deletion", mutate: func(b *bgpv1alpha1.ServiceVIPBinding) { + b.ResourceVersion = "11" + b.DeletionTimestamp = &now + }, want: true}, + } + p := bindingChangePredicate() + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + newObj := base.DeepCopy() + tt.mutate(newObj) + if got := p.Update(event.UpdateEvent{ObjectOld: base, ObjectNew: newObj}); got != tt.want { + t.Errorf("Update = %v, want %v", got, tt.want) + } + }) + } + if !p.Create(event.CreateEvent{Object: base}) || !p.Delete(event.DeleteEvent{Object: base}) { + t.Error("create and delete events must pass") + } +} From e5b2a61b42f6319d2b4fd91421f6dbba115890ec Mon Sep 17 00:00:00 2001 From: Peter Sprygada Date: Tue, 1 Dec 2026 21:35:42 -0500 Subject: [PATCH 2/2] docs(router): Note the single writer of VIP binding conditions The Bound status write is a JSON merge patch, which replaces the whole status.conditions list. Say in reconcileBind's comment that this reconciler must stay the only writer of that list, so a second writer added later does not have its conditions silently dropped. Related to #1380 --- internal/controller/servicevipbinding_controller.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/controller/servicevipbinding_controller.go b/internal/controller/servicevipbinding_controller.go index a210ccc56..18001b0d9 100644 --- a/internal/controller/servicevipbinding_controller.go +++ b/internal/controller/servicevipbinding_controller.go @@ -196,7 +196,9 @@ func (r *ServiceVIPBindingReconciler) Reconcile(ctx context.Context, req ctrl.Re // resourceVersion. BackendHealthReconciler patches status.health on every // fail-closed probe, so an optimistic-lock update from the cached copy would // keep failing with a conflict. The patch carries only the fields this -// reconciler owns, so it never overwrites status.health. +// reconciler owns, so it never overwrites status.health. A merge patch +// replaces the whole conditions list, so this reconciler must stay the only +// writer of status.conditions. func (r *ServiceVIPBindingReconciler) reconcileBind(ctx context.Context, binding *bgpv1alpha1.ServiceVIPBinding) error { bindErr := r.applyBind(ctx, binding)