This is an automated email from the ASF dual-hosted git repository.
squakez pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-k.git
The following commit(s) were added to refs/heads/main by this push:
new 90722abf8 Rollback resources when Integration deployment fails (#6997)
90722abf8 is described below
commit 90722abf85ed0d6614f4ed581a157d366fa284ff
Author: Sanjeev Kumar <[email protected]>
AuthorDate: Thu Dec 3 05:39:52 2026 -0500
Rollback resources when Integration deployment fails (#6997)
* fix: rollback resources when deployment fails
* fix: address deployment rollback review feedback
* Test rollback continues after individual resource errors
* Fix lint naming in deployer rollback
* Improve deployer rollback E2E coverage
* Fix rollback E2E Service port expectation
---
e2e/common/traits/deployer_test.go | 125 ++++++++++++++++++++
pkg/trait/deployer.go | 131 ++++++++++++++++++++-
pkg/trait/deployer_rollback_test.go | 223 ++++++++++++++++++++++++++++++++++++
pkg/trait/trait.go | 59 ++++++++--
4 files changed, 525 insertions(+), 13 deletions(-)
diff --git a/e2e/common/traits/deployer_test.go
b/e2e/common/traits/deployer_test.go
new file mode 100644
index 000000000..aa0b08677
--- /dev/null
+++ b/e2e/common/traits/deployer_test.go
@@ -0,0 +1,125 @@
+//go:build integration
+// +build integration
+
+// To enable compilation of this file in Goland, go to "Settings -> Go ->
Vendoring & Build Tags -> Custom Tags" and add "integration"
+
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You 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 common
+
+import (
+ "context"
+ "testing"
+
+ . "github.com/onsi/gomega"
+
+ corev1 "k8s.io/api/core/v1"
+
+ . "github.com/apache/camel-k/v2/e2e/support"
+ v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1"
+)
+
+func TestDeployerRollsBackFailedIntegrationUpgrade(t *testing.T) {
+ t.Parallel()
+
+ WithNewTestNamespace(t, func(ctx context.Context, g *WithT, ns string) {
+ name := RandomizedSuffixName("rollback")
+
+ // Start with a working generation and a valid Service so both
resources
+ // can be checked after the failed upgrade.
+ g.Expect(KamelRun(t, ctx, ns, "files/Java.java", "--name", name,
+ "-t", "container.ports=hello;8085",
+ "-t", "service.ports=hello;85;8085",
+ ).Execute()).To(Succeed())
+ g.Eventually(IntegrationConditionStatus(t, ctx, ns, name,
v1.IntegrationConditionReady), TestTimeoutMedium).
+ Should(Equal(corev1.ConditionTrue))
+ g.Eventually(IntegrationPodPhase(t, ctx, ns, name)).
+ Should(Equal(corev1.PodRunning))
+
+ var previousGeneration string
+ g.Eventually(func() string {
+ deployment := Deployment(t, ctx, ns, name)()
+ if deployment == nil {
+ return ""
+ }
+
+ previousGeneration =
deployment.Labels[v1.IntegrationGenerationLabel]
+
+ return previousGeneration
+ }, TestTimeoutMedium).ShouldNot(BeEmpty())
+
+ var previousServicePorts []corev1.ServicePort
+ g.Eventually(func() int32 {
+ service := Service(t, ctx, ns, name)()
+ if service == nil || len(service.Spec.Ports) == 0 {
+ return 0
+ }
+
+ previousServicePorts =
append([]corev1.ServicePort(nil), service.Spec.Ports...)
+
+ return service.Spec.Ports[0].Port
+ }, TestTimeoutMedium).Should(Equal(int32(85)))
+ // The container trait also adds its managed HTTP Service port.
+ g.Expect(previousServicePorts).To(HaveLen(2))
+
+ // This Service port is rejected by the API server after the
Deployment
+ // has been updated, so rollback must restore both previous
resources.
+ g.Expect(KamelRun(t, ctx, ns, "files/Java.java", "--name", name,
+ "-t", "container.ports=hello;8085",
+ "-t", "service.ports=hello;70000;8085",
+ ).Execute()).To(Succeed())
+
+ g.Eventually(IntegrationPhase(t, ctx, ns, name),
TestTimeoutMedium).
+ Should(Equal(v1.IntegrationPhaseError))
+ g.Eventually(IntegrationConditionStatus(t, ctx, ns, name,
v1.IntegrationConditionReady), TestTimeoutMedium).
+ Should(Equal(corev1.ConditionFalse))
+ g.Eventually(func() string {
+ condition := IntegrationCondition(t, ctx, ns, name,
v1.IntegrationConditionReady)()
+ if condition == nil {
+ return ""
+ }
+
+ return condition.Message
+ }, TestTimeoutMedium).Should(ContainSubstring("previous
generation has been preserved"))
+
+ g.Eventually(func() string {
+ deployment := Deployment(t, ctx, ns, name)()
+ if deployment == nil {
+ return ""
+ }
+
+ return deployment.Labels[v1.IntegrationGenerationLabel]
+ }, TestTimeoutMedium).Should(Equal(previousGeneration))
+
+ g.Eventually(func() []corev1.ServicePort {
+ service := Service(t, ctx, ns, name)()
+ if service == nil {
+ return nil
+ }
+
+ return service.Spec.Ports
+ }, TestTimeoutMedium).Should(Equal(previousServicePorts))
+
+ // Restoring the Deployment recreates its pod; wait until the
previous
+ // generation is serving again before considering the rollback
complete.
+ g.Eventually(IntegrationPodPhase(t, ctx, ns, name),
TestTimeoutMedium).
+ Should(Equal(corev1.PodRunning))
+ g.Eventually(IntegrationLogs(t, ctx, ns, name)).
+ Should(ContainSubstring("Magicstring!"))
+ })
+}
diff --git a/pkg/trait/deployer.go b/pkg/trait/deployer.go
index 0b50f98aa..7a923acae 100644
--- a/pkg/trait/deployer.go
+++ b/pkg/trait/deployer.go
@@ -18,7 +18,14 @@ limitations under the License.
package trait
import (
+ "errors"
+ "fmt"
+ "slices"
+
traitv1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1/trait"
+ k8serrors "k8s.io/apimachinery/pkg/api/errors"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ ctrl "sigs.k8s.io/controller-runtime/pkg/client"
)
const (
@@ -46,12 +53,52 @@ func (t *deployerTrait) Configure(e *Environment) (bool,
*TraitCondition, error)
}
func (t *deployerTrait) Apply(e *Environment) error {
- // Register a post action that patches the resources generated by the
traits
e.PostActions = append(e.PostActions, func(env *Environment) error {
applier := e.Client.ServerOrClientSideApplier()
+ snapshots := make([]resourceSnapshot, 0, env.Resources.Size())
+
for _, resource := range env.Resources.Items() {
+ previous, err := deepCopyResource(resource)
+ if err != nil {
+ operationErr := fmt.Errorf(
+ "unable to snapshot resource %s/%s: %w",
+ resource.GetNamespace(),
resource.GetName(), err,
+ )
+ rollbackErr := rollbackResources(e, snapshots)
+
+ return fatalDeploymentError(operationErr,
rollbackErr)
+ }
+
+ err = e.Client.Get(e.Ctx,
ctrl.ObjectKeyFromObject(resource), previous)
+
+ switch {
+ case k8serrors.IsNotFound(err):
+ previous = nil
+ case err != nil:
+ operationErr := fmt.Errorf(
+ "unable to snapshot resource %s/%s: %w",
+ resource.GetNamespace(),
resource.GetName(), err,
+ )
+ rollbackErr := rollbackResources(e, snapshots)
+
+ return fatalDeploymentError(operationErr,
rollbackErr)
+ }
+
+ // Save the original state before applying because an
apply can fail
+ // after the API server has already persisted the
requested changes.
+ snapshots = append(snapshots, resourceSnapshot{
+ resource: resource,
+ previous: previous,
+ })
+
if err := applier.Apply(e.Ctx, resource); err != nil {
- return err
+ operationErr := fmt.Errorf(
+ "unable to apply resource %s/%s: %w",
+ resource.GetNamespace(),
resource.GetName(), err,
+ )
+ rollbackErr := rollbackResources(e, snapshots)
+
+ return fatalDeploymentError(operationErr,
rollbackErr)
}
}
@@ -61,6 +108,86 @@ func (t *deployerTrait) Apply(e *Environment) error {
return nil
}
+// resourceSnapshot records a generated resource and its state immediately
+// before its apply attempt. It is appended before Apply so rollback also
covers
+// an apply that returns an error after persisting changes. A nil previous
value
+// means the resource did not exist before the attempt and should be deleted.
+type resourceSnapshot struct {
+ resource ctrl.Object
+ previous ctrl.Object
+}
+
+func deepCopyResource(resource ctrl.Object) (ctrl.Object, error) {
+ resourceCopy, ok := resource.DeepCopyObject().(ctrl.Object)
+ if !ok {
+ return nil, fmt.Errorf("cannot copy %T as a Kubernetes client
object", resource)
+ }
+
+ return resourceCopy, nil
+}
+
+// rollbackResources restores the resources touched by a failed deployment.
+// It works in reverse order and makes a best-effort attempt for every
resource.
+func rollbackResources(e *Environment, snapshots []resourceSnapshot) error {
+ var rollbackErrors []error
+
+ for _, snapshot := range slices.Backward(snapshots) {
+ current, err := deepCopyResource(snapshot.resource)
+ if err != nil {
+ rollbackErrors = append(rollbackErrors, fmt.Errorf(
+ "unable to copy resource %s/%s during rollback:
%w",
+ snapshot.resource.GetNamespace(),
snapshot.resource.GetName(), err,
+ ))
+ } else if err := e.Client.Delete(e.Ctx, current); err != nil &&
!k8serrors.IsNotFound(err) {
+ rollbackErrors = append(rollbackErrors, fmt.Errorf(
+ "unable to delete resource %s/%s during
rollback: %w",
+ snapshot.resource.GetNamespace(),
snapshot.resource.GetName(), err,
+ ))
+ }
+
+ if snapshot.previous != nil {
+ previous, err := deepCopyResource(snapshot.previous)
+ if err != nil {
+ rollbackErrors = append(rollbackErrors,
fmt.Errorf(
+ "unable to copy previous resource %s/%s
during rollback: %w",
+ snapshot.previous.GetNamespace(),
snapshot.previous.GetName(), err,
+ ))
+ } else {
+ previous.SetResourceVersion("")
+ previous.SetUID("")
+ previous.SetGeneration(0)
+ previous.SetCreationTimestamp(metav1.Time{})
+ previous.SetDeletionTimestamp(nil)
+ previous.SetDeletionGracePeriodSeconds(nil)
+ previous.SetManagedFields(nil)
+
+ if err := e.Client.Create(e.Ctx, previous); err
!= nil {
+ rollbackErrors = append(rollbackErrors,
fmt.Errorf(
+ "unable to recreate previous
resource %s/%s during rollback: %w",
+ previous.GetNamespace(),
previous.GetName(), err,
+ ))
+ }
+ }
+ }
+ }
+
+ return errors.Join(rollbackErrors...)
+}
+
+func fatalDeploymentError(operationErr, rollbackErr error) error {
+ if rollbackErr != nil {
+ return newFatalPostActionError(fmt.Errorf(
+ "integration upgrade did not go through; rollback was
incomplete: %w",
+ errors.Join(operationErr, rollbackErr),
+ ))
+ }
+
+ return newFatalPostActionError(fmt.Errorf(
+ "integration upgrade did not go through; previous generation
has been preserved: %w",
+ operationErr,
+ ))
+}
+
func (t *deployerTrait) SelectControllerStrategy(e *Environment)
(*ControllerStrategy, error) {
//nolint:staticcheck
if t.Kind != "" {
diff --git a/pkg/trait/deployer_rollback_test.go
b/pkg/trait/deployer_rollback_test.go
new file mode 100644
index 000000000..1f8eabf5d
--- /dev/null
+++ b/pkg/trait/deployer_rollback_test.go
@@ -0,0 +1,223 @@
+/*
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You 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 trait
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ v1 "github.com/apache/camel-k/v2/pkg/apis/camel/v1"
+ "github.com/apache/camel-k/v2/pkg/internal"
+ "github.com/apache/camel-k/v2/pkg/util/kubernetes"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ appsv1 "k8s.io/api/apps/v1"
+ corev1 "k8s.io/api/core/v1"
+ apierrors "k8s.io/apimachinery/pkg/api/errors"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+ ctrl "sigs.k8s.io/controller-runtime/pkg/client"
+ "sigs.k8s.io/controller-runtime/pkg/client/interceptor"
+)
+
+func TestDeployerRollsBackResourcesWhenApplyFailsAfterPersistence(t
*testing.T) {
+ deployer, environment := createNominalDeployerTest()
+ environment.Ctx = context.Background()
+ environment.Integration.Namespace = "namespace"
+ environment.Integration.Generation = 2
+
+ previousDeployment := getIntegrationDeployment(environment.Integration)
+
previousDeployment.SetGroupVersionKind(appsv1.SchemeGroupVersion.WithKind("Deployment"))
+ previousDeployment.Labels[v1.IntegrationGenerationLabel] = "1"
+ previousDeployment.Spec.Template.Spec.Containers[0].Image = "old-image"
+
+ desiredDeployment := previousDeployment.DeepCopy()
+ desiredDeployment.Labels[v1.IntegrationGenerationLabel] = "2"
+ desiredDeployment.Spec.Template.Spec.Containers[0].Image = "new-image"
+
+ newConfigMap := &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{
+ Name: "new-config",
+ Namespace: "namespace",
+ },
+ Data: map[string]string{"config": "new"},
+ }
+
newConfigMap.SetGroupVersionKind(corev1.SchemeGroupVersion.WithKind("ConfigMap"))
+
+ apiClient, err := internal.NewFakeClient(previousDeployment)
+ require.NoError(t, err)
+
+ environment.Client = apiClient
+ environment.Resources = kubernetes.NewCollection(newConfigMap,
desiredDeployment)
+
+ injectedFailure := false
+ apiClient.(*internal.FakeClient).Intercept(&interceptor.Funcs{
+ Update: func(
+ ctx context.Context,
+ next ctrl.WithWatch,
+ obj ctrl.Object,
+ opts ...ctrl.UpdateOption,
+ ) error {
+ if obj.GetName() == desiredDeployment.Name &&
!injectedFailure {
+ injectedFailure = true
+
+ if err := next.Update(ctx, obj, opts...); err
!= nil {
+ return err
+ }
+
+ return errors.New("injected failure after
persistence")
+ }
+
+ return next.Update(ctx, obj, opts...)
+ },
+ })
+
+ require.NoError(t, deployer.Apply(environment))
+
+ gcTrait, ok := newGCTrait().(*gcTrait)
+ require.True(t, ok)
+ require.NoError(t, gcTrait.Apply(environment))
+ require.Len(t, environment.PostActions, 2)
+
+ // Execute deployment followed by the actual GC post-action.
+ // A fatal deployment failure must prevent GC from deleting generation
1.
+ err = executePostActions(environment)
+
+ require.Error(t, err)
+ require.Truef(t, injectedFailure, "deployer error: %v", err)
+ assert.Contains(t, err.Error(), "previous generation has been
preserved")
+
+ var fatalErr *fatalPostActionError
+ require.ErrorAs(t, err, &fatalErr)
+
+ actualDeployment := getIntegrationDeployment(environment.Integration)
+ require.NoError(t, apiClient.Get(
+ environment.Ctx,
+ ctrl.ObjectKeyFromObject(previousDeployment),
+ actualDeployment,
+ ))
+ assert.Equal(t, "old-image",
actualDeployment.Spec.Template.Spec.Containers[0].Image)
+ assert.Equal(t, "1",
actualDeployment.Labels[v1.IntegrationGenerationLabel])
+
+ actualConfigMap := &corev1.ConfigMap{}
+ err = apiClient.Get(
+ environment.Ctx,
+ ctrl.ObjectKeyFromObject(newConfigMap),
+ actualConfigMap,
+ )
+ require.True(t, apierrors.IsNotFound(err))
+}
+
+func TestFatalPostActionStopsSubsequentActions(t *testing.T) {
+ environment := &Environment{}
+ garbageCollectionCalled := false
+
+ environment.PostActions = []func(*Environment) error{
+ func(*Environment) error {
+ return newFatalPostActionError(errors.New("deployment
failed"))
+ },
+ func(*Environment) error {
+ garbageCollectionCalled = true
+ return nil
+ },
+ }
+
+ err := executePostActions(environment)
+
+ require.Error(t, err)
+ assert.False(t, garbageCollectionCalled)
+}
+
+func TestNonFatalPostActionErrorDoesNotStopSubsequentActions(t *testing.T) {
+ environment := &Environment{}
+ subsequentActionCalled := false
+
+ environment.PostActions = []func(*Environment) error{
+ func(*Environment) error {
+ return errors.New("non-fatal post-action failure")
+ },
+ func(*Environment) error {
+ subsequentActionCalled = true
+ return nil
+ },
+ }
+
+ err := executePostActions(environment)
+
+ require.Error(t, err)
+ assert.True(t, subsequentActionCalled)
+}
+
+
+func TestRollbackResourcesContinuesAfterDeleteFailure(t *testing.T) {
+ ctx := context.Background()
+ namespace := "namespace"
+
+ previousFirst := &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{Name: "first", Namespace:
namespace},
+ Data: map[string]string{"version": "old"},
+ }
+ currentFirst := previousFirst.DeepCopy()
+ currentFirst.Data["version"] = "new"
+
+ previousSecond := &corev1.ConfigMap{
+ ObjectMeta: metav1.ObjectMeta{Name: "second", Namespace:
namespace},
+ Data: map[string]string{"version": "old"},
+ }
+ currentSecond := previousSecond.DeepCopy()
+ currentSecond.Data["version"] = "new"
+
+ apiClient, err := internal.NewFakeClient(currentFirst, currentSecond)
+ require.NoError(t, err)
+
+ injectedDeleteError := errors.New("injected rollback delete failure")
+ apiClient.(*internal.FakeClient).Intercept(&interceptor.Funcs{
+ Delete: func(
+ ctx context.Context,
+ next ctrl.WithWatch,
+ obj ctrl.Object,
+ opts ...ctrl.DeleteOption,
+ ) error {
+ if obj.GetName() == "second" {
+ return injectedDeleteError
+ }
+
+ return next.Delete(ctx, obj, opts...)
+ },
+ })
+
+ environment := &Environment{
+ Ctx: ctx,
+ Client: apiClient,
+ }
+ err = rollbackResources(environment, []resourceSnapshot{
+ {resource: currentFirst, previous: previousFirst},
+ {resource: currentSecond, previous: previousSecond},
+ })
+
+ require.Error(t, err)
+ assert.ErrorIs(t, err, injectedDeleteError)
+ assert.Contains(t, err.Error(), "already exists")
+
+ // The second resource could not be restored, but rollback must still
+ // continue and restore the first resource.
+ actualFirst := &corev1.ConfigMap{}
+ require.NoError(t, apiClient.Get(ctx,
ctrl.ObjectKeyFromObject(previousFirst), actualFirst))
+ assert.Equal(t, "old", actualFirst.Data["version"])
+}
diff --git a/pkg/trait/trait.go b/pkg/trait/trait.go
index 1f39477c9..23f613d4d 100644
--- a/pkg/trait/trait.go
+++ b/pkg/trait/trait.go
@@ -34,6 +34,23 @@ import (
ctrl "sigs.k8s.io/controller-runtime/pkg/client"
)
+// fatalPostActionError marks a post-action failure that must stop subsequent
actions.
+type fatalPostActionError struct {
+ err error
+}
+
+func newFatalPostActionError(err error) error {
+ return &fatalPostActionError{err: err}
+}
+
+func (e *fatalPostActionError) Error() string {
+ return e.err.Error()
+}
+
+func (e *fatalPostActionError) Unwrap() error {
+ return e.err
+}
+
func Apply(ctx context.Context, c client.Client, integration *v1.Integration,
kit *v1.IntegrationKit) (*Environment, error) {
var ilog log.Logger
switch {
@@ -79,17 +96,8 @@ func Apply(ctx context.Context, c client.Client, integration
*v1.Integration, ki
}
}
- postActionErrors := make([]error, 0)
- // execute post actions registered by traits
- for _, postAction := range environment.PostActions {
- err := postAction(environment)
- if err != nil {
- postActionErrors = append(postActionErrors, err)
- }
- }
-
- if len(postActionErrors) > 0 {
- return nil, fmt.Errorf("error executing post actions - %d/%d
failed: %s", len(postActionErrors), len(environment.PostActions),
postActionErrors)
+ if err := executePostActions(environment); err != nil {
+ return nil, err
}
switch {
@@ -104,6 +112,35 @@ func Apply(ctx context.Context, c client.Client,
integration *v1.Integration, ki
return environment, nil
}
+// executePostActions runs registered post actions. Fatal failures stop
subsequent actions.
+func executePostActions(environment *Environment) error {
+ postActionErrors := make([]error, 0)
+ executedPostActions := 0
+
+ for _, postAction := range environment.PostActions {
+ executedPostActions++
+
+ if err := postAction(environment); err != nil {
+ postActionErrors = append(postActionErrors, err)
+
+ if _, ok := errors.AsType[*fatalPostActionError](err);
ok {
+ break
+ }
+ }
+ }
+
+ if len(postActionErrors) > 0 {
+ return fmt.Errorf(
+ "error executing post actions - %d/%d failed: %w",
+ len(postActionErrors),
+ executedPostActions,
+ errors.Join(postActionErrors...),
+ )
+ }
+
+ return nil
+}
+
// newEnvironment creates a Environment from the given data.
func newEnvironment(ctx context.Context, c client.Client, integration
*v1.Integration, kit *v1.IntegrationKit) (*Environment, error) {
if integration == nil && kit == nil {