8000 fix(chi): recreate Services only for immutable type or headless changes (#2165 follow-up) by alex-zaitsev · Pull Request #2185 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
60 changes: 56 additions & 4 deletions pkg/controller/chi/worker-service.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package chi

import (
"context"
"errors"
"fmt"

core "k8s.io/api/core/v1"
Expand All @@ -27,6 +28,17 @@ import (
"github.com/altinity/clickhouse-operator/pkg/util"
)

// Service type changes and ClusterIP <-> headless transitions cannot be updated in place.
// Only these changes (or a missing Service) justify deletion and recreation.
var (
errServiceTypeChanged = errors.New("service type changed")
errServiceHeadlessChanged = errors.New("service headless mode changed")
)

func shouldRecreateService(err error) bool {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Other immutable fields used to be fixed by the old delete+create fallback, for example switching ipFamilies / ipFamilyPolicy to a different primary family. Those now return Invalid on every reconcile and the Service never converges. If that's intended, could we at least say so in the error/event? Something like "immutable field changed, delete the Service manually".

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Thanks, agreed that Invalid can also arise from immutable fields such as the primary IP family. I kept the conservative behavior (do not delete a working Service on an ambiguous Invalid), and added an actionable failure event/log that says to validate the desired spec and manually delete/reconcile the Service for an intentional immutable-field transition. I also added a regression test for primary ipFamilies changes. See 3254455 and 6363391. I would prefer to handle automatic replacement only for specifically recognized transitions, not reintroduce IsInvalid as a blanket delete condition.

return apiErrors.IsNotFound(err) || errors.Is(err, errServiceTypeChanged) || errors.Is(err, errServiceHeadlessChanged)
}

// reconcileService reconciles core.Service
func (w *worker) reconcileService(ctx context.Context, cr chi.ICustomResource, service, prevService *core.Service) error {
w.a.V(2).M(cr).S().Info(service.GetName())
Expand All @@ -39,6 +51,40 @@ func (w *worker) reconcileService(ctx context.Context, cr chi.ICustomResource, s
// We have the Service - try to update it
w.a.V(1).M(cr).F().Info("Service found: %s. Will try to update", util.NamespaceNameString(service))
err = w.updateService(ctx, cr, curService, service, prevService)
if apiErrors.IsConflict(err) {
// A concurrent Service update may have changed resourceVersion. Re-read the
// live object and retry once. Do not delete it if the retry also conflicts.
latestService, getErr := w.c.getService(ctx, service)
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nit: the retry has no tests for the re-Get returning NotFound or a changed type. Worth one case each?

switch {
case getErr != nil:
err = getErr
case latestService != nil:
err = w.updateService(ctx, cr, latestService, service, prevService)
}
}
}

// Recreate is for the situations a recreate actually fixes, see shouldRecreateService. Any other
// error - a read that was Forbidden or spent its retry budget, an update that hit a Conflict or
// an admission webhook that is down - says nothing about whether the Service is healthy, so
// surface it rather than deleting the Service. Falling through would delete and create it,
// dropping its endpoints and its address, which for a LoadBalancer is the external one.
if (err != nil) && !shouldRecreateService(err) {
message := "Reconcile Service: %s failed, leaving it alone. err: %v"
if apiErrors.IsInvalid(err) {
// Invalid may mean a bad desired spec OR an immutable field change.
// Never delete a working Service on that ambiguous response. Explain
// how an intentional immutable change can be applied explicitly.
message = "Reconcile Service: %s update rejected as Invalid; preserving the existing Service. " +
"Check the desired spec. If an immutable field must change, delete the Service manually " +
"and trigger reconciliation after correcting the spec. err: %v"
}
w.a.WithEvent(cr, a.EventActionReconcile, a.EventReasonReconcileFailed).
WithAction(cr).
WithError(cr).
M(cr).F().
Error(message, util.NamespaceNameString(service), err)
return err
}

if err != nil {
Expand Down Expand Up @@ -79,10 +125,16 @@ func (w *worker) updateService(
prevService *core.Service,
) error {
if curService.Spec.Type != targetService.Spec.Type {
return fmt.Errorf(
"just recreate the service in case of service type change '%s'=>'%s'",
curService.Spec.Type, targetService.Spec.Type,
)
// A Service type change must be handled by deleting and recreating it.
return fmt.Errorf("%w: '%s'=>'%s'",
errServiceTypeChanged, curService.Spec.Type, targetService.Spec.Type)
}
// ClusterIP is immutable: switching between a headless Service ("None") and a
// normal Service (an assigned IP) needs recreation. An empty desired ClusterIP
// for an existing normal Service is not a transition: it means reuse its IP.
if (curService.Spec.ClusterIP == core.ClusterIPNone) != (targetService.Spec.ClusterIP == core.ClusterIPNone) {
return fmt.Errorf("%w: ClusterIP '%s'=>'%s'",
errServiceHeadlessChanged, curService.Spec.ClusterIP, targetService.Spec.ClusterIP)
}

// Updating a Service is a complicated business
Expand Down
250 changes: 250 additions & 0 deletions pkg/controller/chi/worker-service_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
// Copyright 2019 Altinity Ltd and/or its affiliates. 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 chi
import (
"context"
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/require"
core "k8s.io/api/core/v1"
apiErrors "k8s.io/apimachinery/pkg/api/errors"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/validation/field"

api "github.com/altinity/clickhouse-operator/pkg/apis/clickhouse.altinity.com/v1"
a "github.com/altinity/clickhouse-operator/pkg/controller/common/announcer"
"github.com/altinity/clickhouse-operator/pkg/interfaces"
)

type reconcileServiceFake struct {
interfaces.IKubeService
current *core.Service
updateErr error
updateErrors []error
retryGetErr error
getCalls int
updates int
deletes int
creates int
updated *core.Service
}

func (f *reconcileServiceFake) Get(context.Context, ...any) (*core.Service, error) {
f.getCalls++
if f.getCalls > 1 && f.retryGetErr != nil {
return nil, f.retryGetErr
}
service := f.current.DeepCopy()
if f.getCalls > 1 {
// A conflict means another actor changed the resourceVersion.
service.ResourceVersion = "2"
}
return service, nil
}

func (f *reconcileServiceFake) Update(_ context.Context, service *core.Service) (*core.Service, error) {
f.updates++
f.updated = service.DeepCopy()
if f.updates <= len(f.updateErrors) {
return service, f.updateErrors[f.updates-1]
}
return service, f.updateErr
}

func (f *reconcileServiceFake) Delete(context.Context, string, string) error {
f.deletes++
return nil
}

func (f *reconcileServiceFake) Create(_ context.Context, service *core.Service) (*core.Service, error) {
f.creates++
return service, nil
}

type reconcileServiceKube struct {
interfaces.IKube
service interfaces.IKubeService
}

func (k *reconcileServiceKube) Service() interfaces.IKubeService { return k.service }

func serviceForReconcile(serviceType core.ServiceType, clusterIP string) *core.Service {
return &core.Service{
ObjectMeta: meta.ObjectMeta{Namespace: "ns", Name: "svc", ResourceVersion: "1"},
Spec: core.ServiceSpec{
Type: serviceType,
ClusterIP: clusterIP,
Ports: []core.ServicePort{{Port: 9000}},
},
}
}

func reconcileUsingServiceFake(client *reconcileServiceFake, desired *core.Service) error {
w := &worker{
c: &Controller{kube: &reconcileServiceKube{service: client}},
a: a.NewAnnouncer(nil, nil),
}
cr := &api.ClickHouseInstallation{ObjectMeta: meta.ObjectMeta{Namespace: "ns", Name: "chi"}}
return w.reconcileService(context.Background(), cr, desired, nil)
}

func reconcileWithServiceFake(current, desired *core.Service, updateErr error) (error, *reconcileServiceFake) {
client := &reconcileServiceFake{current: current, updateErr: updateErr}
return reconcileUsingServiceFake(client, desired), client
}

func TestShouldRecreateServiceOnlyForExplicitTransitions(t *testing.T) {
resource := schema.GroupResource{Resource: "services"}
invalid := apiErrors.NewInvalid(schema.GroupKind{Kind: "Service"}, "svc", field.ErrorList{
field.Invalid(field.NewPath("spec", "ports").Index(0).Child("port"), 0, "must be positive"),
})
cases := []struct {
name string
err error
recreate bool
}{
{"not found", apiErrors.NewNotFound(resource, "svc"), true},
{"type changed", fmt.Errorf("wrapped: %w", errServiceTypeChanged), true},
{"headless changed", fmt.Errorf("wrapped: %w", errServiceHeadlessChanged), true},
{"invalid desired service", invalid, false},
{"conflict", apiErrors.NewConflict(resource, "svc", errors.New("conflict")), false},
{"forbidden", apiErrors.NewForbidden(resource, "svc", errors.New("forbidden")), false},
{"transient error", errors.New("connection interrupted"), false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.recreate, shouldRecreateService(tc.err))
})
}
}

func TestReconcileServicePreservesWorkingServiceOnInvalidUpdate(t *testing.T) {
current := serviceForReconcile(core.ServiceTypeLoadBalancer, "10.0.0.25")
desired := current.DeepCopy()
desired.Spec.Ports[0].Port = 0
invalid := apiErrors.NewInvalid(schema.GroupKind{Kind: "Service"}, "svc", field.ErrorList{
field.Invalid(field.NewPath("spec", "ports").Index(0).Child("port"), 0, "must be positive"),
})

err, fake := reconcileWithServiceFake(current, desired, invalid)
require.True(t, apiErrors.IsInvalid(err), "invalid specification must be surfaced")
require.Equal(t, 1, fake.updates, "an in-place update should have been attempted")
require.Zero(t, fake.deletes, "invalid desired state must not delete the live LoadBalancer")
require.Zero(t, fake.creates, "invalid desired state must not replace the live LoadBalancer")
}

func TestReconcileServiceRecreatesOnlyOnHeadlessModeChange(t *testing.T) {
cases := []struct {
name string
currentIP string
desiredIP string
recreate bool
}{
{"ClusterIP to headless", "10.0.0.25", core.ClusterIPNone, true},
{"headless to ClusterIP", core.ClusterIPNone, "", true},
{"assigned ClusterIP to unspecified ClusterIP", "10.0.0.25", "", false},
{"headless to headless", core.ClusterIPNone, core.ClusterIPNone, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
current := serviceForReconcile(core.ServiceTypeClusterIP, tc.currentIP)
desired := serviceForReconcile(core.ServiceTypeClusterIP, tc.desiredIP)
err, fake := reconcileWithServiceFake(current, desired, nil)
require.NoError(t, err)
if tc.recreate {
require.Zero(t, fake.updates, "Kubernetes cannot update headless mode in place")
require.Equal(t, 1, fake.deletes)
require.Equal(t, 1, fake.creates)
} else {
require.Equal(t, 1, fake.updates)
require.Zero(t, fake.deletes)
require.Zero(t, fake.creates)
require.Equal(t, tc.currentIP, fake.updated.Spec.ClusterIP,
"an ordinary update must preserve the existing ClusterIP")
}
})
}
}

func TestReconcileServiceStillRecreatesOnTypeChange(t *testing.T) {
current := serviceForReconcile(core.ServiceTypeClusterIP, "10.0.0.25")
desired := serviceForReconcile(core.ServiceTypeNodePort, "")
err, fake := reconcileWithServiceFake(current, desired, nil)
require.NoError(t, err)
require.Zero(t, fake.updates)
require.Equal(t, 1, fake.deletes)
require.Equal(t, 1, fake.creates)
}

func TestReconcileServiceRetriesOnceOnConflict(t *testing.T) {
resource := schema.GroupResource{Resource: "services"}
conflict := apiErrors.NewConflict(resource, "svc", errors.New("object has been modified"))
current := serviceForReconcile(core.ServiceTypeClusterIP, "10.0.0.25")
desired := current.DeepCopy()

t.Run("retry gets latest resourceVersion and succeeds", func(t *testing.T) {
fake := &reconcileServiceFake{current: current, updateErrors: []error{conflict, nil}}
err := reconcileUsingServiceFake(fake, desired)
require.NoError(t, err)
require.Equal(t, 2, fake.getCalls)
require.Equal(t, 2, fake.updates)
require.Equal(t, "2", fake.updated.ResourceVersion)
require.Zero(t, fake.deletes)
require.Zero(t, fake.creates)
})

t.Run("second conflict is returned without deleting service", func(t *testing.T) {
fake := &reconcileServiceFake{current: current, updateErr: conflict}
err := reconcileUsingServiceFake(fake, desired)
require.True(t, apiErrors.IsConflict(err))
require.Equal(t, 2, fake.getCalls)
require.Equal(t, 2, fake.updates, "retry must be bounded")
require.Zero(t, fake.deletes)
require.Zero(t, fake.creates)
})

t.Run("failed refresh is returned without deleting service", func(t *testing.T) {
forbidden := apiErrors.NewForbidden(resource, "svc", errors.New("permission revoked"))
fake := &reconcileServiceFake{current: current, updateErr: conflict, retryGetErr: forbidden}
err := reconcileUsingServiceFake(fake, desired)
require.True(t, apiErrors.IsForbidden(err))
require.Equal(t, 2, fake.getCalls)
require.Equal(t, 1, fake.updates)
require.Zero(t, fake.deletes)
require.Zero(t, fake.creates)
})
}

func TestReconcileServiceReportsImmutableIPFamilyChangeAsInvalid(t *testing.T) {
// An explicit primary IP family change can require recreation. It should not
// be treated as proof that deleting the live Service will make the desired
// spec valid: invalid ports and other bad specs yield the same API error.
current := serviceForReconcile(core.ServiceTypeClusterIP, "10.0.0.25")
current.Spec.IPFamilies = []core.IPFamily{core.IPv4Protocol}
desired := current.DeepCopy()
desired.Spec.IPFamilies = []core.IPFamily{core.IPv6Protocol}
invalid := apiErrors.NewInvalid(schema.GroupKind{Kind: "Service"}, "svc", field.ErrorList{
field.Invalid(field.NewPath("spec", "ipFamilies"), desired.Spec.IPFamilies, "primary family is immutable"),
})
err, fake := reconcileWithServiceFake(current, desired, invalid)
require.True(t, apiErrors.IsInvalid(err))
require.Equal(t, 1, fake.updates)
require.Zero(t, fake.deletes, "the operator must not destroy a live Service on ambiguous Invalid errors")
require.Zero(t, fake.creates)
}
0