Skip to content
Open
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
74 changes: 74 additions & 0 deletions cmd/crossplane/composition/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,80 @@ Summary: 2 modified`,
WithDownstreamSummary(0, 0, 1).
WithDownstreamResource("removed", "XDownstreamResource", "resource-to-be-removed", "default"),
},
"UnhealthyXRWithChangesExits7": {
Reason: "A composition change on a failing XR prints the XR's health and its not-ready composed resource's in the impact analysis, then the Health: line, and exits 7: changes (3) and failing (4).",
SetupFiles: []string{
"../../../internal/testutils/integration/testdata/comp/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/original-composition.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/functions.yaml",
},
CrossplaneManagedResources: []integration.HierarchicalOwnershipRelation{
integration.Composes(
"../../../internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml",
),
},
InputFiles: []string{"../../../internal/testutils/integration/testdata/comp/updated-composition.yaml"},
Namespace: "default",
NoColor: true,
ExpectedOutput: `
=== Affected Composite Resources ===

⚠ XNopResource/test-resource (namespace: default) ⚠ failing (Synced=False, ReconcileError): cannot compose resources: the vpc does not exist

Summary: 1 resource with changes

=== Impact Analysis ===

~~~ XDownstreamResource/test-resource ⚠ not ready (Ready=False, Creating)
apiVersion: ns.nop.example.org/v1alpha1
kind: XDownstreamResource
metadata:
annotations:
crossplane.io/composition-resource-name: nop-resource
labels:
crossplane.io/composite: test-resource
name: test-resource
namespace: default
spec:
forProvider:
- configData: existing-value
- resourceTier: basic
+ configData: updated-existing-value
+ resourceTier: premium

---

Summary: 1 modified

Health: 1 of 1 XR unhealthy before apply; 1 resource not ready.`,
ExpectedExitCode: dp.ExitCodeDiffDetected | dp.ExitCodeFailing,
},
"UnhealthyXRWithoutChangesExits4": {
Reason: "An unchanged composition analysed on a failing XR reports its health in -o json and exits 4: failing, no changes.",
SetupFiles: []string{
"../../../internal/testutils/integration/testdata/comp/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/original-composition.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/functions.yaml",
},
CrossplaneManagedResources: []integration.HierarchicalOwnershipRelation{
integration.Composes(
"../../../internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml",
"../../../internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml",
),
},
InputFiles: []string{"testdata/comp/composition-no-changes.yaml"},
Namespace: "default",
AnalyzeUnchanged: true,
OutputFormat: "json",
ExpectedExitCode: dp.ExitCodeFailing,
ExpectedStructured: simtest.Expect().
WithHealthSummary(1, 0, 1, 0).
WithXRs(simtest.XR("XNopResource", "test-resource", "default").
Status("unchanged").
Health("failing").
Unhealthy("XDownstreamResource", "test-resource", "notReady")),
},
"CompositionDiffIgnorePaths": {
Reason: "Validates that ArgoCD annotations are ignored in composition diffs",
SetupFiles: []string{
Expand Down
95 changes: 93 additions & 2 deletions cmd/crossplane/project/integration_plan_output_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"testing"

"github.com/google/go-cmp/cmp"
corev1 "k8s.io/api/core/v1"
un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/client"

Expand Down Expand Up @@ -77,6 +78,18 @@ func TestSimulatePlanOutput(t *testing.T) {
// healthy is a live composite's health with no failing condition.
healthy := &health.Health{State: health.Healthy}

// unhealthyCase is compCase with test-resource failing (Synced=False) and
// its composed resource not ready (Ready=False), and the composed resource
// of another-resource paused.
unhealthyCase := compCase
unhealthyCase.CrossplaneManagedResources = []integration.HierarchicalOwnershipRelation{
integration.Composes("../../../internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml", "../../../internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml"),
integration.Composes("../../../internal/testutils/integration/testdata/comp/resources/existing-xr-2.yaml", "../../../internal/testutils/integration/testdata/comp/resources/existing-downstream-2.yaml"),
}
unhealthyCase.FieldManagerApplies = []integration.FieldManagerApply{
{File: "../../../internal/testutils/integration/testdata/comp/resources/existing-downstream-2-paused-annotation.yaml", FieldManager: "kubectl"},
}

xrArgs := []string{"-f", "../../../internal/testutils/integration/testdata/diff/modified-xr.yaml"}
compArgs := []string{"-f", "../../../internal/testutils/integration/testdata/comp/updated-composition.yaml", "--namespace=default"}

Expand All @@ -89,6 +102,11 @@ func TestSimulatePlanOutput(t *testing.T) {
// tt, when set, runs `xr simulate` with args against its cluster
// instead of compCase's.
tt *integration.Setup
// cluster, when set, replaces compCase's cluster for a project or
// composition run.
cluster *integration.Setup
// wantExitCode is the exit code; zero means dp.ExitCodeDiffDetected.
wantExitCode int
// wantText is the -o plan output; empty for a json case.
wantText string
// wantResult is the -o json output, reduced by summarize.
Expand Down Expand Up @@ -201,6 +219,67 @@ Note: Provider plan not run: no provider diff server planned these resources.
},
},
},
"UnhealthyPlanText": {
reason: "-o plan marks the failing XR's header and its not-ready and paused composed resources' plan entries, prints the Health: line after Plan:, and exits 7: changes (3) and failing (4).",
cluster: &unhealthyCase,
wantExitCode: dp.ExitCodeDiffDetected | dp.ExitCodeFailing,
wantText: `[~] Composition.apiextensions.crossplane.io xnopresources.diff.example.org (update)
Applying this creates a new CompositionRevision, which 2 composites would adopt.
spec:
pipeline[0]:
input:
inline:
~ template: "apiVersion: ns.nop.example.org/v1alpha1\nkind: XDownstreamResource\nmetadata:\n name: {{ .observed.composite.resource.metadata.name }}\n namespace: {{ .observed.composite.resource.metadata.namespace }}\n annotations:\n gotemplating.fn.crossplane.io/composition-resource-name: nop-resource\nspec:\n forProvider:\n configData: {{ .observed.composite.resource.spec.coolField }}\n resourceTier: basic\n" -> "apiVersion: ns.nop.example.org/v1alpha1\nkind: XDownstreamResource\nmetadata:\n name: {{ .observed.composite.resource.metadata.name }}\n namespace: {{ .observed.composite.resource.metadata.namespace }}\n annotations:\n gotemplating.fn.crossplane.io/composition-resource-name: nop-resource\nspec:\n forProvider:\n configData: updated-{{ .observed.composite.resource.spec.coolField }}\n resourceTier: premium\n"

XR: XNopResource.ns.diff.example.org default/another-resource
[~] XDownstreamResource.ns.nop.example.org default/another-resource (update)
⚠ paused
spec:
forProvider:
~ configData: "another-existing-value" -> "updated-another-existing-value"
~ resourceTier: "basic" -> "premium"

XR: XNopResource.ns.diff.example.org default/test-resource ⚠ failing (Synced=False, ReconcileError): cannot compose resources: the vpc does not exist
[~] XDownstreamResource.ns.nop.example.org default/test-resource (update)
⚠ not ready (Ready=False, Creating)
spec:
forProvider:
~ configData: "existing-value" -> "updated-existing-value"
~ resourceTier: "basic" -> "premium"

Plan: 0 to add, 3 to change, 0 to destroy.
Health: 1 of 2 XRs unhealthy before apply; 1 resource not ready, 1 paused.

Note: Provider plan not run: no provider diff server planned these resources.
`,
},
"UnhealthyPlanJSON": {
reason: "-o json carries the failing XR's health and each unhealthy plan entry's, and exits 7.",
cluster: &unhealthyCase,
args: []string{"-o", "json"},
wantExitCode: dp.ExitCodeDiffDetected | dp.ExitCodeFailing,
wantResult: &planShape{
Summary: plan.Summary{Update: 3, NoOp: 2},
Composites: []simulate.CompositeResult{
{Ref: another, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy},
{Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp, Health: &health.Health{
State: health.Failing,
Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot compose resources: the vpc does not exist"},
}},
},
Compositions: []simulate.CompositionResult{{
Ref: comp,
RevisionImpact: &simulate.RevisionImpact{ChangeScope: "spec", CreatesRevision: true, RepointedComposites: 2},
}},
Plans: []planEntry{
{Kind: "Composition", Name: comp.Name, Action: plan.ActionUpdate},
{Kind: "XDownstreamResource", Name: "another-resource", Action: plan.ActionUpdate, Composite: "another-resource", Health: health.Paused},
{Kind: "XNopResource", Name: "another-resource", Action: plan.ActionNoOp, Composite: "another-resource"},
{Kind: "XDownstreamResource", Name: "test-resource", Action: plan.ActionUpdate, Composite: "test-resource", Health: health.NotReady},
{Kind: "XNopResource", Name: "test-resource", Action: plan.ActionNoOp, Composite: "test-resource", Health: health.Failing},
},
},
},
"NameRepeatedScopesToEach": {
reason: "repeated --name with --namespace scopes the run to each named composite, as the unscoped run covers both.",
args: []string{"-o", "json", "-n", "default", "--name=another-resource", "--name=test-resource"},
Expand Down Expand Up @@ -251,6 +330,9 @@ Note: Provider plan not run: no provider diff server planned these resources.
if tc.tt != nil {
setup = *tc.tt
}
if tc.cluster != nil {
setup = *tc.cluster
}
cfg := integration.Start(t, setup).Config

var stdout, stderr bytes.Buffer
Expand All @@ -265,8 +347,12 @@ Note: Provider plan not run: no provider diff server planned these resources.
if err != nil {
t.Fatalf("\n%s\nsimulate: unexpected error: %v\nstderr:\n%s", tc.reason, err, stderr.String())
}
if code != dp.ExitCodeDiffDetected {
t.Errorf("\n%s\nsimulate: want exit code %d, got %d", tc.reason, dp.ExitCodeDiffDetected, code)
wantCode := dp.ExitCodeDiffDetected
if tc.wantExitCode != 0 {
wantCode = tc.wantExitCode
}
if code != wantCode {
t.Errorf("\n%s\nsimulate: want exit code %d, got %d", tc.reason, wantCode, code)
}

if tc.wantResult == nil {
Expand Down Expand Up @@ -305,6 +391,8 @@ type planEntry struct {
Kind, Name string
Action plan.Action
Composite string
// Health is the live object's state when it is not healthy, else empty.
Health health.State
}

func summarize(r simulate.Result) planShape {
Expand All @@ -314,6 +402,9 @@ func summarize(r simulate.Result) planShape {
if p.Composite != nil {
e.Composite = p.Composite.Name
}
if p.Health.Unhealthy() {
e.Health = p.Health.State
}
s.Plans = append(s.Plans, e)
}
// The revision's predicted name is a hash of the Composition's content.
Expand Down
82 changes: 82 additions & 0 deletions cmd/crossplane/xr/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,88 @@ Summary: 2 modified`,
ExpectedError: false,
ExpectedExitCode: dp.ExitCodeDiffDetected,
},
"UnhealthyXRWithChangesExits7": {
Reason: "A failing XR with changes prints its health and its not-ready composed resource's, then the Health: line, and exits 7: changes (3) and failing (4).",
SetupFiles: []string{
"../../../internal/testutils/integration/testdata/diff/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/composition.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/functions.yaml",
},
CrossplaneManagedResources: []integration.HierarchicalOwnershipRelation{
integration.Composes(
"../../../internal/testutils/integration/testdata/diff/resources/existing-xr-failing.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/existing-downstream-resource-not-ready.yaml",
),
},
InputFiles: []string{"../../../internal/testutils/integration/testdata/diff/modified-xr.yaml"},
NoColor: true,
ExpectedOutput: `XR: XNopResource/default/test-resource ⚠ failing (Synced=False, ReconcileError): cannot compose resources: the vpc does not exist

~~~ XDownstreamResource/test-resource ⚠ not ready (Ready=False, Creating)
apiVersion: ns.nop.example.org/v1alpha1
kind: XDownstreamResource
metadata:
annotations:
crossplane.io/composition-resource-name: nop-resource
labels:
crossplane.io/composite: test-resource
name: test-resource
namespace: default
spec:
forProvider:
- configData: existing-value
+ configData: modified-value

---
~~~ XNopResource/test-resource ⚠ failing
apiVersion: ns.diff.example.org/v1alpha1
kind: XNopResource
metadata:
labels:
crossplane.io/composite: test-resource
name: test-resource
namespace: default
spec:
- coolField: existing-value
+ coolField: modified-value
crossplane:
compositionRef:
name: xnopresources.diff.example.org
compositionRevisionRef:
name: xnopresources.diff.example.org-b616215
compositionUpdatePolicy: Automatic

---

Summary: 2 modified

Health: 1 of 1 XR unhealthy before apply; 1 resource not ready.`,
ExpectedExitCode: dp.ExitCodeDiffDetected | dp.ExitCodeFailing,
},
"UnhealthyXRWithoutChangesExits4": {
Reason: "A failing XR without changes reports its health and its not-ready composed resource in -o json, and exits 4: failing, no changes.",
OutputFormat: "json",
SetupFiles: []string{
"../../../internal/testutils/integration/testdata/diff/resources/xrd.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/composition.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/functions.yaml",
},
CrossplaneManagedResources: []integration.HierarchicalOwnershipRelation{
integration.Composes(
"../../../internal/testutils/integration/testdata/diff/resources/existing-xr-failing.yaml",
"../../../internal/testutils/integration/testdata/diff/resources/existing-downstream-resource-not-ready.yaml",
),
},
InputFiles: []string{"../../../internal/testutils/integration/testdata/diff/unmodified-xr.yaml"},
ExpectedStructured: simtest.Expect().
WithSummary(0, 0, 0).
WithHealthSummary(1, 0, 1, 0).
WithXRs(simtest.XR("XNopResource", "test-resource", "default").
Status("unchanged").
Health("failing").
Unhealthy("XDownstreamResource", "test-resource", "notReady")),
ExpectedExitCode: dp.ExitCodeFailing,
},
"IgnorePathsArgoCD": {
Reason: "Ignores ArgoCD annotations and labels when --ignore-paths is specified",
SetupFiles: []string{
Expand Down
2 changes: 1 addition & 1 deletion internal/diff/diffprocessor/comp_processor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3008,7 +3008,7 @@ func TestDefaultCompDiffProcessor_DiffComposition_RenderOverlaps(t *testing.T) {
t.Errorf("%s\nDiffComposition(...): want one run-level report error containing %q, got %+v", tc.reason, tc.wantErr, out)
}

if code := DetermineExitCode(err, true); code != ExitCodeToolError {
if code := DetermineExitCode(err, true, false); code != ExitCodeToolError {
t.Errorf("%s\nDetermineExitCode(...) = %d, want %d", tc.reason, code, ExitCodeToolError)
}
})
Expand Down
25 changes: 18 additions & 7 deletions internal/diff/diffprocessor/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ const (
// ExitCodeDiffDetected indicates that differences were detected.
ExitCodeDiffDetected = 3

// ExitCodeFailing indicates that a resource was failing (Synced=False) before apply. It is a bit
// that composes with ExitCodeDiffDetected: a run that finds changes and a failing resource exits
// 7.
ExitCodeFailing = 4

// ExitCodeInterrupted indicates the run was cancelled by SIGINT (Ctrl+C) or SIGTERM. It is 130 by
// the shell convention for SIGINT (128 + 2); the signal handler does not report which signal
// arrived, so SIGTERM uses the same code.
Expand Down Expand Up @@ -345,11 +350,12 @@ func isOnlySchemaValidationErrors(err error) bool {
return false
}

// DetermineExitCode determines the appropriate exit code based on the error and diff status.
// Priority: interrupted (130) > tool error (1) > schema validation error (2) > diff detected (3) >
// success (0). An interruption outranks everything because the other errors of an interrupted run are
// mostly the cancelled calls it caused.
func DetermineExitCode(err error, hasDiffs bool) int {
// DetermineExitCode determines the appropriate exit code based on the error, diff and health status.
// Errors come first, by priority: interrupted (130) > tool error (1) > schema validation error (2).
// An interruption outranks everything because the other errors of an interrupted run are mostly the
// cancelled calls it caused. A run without errors exits with a bitmask: ExitCodeDiffDetected (3) when
// it found differences, ORed with ExitCodeFailing (4) when a resource was failing, so 0, 3, 4 or 7.
func DetermineExitCode(err error, hasDiffs, failing bool) int {
if errors.Is(err, ErrInterrupted) {
return ExitCodeInterrupted
}
Expand All @@ -366,9 +372,14 @@ func DetermineExitCode(err error, hasDiffs bool) int {
return ExitCodeToolError
}

code := ExitCodeSuccess
if hasDiffs {
return ExitCodeDiffDetected
code |= ExitCodeDiffDetected
}

if failing {
code |= ExitCodeFailing
}

return ExitCodeSuccess
return code
}
Loading
Loading