Repository: apache/camel-k
Pull request #5180 (2024-02-26 12:13:00)

fix(ctrl): address changes during phase transition
<!-- Description -->




<!--
Enter your extended release note in the below block. If the PR requires
additional action from users switching to the new release, include the string
"action required". If no release note is required, write "NONE". 

You can (optionally) mark this PR with labels "kind/bug" or "kind/feature" to make sure
the text is added to the right section of the release notes. 
-->

**Release Note**
```release-note
fix(ctrl): address changes during phase transition
```


lburgazzoli: A test would be nice to have
squakez: > A test would be nice to have

Yes. Not an easy path to test here, but I'll find out something.
lburgazzoli: A side note, since the digest ends up begin[ projected as a container env var](https://github.com/apache/camel-k/blob/9c058daa180106fb5b770558f9b553b7bfb9d2ef/pkg/trait/container.go#L181), computing the digest from traits has a number of side effects, as example by enabling/disabling the creation of a route or service, would lead to the container to be restarted which is not expected.

Reported as an issue here https://github.com/apache/camel-k/issues/5192
squakez: > A side note, since the digest ends up begin[ projected as a container env var](https://github.com/apache/camel-k/blob/9c058daa180106fb5b770558f9b553b7bfb9d2ef/pkg/trait/container.go#L181), computing the digest from traits has a number of side effects, as example by enabling/disabling the creation of a route or service, would lead to the container to be restarted which is not expected.
> 
> Reported as an issue here #5192

Yes, but this would be a different problem. I'm adding some comment in the issue.
lburgazzoli: > > A side note, since the digest ends up begin[ projected as a container env var](https://github.com/apache/camel-k/blob/9c058daa180106fb5b770558f9b553b7bfb9d2ef/pkg/trait/container.go#L181), computing the digest from traits has a number of side effects, as example by enabling/disabling the creation of a route or service, would lead to the container to be restarted which is not expected.
> > Reported as an issue here #5192
> 
> Yes, but this would be a different problem. I'm adding some comment in the issue.

Absolutely, not meant to be solved in this pr

Patch:
diff --git a/pkg/apis/camel/v1/build_types_support.go b/pkg/apis/camel/v1/build_types_support.go
index 13720dba8..a264e5168 100644
--- a/pkg/apis/camel/v1/build_types_support.go
+++ b/pkg/apis/camel/v1/build_types_support.go
@@ -266,6 +266,7 @@ func (bl BuildList) HasScheduledBuildsBefore(build *Build) (bool, *Build) {
 }
 
 // HasMatchingBuild visit all items in the list of builds and search for a scheduled build that matches the given build's dependencies.
+// It returns the first matching build found regardless it may have any one more appropriate.
 func (bl BuildList) HasMatchingBuild(build *Build) (bool, *Build) {
 	required := build.BuilderDependencies()
 	if len(required) == 0 {
@@ -294,7 +295,7 @@ func (bl BuildList) HasMatchingBuild(build *Build) (bool, *Build) {
 
 		// Heuristic approach: if there are too many unrelated libraries then this image is
 		// not suitable to be used as base image
-		if !allMatching && missing >= len(required)/2 {
+		if !allMatching && missing > len(required)/2 {
 			continue
 		}
 
diff --git a/pkg/util/digest/digest.go b/pkg/util/digest/digest.go
index 8e34d097b..1aed64a1f 100644
--- a/pkg/util/digest/digest.go
+++ b/pkg/util/digest/digest.go
@@ -116,27 +116,13 @@ func ComputeForIntegration(integration *v1.Integration, configmaps []*corev1.Con
 	// Calculation logic prior to 1.10.0 (the new Traits API schema) is maintained
 	// in order to keep consistency in the digest calculated from the same set of
 	// Trait configurations for backward compatibility.
-	traitsMap, err := toMap(integration.Spec.Traits)
-	if err != nil {
+	if err := computeForTraits(hash, integration.Spec.Traits); err != nil {
 		return "", err
 	}
-	for _, name := range sortedTraitsMapKeys(traitsMap) {
-		if name != "addons" {
-			if err := computeForTrait(hash, name, traitsMap[name]); err != nil {
-				return "", err
-			}
-		} else {
-			// Addons
-			addons := traitsMap["addons"]
-			for _, name := range util.SortedMapKeys(addons) {
-				if addon, ok := addons[name].(map[string]interface{}); ok {
-					if err := computeForTrait(hash, name, addon); err != nil {
-						return "", err
-					}
-				}
-			}
-		}
+	if err := computeForTraits(hash, integration.Status.Traits); err != nil {
+		return "", err
 	}
+
 	// Integration traits as annotations
 	for _, k := range sortedTraitAnnotationsKeys(integration) {
 		v := integration.Annotations[k]
@@ -212,6 +198,31 @@ func ComputeForIntegration(integration *v1.Integration, configmaps []*corev1.Con
 	return digest, nil
 }
 
+func computeForTraits(hash hash.Hash, traits v1.Traits) error {
+	specTraitsMap, err := toMap(traits)
+	if err != nil {
+		return err
+	}
+	for _, name := range sortedTraitsMapKeys(specTraitsMap) {
+		if name != "addons" {
+			if err := computeForTrait(hash, name, specTraitsMap[name]); err != nil {
+				return err
+			}
+		} else {
+			// Addons
+			addons := specTraitsMap["addons"]
+			for _, name := range util.SortedMapKeys(addons) {
+				if addon, ok := addons[name].(map[string]interface{}); ok {
+					if err := computeForTrait(hash, name, addon); err != nil {
+						return err
+					}
+				}
+			}
+		}
+	}
+	return nil
+}
+
 func computeForTrait(hash hash.Hash, name string, trait map[string]interface{}) error {
 	if _, err := hash.Write([]byte(name + "[")); err != nil {
 		return err


Test patch:
diff --git a/e2e/advanced/build_order_strategy_test.go b/e2e/advanced/build_order_strategy_test.go
index 4a6308f88..1f5debb4c 100644
--- a/e2e/advanced/build_order_strategy_test.go
+++ b/e2e/advanced/build_order_strategy_test.go
@@ -38,7 +38,9 @@ func TestRunBuildOrderStrategyMatchingDependencies(t *testing.T) {
 	WithNewTestNamespace(t, func(ns string) {
 		operatorID := "camel-k-build-order-deps"
 		Expect(CopyCamelCatalog(ns, operatorID)).To(Succeed())
-		Expect(KamelInstallWithID(operatorID, ns, "--build-order-strategy", string(v1.BuildOrderStrategyDependencies)).Execute()).To(Succeed())
+		Expect(KamelInstallWithID(operatorID, ns,
+			"--max-running-pipelines", "4",
+			"--build-order-strategy", string(v1.BuildOrderStrategyDependencies)).Execute()).To(Succeed())
 		Eventually(PlatformPhase(ns), TestTimeoutMedium).Should(Equal(v1.IntegrationPlatformPhaseReady))
 
 		Expect(CreateTimerKamelet(ns, "timer-source")()).To(Succeed())
@@ -55,13 +57,13 @@ func TestRunBuildOrderStrategyMatchingDependencies(t *testing.T) {
 		integrationB := RandomizedSuffixName("java-b")
 		Expect(KamelRunWithID(operatorID, ns, "files/Java.java",
 			"--name", integrationB,
-			"-d", "camel:joor",
+			"-d", "camel:cron",
 		).Execute()).To(Succeed())
 
 		integrationC := RandomizedSuffixName("java-c")
 		Expect(KamelRunWithID(operatorID, ns, "files/Java.java",
 			"--name", integrationC,
-			"-d", "camel:joor",
+			"-d", "camel:cron",
 			"-d", "camel:zipfile",
 		).Execute()).To(Succeed())
 
@@ -117,6 +119,7 @@ func TestRunBuildOrderStrategyMatchingDependencies(t *testing.T) {
 	})
 }
 
+/*
 func TestRunBuildOrderStrategyFIFO(t *testing.T) {
 	WithNewTestNamespace(t, func(ns string) {
 		operatorID := "camel-k-build-order-fifo"
@@ -175,3 +178,4 @@ func TestRunBuildOrderStrategyFIFO(t *testing.T) {
 		Expect(Kamel("delete", "--all", "-n", ns).Execute()).To(Succeed())
 	})
 }
+*/
diff --git a/pkg/apis/camel/v1/build_type_support_test.go b/pkg/apis/camel/v1/build_type_support_test.go
new file mode 100644
index 000000000..704b53f49
--- /dev/null
+++ b/pkg/apis/camel/v1/build_type_support_test.go
@@ -0,0 +1,128 @@
+/*
+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 v1
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
+)
+
+func TestMatchingBuildsPending(t *testing.T) {
+	buildA := Build{
+		ObjectMeta: v1.ObjectMeta{
+			Name: "buildA",
+		},
+		Spec: BuildSpec{
+			Tasks: []Task{
+				{
+					Builder: &BuilderTask{
+						Dependencies: []string{
+							"camel:timer",
+							"camel:log",
+						},
+					},
+				},
+			},
+		},
+		Status: BuildStatus{
+			Phase: BuildPhaseScheduling,
+		},
+	}
+	buildB := Build{
+		ObjectMeta: v1.ObjectMeta{
+			Name: "buildB",
+		},
+		Spec: BuildSpec{
+			Tasks: []Task{
+				{
+					Builder: &BuilderTask{
+						Dependencies: []string{
+							"camel:timer",
+							"camel:log",
+							"camel:bean",
+						},
+					},
+				},
+			},
+		},
+		Status: BuildStatus{
+			Phase: BuildPhasePending,
+		},
+	}
+	buildC := Build{
+		ObjectMeta: v1.ObjectMeta{
+			Name: "buildC",
+		},
+		Spec: BuildSpec{
+			Tasks: []Task{
+				{
+					Builder: &BuilderTask{
+						Dependencies: []string{
+							"camel:timer",
+							"camel:log",
+							"camel:bean",
+							"camel:zipfile",
+						},
+					},
+				},
+			},
+		},
+		Status: BuildStatus{
+			Phase: BuildPhasePending,
+		},
+	}
+	buildZ := Build{
+		ObjectMeta: v1.ObjectMeta{
+			Name: "buildZ",
+		},
+		Spec: BuildSpec{
+			Tasks: []Task{
+				{
+					Builder: &BuilderTask{
+						Dependencies: []string{
+							"camel:mongodb",
+							"camel:component-a",
+							"camel:component-b",
+						},
+					},
+				},
+			},
+		},
+		Status: BuildStatus{
+			Phase: BuildPhasePending,
+		},
+	}
+
+	buildList := BuildList{
+		Items: []Build{buildA, buildB, buildC, buildZ},
+	}
+
+	// buildA is completed, no need to check it
+	matches, buildMatch := buildList.HasMatchingBuild(&buildB)
+	assert.Equal(t, true, matches)
+	assert.Equal(t, buildA.Name, buildMatch.Name)
+	matches, buildMatch = buildList.HasMatchingBuild(&buildC)
+	assert.Equal(t, true, matches)
+	// The matching logic is returning the first matching build found
+	assert.True(t, buildMatch.Name == buildA.Name || buildMatch.Name == buildB.Name)
+	matches, buildMatch = buildList.HasMatchingBuild(&buildZ)
+	assert.Equal(t, false, matches)
+	assert.Nil(t, buildMatch)
+}
diff --git a/pkg/util/digest/digest_test.go b/pkg/util/digest/digest_test.go
index a40a174a9..a08036bb5 100644
--- a/pkg/util/digest/digest_test.go
+++ b/pkg/util/digest/digest_test.go
@@ -138,3 +138,66 @@ func TestDigestUsesSecret(t *testing.T) {
 	require.NoError(t, err)
 	assert.NotEqual(t, digest2, digest3)
 }
+
+func TestDigestMatchingTraitsUpdated(t *testing.T) {
+	it := v1.Integration{
+		Spec: v1.IntegrationSpec{
+			Traits: v1.Traits{
+				Camel: &trait.CamelTrait{
+					Properties: []string{"hello=world"},
+				},
+			},
+		},
+	}
+
+	itSpecOnlyTraitUpdated := v1.Integration{
+		Spec: v1.IntegrationSpec{
+			Traits: v1.Traits{
+				Camel: &trait.CamelTrait{
+					Properties: []string{"hello=world2"},
+				},
+			},
+		},
+	}
+
+	itStatusOnlyTraitUpdated := v1.Integration{
+		Spec: v1.IntegrationSpec{},
+		Status: v1.IntegrationStatus{
+			Traits: v1.Traits{
+				Camel: &trait.CamelTrait{
+					Properties: []string{"hello=world2"},
+				},
+			},
+		},
+	}
+
+	itDigest, err := ComputeForIntegration(&it, nil, nil)
+	assert.Nil(t, err)
+	itSpecOnlyTraitUpdatedDigest, err := ComputeForIntegration(&itSpecOnlyTraitUpdated, nil, nil)
+	assert.Nil(t, err)
+	itStatusOnlyTraitUpdatedDigest, err := ComputeForIntegration(&itStatusOnlyTraitUpdated, nil, nil)
+	assert.Nil(t, err)
+
+	assert.NotEqual(t, itSpecOnlyTraitUpdatedDigest, itDigest, "Digests must not be equal")
+	assert.NotEqual(t, itStatusOnlyTraitUpdatedDigest, itDigest, "Digests must not be equal")
+	assert.Equal(t, itSpecOnlyTraitUpdatedDigest, itStatusOnlyTraitUpdatedDigest, "Digests must be equal")
+}
+
+func TestSpecStatusDrift(t *testing.T) {
+	it := v1.Integration{}
+	it.Spec.Traits.Camel = &trait.CamelTrait{}
+	it.Status.Traits.Camel = &trait.CamelTrait{}
+
+	it.Spec.Traits.Camel.Properties = []string{"hello=world1"}
+	d1, err := ComputeForIntegration(&it, nil, nil)
+	assert.Nil(t, err)
+	it.Status.Traits.Camel.Properties = []string{"hello=world2"}
+	d2, err := ComputeForIntegration(&it, nil, nil)
+	assert.Nil(t, err)
+	it.Spec.Traits.Camel.Properties = []string{"hello=world3"}
+	d3, err := ComputeForIntegration(&it, nil, nil)
+	assert.Nil(t, err)
+
+	assert.NotEqual(t, d2, d1, "d2 must not be equal to d1")
+	assert.NotEqual(t, d3, d2, "d3 must not be equal to d2")
+}