diff --git a/cmd/crossplane/composition/integration_test.go b/cmd/crossplane/composition/integration_test.go index 881cd4e0..1adfb572 100644 --- a/cmd/crossplane/composition/integration_test.go +++ b/cmd/crossplane/composition/integration_test.go @@ -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{ diff --git a/cmd/crossplane/project/integration_plan_output_test.go b/cmd/crossplane/project/integration_plan_output_test.go index 657d89a2..fc8d13ca 100644 --- a/cmd/crossplane/project/integration_plan_output_test.go +++ b/cmd/crossplane/project/integration_plan_output_test.go @@ -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" @@ -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"} @@ -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. @@ -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"}, @@ -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 @@ -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 { @@ -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 { @@ -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. diff --git a/cmd/crossplane/xr/integration_test.go b/cmd/crossplane/xr/integration_test.go index c60bc0d3..8f937857 100644 --- a/cmd/crossplane/xr/integration_test.go +++ b/cmd/crossplane/xr/integration_test.go @@ -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{ diff --git a/internal/diff/diffprocessor/comp_processor_test.go b/internal/diff/diffprocessor/comp_processor_test.go index 446cba1a..9071903f 100644 --- a/internal/diff/diffprocessor/comp_processor_test.go +++ b/internal/diff/diffprocessor/comp_processor_test.go @@ -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) } }) diff --git a/internal/diff/diffprocessor/errors.go b/internal/diff/diffprocessor/errors.go index f721f15a..8ff64d29 100644 --- a/internal/diff/diffprocessor/errors.go +++ b/internal/diff/diffprocessor/errors.go @@ -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. @@ -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 } @@ -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 } diff --git a/internal/diff/diffprocessor/errors_test.go b/internal/diff/diffprocessor/errors_test.go index 9ec3fda0..d35cb3c8 100644 --- a/internal/diff/diffprocessor/errors_test.go +++ b/internal/diff/diffprocessor/errors_test.go @@ -650,8 +650,34 @@ func TestDetermineExitCode(t *testing.T) { tests := map[string]struct { err error hasDiffs bool + failing bool want int }{ + "NoErrorFailing": { + failing: true, + want: ExitCodeFailing, + }, + "NoErrorWithDiffFailing": { + hasDiffs: true, + failing: true, + want: ExitCodeDiffDetected | ExitCodeFailing, + }, + "ToolErrorOutranksFailing": { + err: errors.New("connection refused"), + hasDiffs: true, + failing: true, + want: ExitCodeToolError, + }, + "SchemaValidationErrorOutranksFailing": { + err: &SchemaValidationError{ResourceID: "Kind/res", Message: "invalid"}, + failing: true, + want: ExitCodeSchemaValidation, + }, + "InterruptedOutranksFailing": { + err: ErrInterrupted, + failing: true, + want: ExitCodeInterrupted, + }, "NoErrorNoDiff": { err: nil, hasDiffs: false, @@ -780,7 +806,7 @@ func TestDetermineExitCode(t *testing.T) { for name, tc := range tests { t.Run(name, func(t *testing.T) { - got := DetermineExitCode(tc.err, tc.hasDiffs) + got := DetermineExitCode(tc.err, tc.hasDiffs, tc.failing) if got != tc.want { t.Errorf("DetermineExitCode() = %v, want %v", got, tc.want) } diff --git a/internal/diff/renderer/comp_diff_renderer.go b/internal/diff/renderer/comp_diff_renderer.go index 2e473c2f..be3b5555 100644 --- a/internal/diff/renderer/comp_diff_renderer.go +++ b/internal/diff/renderer/comp_diff_renderer.go @@ -25,6 +25,7 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/logging" dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" ) const ( @@ -65,6 +66,7 @@ func NewDefaultCompDiffRenderer(logger logging.Logger, diffRenderer DiffRenderer // to r.opts.Stdout. Top-level errors are not printed; see CompDiffRenderer. func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) error { stdout := r.opts.Stdout + ownedElsewhere := unhealthyOwnedElsewhere(output.Compositions) for i, comp := range output.Compositions { if i > 0 { @@ -73,11 +75,26 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro } } - if err := r.renderComposition(&comp); err != nil { + if err := r.renderComposition(&comp, ownedElsewhere); err != nil { return err } } + // What is not healthy before apply is summarized once for the run, as in plan output. + var t health.Tally + + for _, comp := range output.Compositions { + for _, impact := range comp.ImpactAnalysis { + tallyComposite(&t, impact.ObjectReference, impact.Health, impact.Diffs) + } + } + + if line := health.SummaryLine(t.Counts()); line != "" { + if _, err := fmt.Fprintf(stdout, "\n%s\n", line); err != nil { + return errors.Wrap(err, "cannot write health summary") + } + } + // One run-wide summary of unverified additions; see DiffRenderer.RenderDiffs for why it is derived // at render time, and why the per-composition reuse of the diff renderer above does not emit it. return writeWarnings(r.opts.Stderr, dt.CompDryRunWarnings(output)) @@ -87,7 +104,7 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro // followed — only if it processed successfully — by the sections describing its effect on composites. // A composition that failed to process has no such sections to show; renderCompositionChanges // reported the error in their place. -func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff) error { +func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { switch { case r.opts.MinimizeComposition: if err := r.renderMinimizedCompositionChanges(comp); err != nil { @@ -100,7 +117,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff) er } if comp.Error == nil { - return r.renderCompositionImpact(comp) + return r.renderCompositionImpact(comp, ownedElsewhere) } return nil @@ -109,7 +126,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff) er // renderCompositionImpact renders the sections describing how a composition affects its composites: // either the note standing in for them when their evaluation was skipped, or the affected-XR list and // the downstream impact analysis. -func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDiff) error { +func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { if comp.ImpactAnalysisSkipped { return r.renderSkippedComposition(comp) } @@ -126,7 +143,7 @@ func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDi } // Render impact analysis (downstream diffs) - return r.renderImpactAnalysis(comp) + return r.renderImpactAnalysis(comp, ownedElsewhere) } // renderSkippedComposition stands in for the affected-XR and impact-analysis sections when a @@ -403,7 +420,7 @@ func (r *DefaultCompDiffRenderer) renderAffectedResourcesList(comp *dt.Compositi } // renderImpactAnalysis renders the impact analysis section with downstream diffs. -func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff) error { +func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { stdout := r.opts.Stdout if _, err := fmt.Fprintf(stdout, headerImpactAnalysis+"\n\n"); err != nil { @@ -438,7 +455,70 @@ func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff) } } - return nil + return r.renderUnhealthyBlocks(comp, ownedElsewhere, len(allDiffs) > 0) +} + +// renderUnhealthyBlocks writes, for each composite the composition affects, +// the resources it composes that are not healthy and have no changes, under a +// line naming the composite. afterDiffs separates the first from the diffs +// above it. +func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool, afterDiffs bool) error { + var sb strings.Builder + + for _, impact := range listedImpacts(comp) { + block := unhealthyBlock(impact.Health, impact.Diffs, ownedElsewhere[refKey(impact.ObjectReference)], r.opts.FullMessages) + if len(block) == 0 { + continue + } + + if afterDiffs || sb.Len() > 0 { + sb.WriteString("\n") + } + + sb.WriteString("XR: " + impactTitle(impact) + "\n") + + for _, l := range block { + sb.WriteString(" " + l + "\n") + } + } + + return write(r.opts.Stdout, sb.String()) +} + +// unhealthyOwnedElsewhere returns, by the key of each composite the run lists, +// the keys its unhealthy block skips: a nested XR the run lists with health +// of its own, in any composition, lists what it composes, so its parent lists +// neither, as in plan output. +func unhealthyOwnedElsewhere(comps []dt.CompositionDiff) map[string]map[string]bool { + var entries []health.Entry + + for i := range comps { + for _, impact := range listedImpacts(&comps[i]) { + e := health.Entry{Key: refKey(impact.ObjectReference), HasHealth: impact.Health.XR != nil} + for _, c := range impact.Health.Composed { + e.Composes = append(e.Composes, refKey(c.ObjectReference)) + } + + entries = append(entries, e) + } + } + + out := map[string]map[string]bool{} + for i, skip := range health.OwnedElsewhere(entries) { + out[entries[i].Key] = skip + } + + return out +} + +// impactTitle names an affected composite, e.g. "XNetwork/prod/net", as the +// xr diff names its sections. +func impactTitle(impact dt.XRImpact) string { + if impact.Namespace != "" { + return impact.Kind + "/" + impact.Namespace + "/" + impact.Name + } + + return impact.Kind + "/" + impact.Name } // totalFiltered sums the per-reason filter counters. Kept in one place so adding a reason cannot @@ -568,12 +648,26 @@ func (r *DefaultCompDiffRenderer) buildXRStatusList(impacts []dt.XRImpact) strin suffix = filteredSuffix(impact) } - fmt.Fprintf(&sb, "%s %s %s/%s (%s)%s%s\n", + // What is not healthy before apply follows, uncoloured: its marker is + // not the status indicator. + desc := healthDescription(impact.Health.XR, r.opts.FullMessages) + if len(desc) > 0 { + desc[0] = " " + desc[0] + } else { + desc = []string{""} + } + + fmt.Fprintf(&sb, "%s %s %s/%s (%s)%s%s%s\n", color, indicator, impact.Kind, impact.Name, scope, suffix, - colorReset) + colorReset, + desc[0]) + + for _, l := range desc[1:] { + fmt.Fprintf(&sb, " %s\n", l) + } // Include error details for XRStatusError impacts so users can diagnose issues. if impact.Status == dt.XRStatusError && impact.Error != nil { diff --git a/internal/diff/renderer/diff_formatter.go b/internal/diff/renderer/diff_formatter.go index 4a3caefe..0164944b 100644 --- a/internal/diff/renderer/diff_formatter.go +++ b/internal/diff/renderer/diff_formatter.go @@ -50,6 +50,10 @@ type DiffOptions struct { // Replaced, when set, reports whether a diff's resource would be replaced; // its header and the summary say so. Nil reports none. Replaced func(*t.ResourceDiff) bool + + // FullMessages prints health condition messages in full, wrapped, rather + // than cut to one line. + FullMessages bool } // OutputFormat represents the desired output format for diffs. diff --git a/internal/diff/renderer/diff_renderer.go b/internal/diff/renderer/diff_renderer.go index b6c86bee..1947cc46 100644 --- a/internal/diff/renderer/diff_renderer.go +++ b/internal/diff/renderer/diff_renderer.go @@ -11,6 +11,7 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/logging" dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" ) // flattenGroups merges every group's diffs into a single map, for the human @@ -82,8 +83,10 @@ type diffCounts struct { // renderDiffList renders a flat set of diffs (sorted by kind/name) to stdout in // the human-readable +++/~~~/--- form and returns the per-type counts. It does // not print a summary; callers decide whether to emit a per-section or -// aggregate summary from the returned counts. Equal diffs are skipped. -func (r *DefaultDiffRenderer) renderDiffList(diffs map[string]*dt.ResourceDiff) (diffCounts, error) { +// aggregate summary from the returned counts. Equal diffs are skipped. The +// diff whose diffKey is described, an XR whose health line was already +// printed, is marked with its tier alone. +func (r *DefaultDiffRenderer) renderDiffList(diffs map[string]*dt.ResourceDiff, described string) (diffCounts, error) { stdout := r.diffOpts.Stdout // Sort by GetKindName, which is how it's displayed to the user. The same kind and name in two @@ -130,6 +133,16 @@ func (r *DefaultDiffRenderer) renderDiffList(diffs map[string]*dt.ResourceDiff) header += " (requires replacement)" } + // A resource the cluster has is marked when it is not healthy. + h := health.Of(diff.Current.Raw) + if desc := healthDescription(h, r.diffOpts.FullMessages); len(desc) > 0 { + if described != "" && diffKey(diff) == described { + desc = []string{health.Tier(h)} + } + + header = strings.Join(append([]string{header + " " + desc[0]}, desc[1:]...), "\n") + } + content := FormatDiff(diff.LineDiffs, r.diffOpts) if content != "" { @@ -257,7 +270,7 @@ func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.Out if len(xrGroups) > 1 { err = r.renderGrouped(groups) } else { - err = r.renderFlat(flattenGroups(groups)) + err = r.renderFlat(flattenGroups(groups), xrGroups) } if err != nil { @@ -268,26 +281,89 @@ func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.Out } // renderFlat renders a single flat block of diffs plus a "Summary:" line. This -// is the pre-grouping behavior, used for identity-less groups (comp reuse). -func (r *DefaultDiffRenderer) renderFlat(diffs map[string]*dt.ResourceDiff) error { - counts, err := r.renderDiffList(diffs) +// is the pre-grouping behavior, used for identity-less groups (comp reuse) and +// a single input XR. That XR, in xrGroups when there is one, is described +// when it or what it composes is not healthy: its health on a line before the +// diffs, its unhealthy resources without changes after them, and a Health: +// line after the summary. +func (r *DefaultDiffRenderer) renderFlat(diffs map[string]*dt.ResourceDiff, xrGroups []dt.XRDiffGroup) error { + stdout := r.diffOpts.Stdout + full := r.diffOpts.FullMessages + + var ( + head, block, described string + t health.Tally + ) + + if len(xrGroups) == 1 { + g := xrGroups[0] + if desc := healthDescription(g.Health.XR, full); len(desc) > 0 { + desc[0] = "XR: " + groupTitle(g) + " " + desc[0] + head = joinLines(desc) + "\n" + described = refKey(g.XR) + } + + block = joinLines(unhealthyBlock(g.Health, g.Diffs, nil, full)) + tallyComposite(&t, g.XR, g.Health, g.Diffs) + } + + if err := write(stdout, head); err != nil { + return err + } + + counts, err := r.renderDiffList(diffs, described) if err != nil { return err } r.logger.Debug("Diff rendering complete", "counts", counts) + summary := "" if counts.output > 0 { - if line := counts.summaryLine(); line != "" { - if _, err := fmt.Fprintf(r.diffOpts.Stdout, "\nSummary: %s\n", line); err != nil { - return errors.Wrap(err, "failed to write summary to output") - } + summary = counts.summaryLine() + } + + // The block, Summary and Health lines are separated by blank lines from + // whatever precedes them. + written := head != "" || counts.output > 0 + for _, s := range []string{block, summaryText(summary), joinLines([]string{health.SummaryLine(t.Counts())})} { + if s == "" || s == "\n" { + continue + } + + if written { + s = "\n" + s + } + + if err := write(stdout, s); err != nil { + return err } + + written = true } return nil } +// summaryText returns the "Summary:" line for line, or "" when it is empty. +func summaryText(line string) string { + if line == "" { + return "" + } + + return "Summary: " + line + "\n" +} + +// groupTitle names a group's XR, e.g. "XNetwork/prod/net". The namespace is +// part of the identity: same-named XRs in different namespaces are distinct. +func groupTitle(g dt.XRDiffGroup) string { + if g.XR.Namespace != "" { + return g.XR.Kind + "/" + g.XR.Namespace + "/" + g.XR.Name + } + + return g.XR.Kind + "/" + g.XR.Name +} + // renderGrouped renders each group as a per-input-XR section (header + diffs + // per-section summary, or an inline error / "No changes."), then an aggregate // footer. Only called when there is more than one input XR (a single XR renders @@ -300,14 +376,17 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount int unchangedXR int errorXR int + t health.Tally ) - for _, g := range groups { + ownedElsewhere := groupsOwnedElsewhere(groups) + + for i, g := range groups { // An identity-less group (should not normally be mixed in here) has no // owning XR to head a section, so fold its diffs into the aggregate // without a header or per-section summary. if !hasIdentity(g) { - counts, err := r.renderDiffList(g.Diffs) + counts, err := r.renderDiffList(g.Diffs, "") if err != nil { return err } @@ -319,51 +398,91 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount++ - // The namespace is part of the identity: same-named XRs in different namespaces are distinct. - title := g.XR.Kind + "/" + g.XR.Name - if g.XR.Namespace != "" { - title = g.XR.Kind + "/" + g.XR.Namespace + "/" + g.XR.Name - } + tallyComposite(&t, g.XR, g.Health, g.Diffs) - if _, err := fmt.Fprintf(stdout, "=== %s ===\n\n", title); err != nil { - return errors.Wrap(err, "failed to write XR section header") + counts, err := r.renderSection(g, ownedElsewhere[i]) + if err != nil { + return err } - if g.Err != nil { + total = total.plus(counts) + + switch { + case g.Err != nil: errorXR++ + case counts.output == 0: + unchangedXR++ + } + } - if _, err := fmt.Fprintf(stdout, "Error: %s\n\n", g.Err.Message); err != nil { - return errors.Wrap(err, "failed to write XR error") - } + if err := r.renderAggregateFooter(xrCount, total, unchangedXR, errorXR); err != nil { + return err + } - continue + return writeHealthLine(stdout, &t) +} + +// renderSection renders one input XR's section: its header and health, then +// its error, or its diffs, unhealthy resources without changes and summary, +// or "No changes." with those resources. It returns the section's counts, +// zero for an errored XR. Its unhealthy resources skip the keys in skip, +// which another section lists. +func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, skip map[string]bool) (diffCounts, error) { + stdout := r.diffOpts.Stdout + + if _, err := fmt.Fprintf(stdout, "=== %s ===\n\n", groupTitle(g)); err != nil { + return diffCounts{}, errors.Wrap(err, "failed to write XR section header") + } + + described := "" + if s := joinLines(healthDescription(g.Health.XR, r.diffOpts.FullMessages)); s != "" { + if err := write(stdout, s+"\n"); err != nil { + return diffCounts{}, err } - counts, err := r.renderDiffList(g.Diffs) - if err != nil { - return err + described = refKey(g.XR) + } + + if g.Err != nil { + if _, err := fmt.Fprintf(stdout, "Error: %s\n\n", g.Err.Message); err != nil { + return diffCounts{}, errors.Wrap(err, "failed to write XR error") } - total = total.plus(counts) + return diffCounts{}, nil + } - if counts.output == 0 { - unchangedXR++ + counts, err := r.renderDiffList(g.Diffs, described) + if err != nil { + return counts, err + } - if _, err := fmt.Fprintf(stdout, "No changes.\n\n"); err != nil { - return errors.Wrap(err, "failed to write no-changes message") - } + block := joinLines(unhealthyBlock(g.Health, g.Diffs, skip, r.diffOpts.FullMessages)) - continue + if counts.output == 0 { + if _, err := fmt.Fprintf(stdout, "No changes.\n\n"); err != nil { + return counts, errors.Wrap(err, "failed to write no-changes message") } - if line := counts.summaryLine(); line != "" { - if _, err := fmt.Fprintf(stdout, "\nSummary: %s\n\n", line); err != nil { - return errors.Wrap(err, "failed to write section summary") - } + if block != "" { + return counts, write(stdout, block+"\n") + } + + return counts, nil + } + + if block != "" { + if err := write(stdout, "\n"+block); err != nil { + return counts, err } } - return r.renderAggregateFooter(xrCount, total, unchangedXR, errorXR) + if line := counts.summaryLine(); line != "" { + if _, err := fmt.Fprintf(stdout, "\nSummary: %s\n\n", line); err != nil { + return counts, errors.Wrap(err, "failed to write section summary") + } + } + + return counts, nil } // renderAggregateFooter writes the cross-XR totals line shown when more than one diff --git a/internal/diff/renderer/diff_renderer_test.go b/internal/diff/renderer/diff_renderer_test.go index 46630026..2de6315e 100644 --- a/internal/diff/renderer/diff_renderer_test.go +++ b/internal/diff/renderer/diff_renderer_test.go @@ -485,7 +485,7 @@ func TestDefaultDiffRenderer_renderDiffList_SameKindNameDifferentNamespaces(t *t opts := DefaultDiffOptions() opts.Stdout, opts.Stderr = &stdout, &bytes.Buffer{} - if _, err := NewDiffRenderer(tu.TestLogger(t, false), opts).(*DefaultDiffRenderer).renderDiffList(diffs); err != nil { + if _, err := NewDiffRenderer(tu.TestLogger(t, false), opts).(*DefaultDiffRenderer).renderDiffList(diffs, ""); err != nil { t.Fatalf("renderDiffList(): %v", err) } diff --git a/internal/diff/renderer/health.go b/internal/diff/renderer/health.go new file mode 100644 index 00000000..deba2452 --- /dev/null +++ b/internal/diff/renderer/health.go @@ -0,0 +1,140 @@ +package renderer + +import ( + "fmt" + "io" + "strings" + + corev1 "k8s.io/api/core/v1" + + "github.com/crossplane/crossplane-runtime/v2/pkg/errors" + + dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" +) + +// refKey identifies ref across API versions, as health.Key does. +func refKey(ref corev1.ObjectReference) string { + return health.Key(ref.APIVersion, ref.Kind, ref.Namespace, ref.Name) +} + +// diffKey identifies d's resource across API versions, as health.Key does. +func diffKey(d *dt.ResourceDiff) string { + return health.Key(d.Gvk.GroupVersion().String(), d.Gvk.Kind, d.Namespace, d.ResourceName) +} + +// refName returns how the diff list names ref, e.g. "Bucket/my-bucket". +func refName(ref corev1.ObjectReference) string { + return ref.Kind + "/" + ref.Name +} + +// unhealthyBlock returns the lines listing what a composite composes that is +// not healthy and has no changes in diffs, or nil when there is nothing. A +// resource a nested composite composes is nested under that composite, as in +// plan output. It skips the keys in skip, which another entry lists. +func unhealthyBlock(h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff, skip map[string]bool, full bool) []string { + listed := map[string]string{} + + for _, d := range diffs { + if d.DiffType != dt.DiffTypeEqual { + listed[diffKey(d)] = getKindName(d) + } + } + + var items []health.Item + + for _, r := range h.Composed { + id := refKey(r.ObjectReference) + if !r.Health.Unhealthy() || listed[id] != "" || skip[id] { + continue + } + + it := health.Item{ID: id, Name: refName(r.ObjectReference), Health: r.Health} + if r.Via != nil { + it.Via, it.ViaName = refKey(*r.Via), refName(*r.Via) + } + + items = append(items, it) + } + + return health.Block(items, listed, full) +} + +// joinLines returns lines, each ended by a newline, or "" when there are +// none. +func joinLines(lines []string) string { + if len(lines) == 0 { + return "" + } + + return strings.Join(lines, "\n") + "\n" +} + +// write writes s to w, or nothing when s is empty. +func write(w io.Writer, s string) error { + if s == "" { + return nil + } + + _, err := fmt.Fprint(w, s) + + return errors.Wrap(err, "cannot write health") +} + +// healthDescription returns h's description for a line of its own: the first +// line of health.Lines, with any wrapped message indented beneath it. +func healthDescription(h *health.Health, full bool) []string { + lines := health.Lines(h, full) + for i := 1; i < len(lines); i++ { + lines[i] = " " + lines[i] + } + + return lines +} + +// tallyComposite adds a top-level composite with ref and health h, and what +// it composes, to t. A composite without health, as one not yet in the +// cluster or whose processing errored, is not counted as a composite, as in +// plan output; where its parent composes it, it counts as a resource. +func tallyComposite(t *health.Tally, ref corev1.ObjectReference, h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff) { + if h.XR != nil { + t.Composite(refKey(ref), h.XR) + } + + for _, d := range diffs { + t.Resource(diffKey(d), health.Of(d.Current.Raw)) + } + + for _, r := range h.Composed { + t.Resource(refKey(r.ObjectReference), r.Health) + } +} + +// writeHealthLine writes the run's Health: line to w, or nothing when nothing +// in it is unhealthy. +func writeHealthLine(w io.Writer, t *health.Tally) error { + line := health.SummaryLine(t.Counts()) + if line == "" { + return nil + } + + _, err := fmt.Fprintln(w, line) + + return errors.Wrap(err, "cannot write health summary") +} + +// groupsOwnedElsewhere returns, by group index, the keys each group's +// unhealthy block skips: a nested XR given as an input with health of its own +// lists what it composes, so its parent lists neither, as in plan output. +func groupsOwnedElsewhere(groups []dt.XRDiffGroup) []map[string]bool { + entries := make([]health.Entry, len(groups)) + + for i, g := range groups { + entries[i] = health.Entry{Key: refKey(g.XR), HasHealth: g.Health.XR != nil} + for _, c := range g.Health.Composed { + entries[i].Composes = append(entries[i].Composes, refKey(c.ObjectReference)) + } + } + + return health.OwnedElsewhere(entries) +} diff --git a/internal/diff/renderer/health_test.go b/internal/diff/renderer/health_test.go new file mode 100644 index 00000000..845a936c --- /dev/null +++ b/internal/diff/renderer/health_test.go @@ -0,0 +1,375 @@ +package renderer + +import ( + "bytes" + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + dt "github.com/crossplane/cli/v2/internal/diff/result" + tu "github.com/crossplane/cli/v2/internal/diff/testutils" + "github.com/crossplane/cli/v2/internal/health" +) + +// liveWith returns d with a live object carrying a Synced=False condition. +func liveWith(d *dt.ResourceDiff, msg string) *dt.ResourceDiff { + d.Current.Raw = &un.Unstructured{Object: map[string]any{ + "apiVersion": d.Gvk.GroupVersion().String(), "kind": d.Gvk.Kind, + "metadata": map[string]any{"name": d.ResourceName}, + "status": map[string]any{"conditions": []any{map[string]any{ + "type": "Synced", "status": "False", "reason": "ReconcileError", "message": msg, + "lastTransitionTime": "2026-01-01T00:00:00Z", + }}}, + }} + + return d +} + +func TestRenderDiffsHealth(t *testing.T) { + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "vpc does not exist"}} + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False", Reason: "Creating"}} + ref := func(kind, name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: "example.org/v1", Kind: kind, Name: name} + } + group := func(name string, xr *health.Health, composed []dt.ResourceHealth, diffs ...*dt.ResourceDiff) dt.XRDiffGroup { + g := xrGroup("XNetwork", name, map[string]*dt.ResourceDiff{}) + for _, d := range diffs { + g.Diffs[d.GetDiffKey()] = d + } + + g.Health = dt.CompositeHealth{XR: xr, Composed: composed} + + return g + } + + type args struct { + groups []dt.XRDiffGroup + full bool + } + cases := map[string]struct { + reason string + args args + want string + }{ + "SingleXR": { + reason: "A single XR prints its health before its diffs, marks a failing resource, lists the unhealthy resources without changes after them, nested by via, and the Health: line after the summary.", + args: args{groups: []dt.XRDiffGroup{group("net", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("Bucket", "b"), Health: failing}, + {ObjectReference: ref("RouteTable", "rt"), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XSubnet", "x")), Health: notReady}, + {ObjectReference: ref("Healthy", "h"), Health: &health.Health{State: health.Healthy}}, + }, liveWith(modifiedDiffFor("Bucket", "b"), "vpc does not exist"))}}, + want: `XR: XNetwork/net ⚠ not ready (Ready=False, Creating) + +~~~ Bucket/b ⚠ failing (Synced=False, ReconcileError): vpc does not exist +- spec: +- field: old ++ spec: ++ field: new + +--- + +Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + Subnet/sn (via XSubnet/x) ⚠ not ready (Ready=False, Creating) + +Summary: 1 modified + +Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False), 1 not ready. +`, + }, + "SingleXRNoChanges": { + reason: "A single XR without changes still prints its unhealthy resources and the Health: line.", + args: args{groups: []dt.XRDiffGroup{group("net", nil, []dt.ResourceHealth{ + {ObjectReference: ref("RouteTable", "rt"), Health: notReady}, + })}}, + want: `Unhealthy resources without changes: + RouteTable/rt ⚠ not ready (Ready=False, Creating) + +Health: 1 resource not ready. +`, + }, + "Grouped": { + reason: "Each XR section carries its health under its header and its unhealthy resources, changed or not, and the Health: line follows the footer. XNetwork/c has no health, so the Health: line counts only XNetwork/a, as plan output does.", + args: args{groups: []dt.XRDiffGroup{ + group("a", failing, nil, modifiedDiffFor("Bucket", "b")), + group("c", nil, []dt.ResourceHealth{{ObjectReference: ref("RouteTable", "rt"), Health: notReady}}), + }}, + want: `=== XNetwork/a === + +⚠ failing (Synced=False, ReconcileError): vpc does not exist + +~~~ Bucket/b +- spec: +- field: old ++ spec: ++ field: new + +--- + +Summary: 1 modified + +=== XNetwork/c === + +No changes. + +Unhealthy resources without changes: + RouteTable/rt ⚠ not ready (Ready=False, Creating) + +================================================================================ +Total: 1 modified across 2 XRs (1 unchanged) +Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. +`, + }, + "GroupedNestedListsItsOwn": { + reason: "A nested XR given as an input with health of its own lists what it composes; its parent lists neither, so each resource is listed once, as in plan output.", + args: args{groups: []dt.XRDiffGroup{ + group("a", nil, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + }), + group("b", notReady, []dt.ResourceHealth{{ObjectReference: ref("RouteTable", "rt"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +No changes. + +=== XNetwork/b === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +================================================================================ +Total: no changes across 2 XRs (2 unchanged) +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "FullMessages": { + reason: "With full messages, a message prints in full beneath its line.", + args: args{full: true, groups: []dt.XRDiffGroup{group("net", nil, nil, liveWith(modifiedDiffFor("Bucket", "b"), "line one\nline two"))}}, + want: `~~~ Bucket/b ⚠ failing (Synced=False, ReconcileError) + line one + line two +- spec: +- field: old ++ spec: ++ field: new + +--- + +Summary: 1 modified + +Health: 1 resource failing (Synced=False). +`, + }, + "XRMessageOnce": { + reason: "An unhealthy XR's message prints once, on its XR: line, with full messages too, and its own diff entry carries only its tier; a composed resource keeps its whole marker.", + args: args{full: true, groups: []dt.XRDiffGroup{group("net", failing, nil, + liveWith(modifiedDiffFor("XNetwork", "net"), "vpc does not exist"), + liveWith(modifiedDiffFor("Bucket", "b"), "boom"))}}, + want: `XR: XNetwork/net ⚠ failing (Synced=False, ReconcileError) + vpc does not exist + +~~~ Bucket/b ⚠ failing (Synced=False, ReconcileError) + boom +- spec: +- field: old ++ spec: ++ field: new + +--- +~~~ XNetwork/net ⚠ failing +- spec: +- field: old ++ spec: ++ field: new + +--- + +Summary: 2 modified + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var buf bytes.Buffer + + opts := DefaultDiffOptions() + opts.UseColors = false + opts.FullMessages = tc.args.full + opts.Stdout = &buf + opts.Stderr = &bytes.Buffer{} + + if err := NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(tc.args.groups, nil, nil); err != nil { + t.Fatalf("\n%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) + } + + if diff := cmp.Diff(tc.want, buf.String()); diff != "" { + t.Errorf("\n%s\nRenderDiffs(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestRenderCompDiffHealth(t *testing.T) { + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "boom"}} + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False", Reason: "Creating"}} + healthy := &health.Health{State: health.Healthy} + rt := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "RouteTable", Name: "rt"} + p := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "p"} + c := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "c"} + sn := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "Subnet", Name: "sn"} + + type args struct { + impacts []dt.XRImpact + } + cases := map[string]struct { + reason string + args args + want string + }{ + "Unhealthy": { + reason: "An unhealthy XR's affected line carries its health, each XR's unhealthy resources without changes follow the impact analysis under its name, and the Health: line ends the run, counting only XBucket/a since XBucket/b has no health.", + args: args{impacts: []dt.XRImpact{ + { + APIVersion: "example.org/v1", Kind: "XBucket", Namespace: "ns", Name: "a", + Status: dt.XRStatusUnchanged, + Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: notReady}}}, + }, + { + APIVersion: "example.org/v1", Kind: "XBucket", Name: "b", + Status: dt.XRStatusUnchanged, + }, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/a (namespace: ns) ⚠ failing (Synced=False, ReconcileError): boom + ✓ XBucket/b (cluster-scoped) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/ns/a + Unhealthy resources without changes: + RouteTable/rt ⚠ not ready (Ready=False, Creating) + +Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. +`, + }, + "NestedListsItsOwn": { + reason: "A nested XR listed with health of its own lists what it composes; its parent lists neither, so each resource is listed once, as in plan output.", + args: args{impacts: []dt.XRImpact{ + { + ObjectReference: p, + Status: dt.XRStatusUnchanged, + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: c, Health: notReady}, {ObjectReference: sn, Via: &c, Health: failing}}}, + }, + { + ObjectReference: c, + Status: dt.XRStatusUnchanged, + ComposedBy: &p, + Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{{ObjectReference: sn, Health: failing}}}, + }, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + ✓ XBucket/c (cluster-scoped) ⚠ not ready (Ready=False, Creating) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/c + Unhealthy resources without changes: + Subnet/sn ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "NestedEntryWithoutHealth": { + reason: "A nested XR whose own entry errored has no health, so it counts as a resource where its parent composes it, and the Health: line shows the failure the run exits 4 for, as plan output does.", + args: args{impacts: []dt.XRImpact{ + { + ObjectReference: p, + Status: dt.XRStatusUnchanged, + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: c, Health: failing}}}, + }, + { + ObjectReference: c, + Status: dt.XRStatusError, + ComposedBy: &p, + }, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + ✗ XBucket/c (cluster-scoped) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/p + Unhealthy resources without changes: + XBucket/c ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 resource failing (Synced=False). +`, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var stdout bytes.Buffer + + opts := DefaultDiffOptions() + opts.Stdout = &stdout + opts.Stderr = &bytes.Buffer{} + opts.UseColors = false + + r := NewDefaultCompDiffRenderer(tu.TestLogger(t, false), NewDiffRenderer(tu.TestLogger(t, false), opts), opts) + comp := dt.CompositionDiff{ + Name: "xbuckets.example.org", + AffectedResources: dt.AffectedResourcesSummary{Total: 2, Unchanged: 2}, + ImpactAnalysis: tc.args.impacts, + } + + if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: []dt.CompositionDiff{comp}}); err != nil { + t.Fatalf("\n%s\nRenderCompDiff(...): unexpected error: %v", tc.reason, err) + } + + if diff := cmp.Diff(tc.want, stdout.String()); diff != "" { + t.Errorf("\n%s\nRenderCompDiff(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/diff/result/comp.go b/internal/diff/result/comp.go index bc89b03c..af2d97a8 100644 --- a/internal/diff/result/comp.go +++ b/internal/diff/result/comp.go @@ -167,7 +167,7 @@ func (i RevisionImpact) Determined() bool { } // HasChanges returns true if this composition diff has any changes, which is what drives -// ExitCodeDiffDetected. +// ExitCodeDiffDetected's bit. // // Deliberately excluded: RevisionImpact. A composition whose only difference is in masked fields // creates a CompositionRevision but has nothing to show and nothing rendering differently, and a diff --git a/internal/health/format.go b/internal/health/format.go new file mode 100644 index 00000000..13b5677e --- /dev/null +++ b/internal/health/format.go @@ -0,0 +1,433 @@ +/* +Copyright 2026 The Crossplane Authors. + +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 health + +import ( + "fmt" + "maps" + "strings" + "unicode/utf8" + + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// Marker flags an object that is not healthy in text output. The diff +// renderer's text output already uses non-ASCII status glyphs, and the marker +// is not a colour, so it stays with colours off. +const Marker = "⚠" + +// BlockHeading heads the block listing a composite's resources that are not +// healthy and have no changes. +const BlockHeading = "Unhealthy resources without changes:" + +const ( + // messageRunes is how many runes of a condition message a one-line + // description keeps, its ellipsis included. + messageRunes = 120 + // wrapRunes is the width a full message is wrapped to. + wrapRunes = 100 +) + +// Tier returns the marker and the tier of h alone, e.g. "⚠ failing", or "" when +// h is nil or healthy. +func Tier(h *Health) string { + if !h.Unhealthy() { + return "" + } + + name, _, _ := tier(h) + + return Marker + " " + name +} + +// tier returns the name of h's tier, and the condition it was read from as +// "Type=Status" with that condition. A paused object has no condition, as its +// conditions are stale. +func tier(h *Health) (name, cond string, c *Condition) { + switch h.State { + case Failing: + return "failing", "Synced=False", h.Synced + case NotReady: + return "not ready", "Ready=False", h.Ready + case Paused, Healthy: + } + + return "paused", "", nil +} + +// Lines describes h for text output, or returns nil when h is nil or healthy. +// The first line is the marker, the tier, the condition it was read from with +// that condition's reason, and its message cut to one line, e.g. +// "⚠ failing (Synced=False, ReconcileError): cannot update". With full, the +// message instead follows in full, wrapped, one element per line. A paused +// object's conditions are stale, so it is described by its tier alone. +func Lines(h *Health, full bool) []string { + if !h.Unhealthy() { + return nil + } + + name, cond, c := tier(h) + if cond == "" { + return []string{Marker + " " + name} + } + + line := Marker + " " + name + " (" + cond + + if c == nil { + return []string{line + ")"} + } + + if c.Reason != "" { + line += ", " + c.Reason + } + + line += ")" + + switch { + case strings.TrimSpace(c.Message) == "": + return []string{line} + case full: + return append([]string{line}, wrap(c.Message)...) + default: + return []string{line + ": " + truncate(c.Message)} + } +} + +// Item is a resource a block of unhealthy resources lists. +type Item struct { + // ID identifies the resource, to match another item's Via against. + ID string + // Name is how the block prints the resource. + Name string + // Via is the ID of the nested composite that composes the resource, and + // ViaName how the block prints it. Both are empty when the block's own + // composite composes it. + Via, ViaName string + + Health *Health +} + +// Block returns the lines of the block listing items, a composite's resources +// that are not healthy and have no changes, or nil when there are none. The +// heading is unindented and each item is indented two spaces per level below +// it, with any wrapped message four more. +// +// An item a nested composite composes is nested under that composite: under +// its own item, or, for a composite listed elsewhere with changes, under a +// line naming it. listed maps the IDs of the resources listed elsewhere to that +// line. An item whose nested composite is neither names it, as "(via ...)". +func Block(items []Item, listed map[string]string, full bool) []string { + if len(items) == 0 { + return nil + } + + ids := make(map[string]bool, len(items)) + for _, it := range items { + ids[it.ID] = true + } + + nested := func(it Item) bool { + return it.Via != "" && (ids[it.Via] || listed[it.Via] != "") + } + + children := map[string][]Item{} + + for _, it := range items { + if nested(it) { + children[it.Via] = append(children[it.Via], it) + } + } + + lines := []string{BlockHeading} + done := map[string]bool{} + + var add func(it Item, depth int) + + add = func(it Item, depth int) { + if done[it.ID] { + return + } + + done[it.ID] = true + indent := strings.Repeat(" ", depth+1) + + name := it.Name + if it.Via != "" && !nested(it) { + name += " (via " + it.ViaName + ")" + } + + desc := Lines(it.Health, full) + if len(desc) == 0 { + lines = append(lines, indent+name) + } else { + lines = append(lines, indent+name+" "+desc[0]) + for _, l := range desc[1:] { + lines = append(lines, indent+" "+l) + } + } + + for _, c := range children[it.ID] { + add(c, depth+1) + } + } + + shown := map[string]bool{} + + for _, it := range items { + switch { + case !nested(it): + add(it, 0) + case !ids[it.Via] && !shown[it.Via]: + // A composite listed elsewhere heads its resources here too. + shown[it.Via] = true + lines = append(lines, " "+listed[it.Via]) + + for _, c := range children[it.Via] { + add(c, 1) + } + } + } + + // Items whose nesting loops back on itself have no root; list them + // rather than lose them. + for _, it := range items { + add(it, 0) + } + + return lines +} + +// truncate returns msg on one line, whitespace collapsed to single spaces, +// cut to messageRunes with an ellipsis. +func truncate(msg string) string { + msg = strings.Join(strings.Fields(msg), " ") + if utf8.RuneCountInString(msg) <= messageRunes { + return msg + } + + return string([]rune(msg)[:messageRunes-1]) + "…" +} + +// wrap returns msg's lines, blank ones dropped, each wrapped at word +// boundaries to wrapRunes. A word longer than that has a line to itself. +func wrap(msg string) []string { + var out []string + + for line := range strings.SplitSeq(msg, "\n") { + cur := "" + + for w := range strings.FieldsSeq(line) { + if cur != "" && utf8.RuneCountInString(cur)+1+utf8.RuneCountInString(w) > wrapRunes { + out = append(out, cur) + cur = "" + } + + if cur != "" { + cur += " " + } + + cur += w + } + + if cur != "" { + out = append(out, cur) + } + } + + return out +} + +// Key identifies a resource across API versions, for matching an Item's Via +// against the resource it names. +func Key(apiVersion, kind, namespace, name string) string { + gk := schema.FromAPIVersionAndKind(apiVersion, kind).GroupKind() + return gk.String() + "/" + namespace + "/" + name +} + +// Tally counts a run's health: the composites it lists, and the other +// resources by state, each once. Resources are matched by Key, and the first +// health a resource is added with wins. A resource that is also added as a +// composite counts only as a composite, whatever the order they were added in. +type Tally struct { + composites map[string]bool + resources map[string]State + order []string +} + +// Composite adds a composite with key and health h. +func (t *Tally) Composite(key string, h *Health) { + if t.composites == nil { + t.composites = map[string]bool{} + } + + if _, ok := t.composites[key]; !ok { + t.composites[key] = h.Unhealthy() + } +} + +// Resource adds a resource with key and health h. A resource with no health +// is not counted. +func (t *Tally) Resource(key string, h *Health) { + if h == nil { + return + } + + if t.resources == nil { + t.resources = map[string]State{} + } + + if _, ok := t.resources[key]; !ok { + t.resources[key] = h.State + t.order = append(t.order, key) + } +} + +// Counts returns what t counted. +func (t *Tally) Counts() Counts { + c := Counts{Composites: len(t.composites)} + + for _, unhealthy := range t.composites { + if unhealthy { + c.UnhealthyComposites++ + } + } + + for _, key := range t.order { + if _, ok := t.composites[key]; ok { + continue + } + + switch t.resources[key] { + case Failing: + c.Failing++ + case NotReady: + c.NotReady++ + case Paused: + c.Paused++ + case Healthy: + } + } + + return c +} + +// Counts are a run's health counts, for its summary line. +type Counts struct { + // Composites is how many composites the run listed, and + // UnhealthyComposites how many of those are not healthy. + Composites, UnhealthyComposites int + // Failing, NotReady and Paused count the other resources by state. + Failing, NotReady, Paused int +} + +// SummaryLine returns the line summarizing c, e.g. "Health: 1 of 2 XRs +// unhealthy before apply; 12 resources failing (Synced=False), 2 not ready, +// 1 paused.", with only the non-zero parts, or "" when nothing is unhealthy. +func SummaryLine(c Counts) string { + var parts []string + + if c.UnhealthyComposites > 0 { + noun := "XRs" + if c.Composites == 1 { + noun = "XR" + } + + parts = append(parts, fmt.Sprintf("%d of %d %s unhealthy before apply", c.UnhealthyComposites, c.Composites, noun)) + } + + var resources []string + + for _, n := range []struct { + count int + what string + }{ + {c.Failing, "failing (Synced=False)"}, + {c.NotReady, "not ready"}, + {c.Paused, "paused"}, + } { + if n.count == 0 { + continue + } + + if len(resources) == 0 { + noun := "resources" + if n.count == 1 { + noun = "resource" + } + + resources = append(resources, fmt.Sprintf("%d %s %s", n.count, noun, n.what)) + + continue + } + + resources = append(resources, fmt.Sprintf("%d %s", n.count, n.what)) + } + + if len(resources) > 0 { + parts = append(parts, strings.Join(resources, ", ")) + } + + if len(parts) == 0 { + return "" + } + + return "Health: " + strings.Join(parts, "; ") + "." +} + +// Entry is a composite entry in a run's output, for OwnedElsewhere: its Key, +// whether it has health of its own, and the Keys of what it composes. +type Entry struct { + Key string + HasHealth bool + Composes []string +} + +// OwnedElsewhere returns, for each of entries, the Keys it must not list +// because a nested composite entry with health of its own lists them: that +// nested composite, and what it composes. So a resource is listed under the +// most deeply nested composite entry that composes it, once. An entry without +// health is listed by its parent, as a resource. +func OwnedElsewhere(entries []Entry) []map[string]bool { + composes := make([]map[string]bool, len(entries)) + withHealth := map[string][]int{} + + for i, e := range entries { + composes[i] = map[string]bool{} + for _, k := range e.Composes { + composes[i][k] = true + } + + if e.HasHealth { + withHealth[e.Key] = append(withHealth[e.Key], i) + } + } + + out := make([]map[string]bool, len(entries)) + + for i := range entries { + out[i] = map[string]bool{} + + for k := range composes[i] { + for _, j := range withHealth[k] { + out[i][k] = true + maps.Copy(out[i], composes[j]) + } + } + } + + return out +} diff --git a/internal/health/format_test.go b/internal/health/format_test.go new file mode 100644 index 00000000..3d44d86f --- /dev/null +++ b/internal/health/format_test.go @@ -0,0 +1,370 @@ +/* +Copyright 2026 The Crossplane Authors. + +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 health + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestLines(t *testing.T) { + long := strings.Repeat("word ", 40) // 200 runes + failing := func(msg string) *Health { + return &Health{State: Failing, Synced: &Condition{Status: "False", Reason: "ReconcileError", Message: msg}} + } + + type args struct { + h *Health + full bool + } + cases := map[string]struct { + reason string + args args + want []string + }{ + "Nil": { + reason: "No live object prints nothing.", + }, + "Healthy": { + reason: "A healthy object prints nothing, so healthy output is unchanged.", + args: args{h: &Health{State: Healthy}}, + }, + "Failing": { + reason: "A failing object names the tier, the Synced condition's reason and its message.", + args: args{h: failing("cannot update: denied")}, + want: []string{"⚠ failing (Synced=False, ReconcileError): cannot update: denied"}, + }, + "NotReady": { + reason: "A not-ready object is described by its Ready condition.", + args: args{h: &Health{State: NotReady, Ready: &Condition{Status: "False", Reason: "Creating"}}}, + want: []string{"⚠ not ready (Ready=False, Creating)"}, + }, + "Paused": { + reason: "A paused object's conditions are stale, so it is described by its tier alone.", + args: args{h: &Health{State: Paused, Synced: &Condition{Status: "False", Reason: "ReconcileError", Message: "x"}}}, + want: []string{"⚠ paused"}, + }, + "NoReason": { + reason: "A condition without a reason prints none.", + args: args{h: &Health{State: Failing, Synced: &Condition{Status: "False", Message: "boom"}}}, + want: []string{"⚠ failing (Synced=False): boom"}, + }, + "Collapsed": { + reason: "A multi-line message prints on one line, whitespace collapsed.", + args: args{h: failing("first line\n second\tline\n")}, + want: []string{"⚠ failing (Synced=False, ReconcileError): first line second line"}, + }, + "Truncated": { + reason: "A message over 120 runes is cut to 120, its ellipsis included.", + args: args{h: failing(long)}, + want: []string{"⚠ failing (Synced=False, ReconcileError): " + strings.Repeat("word ", 23) + "word…"}, + }, + "TruncatedRunes": { + reason: "Truncation counts runes, not bytes, so a multi-byte message isn't split mid-rune.", + args: args{h: failing(strings.Repeat("é", 130))}, + want: []string{"⚠ failing (Synced=False, ReconcileError): " + strings.Repeat("é", 119) + "…"}, + }, + "Full": { + reason: "With full, the message follows the first line in full, wrapped at word boundaries, its own line breaks kept.", + args: args{h: failing(long + "\nsecond"), full: true}, + want: []string{ + "⚠ failing (Synced=False, ReconcileError)", + strings.TrimSpace(strings.Repeat("word ", 20)), + strings.TrimSpace(strings.Repeat("word ", 20)), + "second", + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Lines(tc.args.h, tc.args.full) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nLines(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestTier(t *testing.T) { + cases := map[string]struct { + reason string + h *Health + want string + }{ + "Nil": { + reason: "No live object has no tier.", + }, + "Healthy": { + reason: "A healthy object has no tier.", + h: &Health{State: Healthy}, + }, + "Failing": { + reason: "A failing object is named by its tier alone, without condition, reason or message.", + h: &Health{State: Failing, Synced: &Condition{Status: "False", Reason: "ReconcileError", Message: "cannot update"}}, + want: "⚠ failing", + }, + "NotReady": { + reason: "A not-ready object is named by its tier alone.", + h: &Health{State: NotReady, Ready: &Condition{Status: "False", Reason: "Creating"}}, + want: "⚠ not ready", + }, + "Paused": { + reason: "A paused object is named by its tier.", + h: &Health{State: Paused}, + want: "⚠ paused", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + if diff := cmp.Diff(tc.want, Tier(tc.h)); diff != "" { + t.Errorf("\n%s\nTier(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestBlock(t *testing.T) { + failing := &Health{State: Failing, Synced: &Condition{Status: "False", Reason: "ReconcileError", Message: "boom"}} + notReady := &Health{State: NotReady, Ready: &Condition{Status: "False", Reason: "Creating"}} + + type args struct { + items []Item + listed map[string]string + } + cases := map[string]struct { + reason string + args args + want []string + }{ + "None": { + reason: "No unhealthy resources print no block.", + }, + "Direct": { + reason: "Each resource prints on one line under the heading, in order.", + args: args{items: []Item{ + {ID: "a", Name: "RouteTable.ec2 rt", Health: failing}, + {ID: "b", Name: "Subnet.ec2 sn", Health: notReady}, + }}, + want: []string{ + "Unhealthy resources without changes:", + " RouteTable.ec2 rt ⚠ failing (Synced=False, ReconcileError): boom", + " Subnet.ec2 sn ⚠ not ready (Ready=False, Creating)", + }, + }, + "NestedUnderListedComposite": { + reason: "A resource a nested composite composes is indented under that composite when the block lists it too.", + args: args{items: []Item{ + {ID: "rt", Name: "RouteTable.ec2 rt", Via: "x", ViaName: "XSubnet.example.org x", Health: failing}, + {ID: "x", Name: "XSubnet.example.org x", Health: notReady}, + }}, + want: []string{ + "Unhealthy resources without changes:", + " XSubnet.example.org x ⚠ not ready (Ready=False, Creating)", + " RouteTable.ec2 rt ⚠ failing (Synced=False, ReconcileError): boom", + }, + }, + "NestedUnderPlannedComposite": { + reason: "A resource whose nested composite has a plan is indented under a line naming that composite.", + args: args{ + items: []Item{{ID: "rt", Name: "RouteTable.ec2 rt", Via: "x", ViaName: "XSubnet.example.org x", Health: failing}}, + listed: map[string]string{"x": "XSubnet.example.org x"}, + }, + want: []string{ + "Unhealthy resources without changes:", + " XSubnet.example.org x", + " RouteTable.ec2 rt ⚠ failing (Synced=False, ReconcileError): boom", + }, + }, + "ViaNotListed": { + reason: "A resource whose nested composite is not listed names it on its line.", + args: args{items: []Item{ + {ID: "rt", Name: "RouteTable.ec2 rt", Via: "x", ViaName: "XSubnet.example.org x", Health: failing}, + }}, + want: []string{ + "Unhealthy resources without changes:", + " RouteTable.ec2 rt (via XSubnet.example.org x) ⚠ failing (Synced=False, ReconcileError): boom", + }, + }, + "DeeplyNested": { + reason: "Nesting follows each via, however deep.", + args: args{items: []Item{ + {ID: "y", Name: "XInner y", Via: "x", ViaName: "XOuter x", Health: notReady}, + {ID: "rt", Name: "RouteTable rt", Via: "y", ViaName: "XInner y", Health: failing}, + {ID: "x", Name: "XOuter x", Health: notReady}, + }}, + want: []string{ + "Unhealthy resources without changes:", + " XOuter x ⚠ not ready (Ready=False, Creating)", + " XInner y ⚠ not ready (Ready=False, Creating)", + " RouteTable rt ⚠ failing (Synced=False, ReconcileError): boom", + }, + }, + "Cycle": { + reason: "Resources whose vias loop back on each other are still listed, once each.", + args: args{items: []Item{ + {ID: "a", Name: "A", Via: "b", ViaName: "B", Health: failing}, + {ID: "b", Name: "B", Via: "a", ViaName: "A", Health: notReady}, + }}, + want: []string{ + "Unhealthy resources without changes:", + " A ⚠ failing (Synced=False, ReconcileError): boom", + " B ⚠ not ready (Ready=False, Creating)", + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Block(tc.args.items, tc.args.listed, false) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nBlock(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestBlockFullMessages(t *testing.T) { + type args struct { + items []Item + } + cases := map[string]struct { + reason string + args args + want []string + }{ + "Wrapped": { + reason: "With full messages, a message prints in full beneath its resource, indented four more.", + args: args{items: []Item{{ID: "rt", Name: "RouteTable rt", Health: &Health{ + State: Failing, Synced: &Condition{Status: "False", Reason: "ReconcileError", Message: "line one\nline two"}, + }}}}, + want: []string{ + "Unhealthy resources without changes:", + " RouteTable rt ⚠ failing (Synced=False, ReconcileError)", + " line one", + " line two", + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Block(tc.args.items, nil, true) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nBlock(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestTally(t *testing.T) { + failing := &Health{State: Failing} + notReady := &Health{State: NotReady} + + type args struct { + add func(*Tally) + } + cases := map[string]struct { + reason string + args args + want Counts + }{ + "Empty": { + reason: "Nothing added counts nothing.", + args: args{add: func(*Tally) {}}, + }, + "EachOnce": { + reason: "A resource added twice counts once, under the health it was first added with.", + args: args{add: func(t *Tally) { + t.Resource("a", failing) + t.Resource("a", notReady) + t.Resource("b", &Health{State: Paused}) + t.Resource("c", nil) + }}, + want: Counts{Failing: 1, Paused: 1}, + }, + "CompositesCountedAsComposites": { + reason: "Composites count once each, the unhealthy ones apart, and not again as resources, whichever is added first.", + args: args{add: func(t *Tally) { + t.Resource("x", failing) + t.Composite("x", failing) + t.Composite("y", nil) + t.Composite("y", failing) + t.Resource("y", failing) + t.Resource("r", notReady) + }}, + want: Counts{Composites: 2, UnhealthyComposites: 1, NotReady: 1}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var tl Tally + tc.args.add(&tl) + if diff := cmp.Diff(tc.want, tl.Counts()); diff != "" { + t.Errorf("\n%s\nCounts(): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestSummaryLine(t *testing.T) { + type args struct { + c Counts + } + cases := map[string]struct { + reason string + args args + want string + }{ + "AllHealthy": { + reason: "With nothing unhealthy there is no line.", + args: args{c: Counts{Composites: 2}}, + }, + "Everything": { + reason: "Every non-zero part prints, in the documented wording.", + args: args{c: Counts{Composites: 2, UnhealthyComposites: 1, Failing: 12, NotReady: 2, Paused: 1}}, + want: "Health: 1 of 2 XRs unhealthy before apply; 12 resources failing (Synced=False), 2 not ready, 1 paused.", + }, + "OnlyResources": { + reason: "Healthy composites are left out, and one resource is singular.", + args: args{c: Counts{Composites: 1, NotReady: 1}}, + want: "Health: 1 resource not ready.", + }, + "OnlyComposite": { + reason: "One composite is singular, and zero resource counts are left out.", + args: args{c: Counts{Composites: 1, UnhealthyComposites: 1}}, + want: "Health: 1 of 1 XR unhealthy before apply.", + }, + "PausedOnly": { + reason: "The first non-zero resource count carries the noun.", + args: args{c: Counts{Paused: 3}}, + want: "Health: 3 resources paused.", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + if diff := cmp.Diff(tc.want, SummaryLine(tc.args.c)); diff != "" { + t.Errorf("\n%s\nSummaryLine(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/plan/output.go b/internal/plan/output.go index b037465a..ab81b0e8 100644 --- a/internal/plan/output.go +++ b/internal/plan/output.go @@ -28,6 +28,8 @@ import ( "sigs.k8s.io/yaml" "github.com/crossplane/crossplane-runtime/v2/pkg/errors" + + "github.com/crossplane/cli/v2/internal/health" ) // The output formats simulate commands share. A unified diff format @@ -161,7 +163,7 @@ type planRenderer struct{} // Render writes the plans to w in the human-readable plan format. func (planRenderer) Render(w io.Writer, plans []*ResourcePlan) error { for _, p := range plans { - RenderPlan(w, p, "") + RenderPlan(w, p, "", false) } s := Summarize(plans) RenderSummaryLine(w, s) @@ -169,11 +171,20 @@ func (planRenderer) Render(w io.Writer, plans []*ResourcePlan) error { return nil } -// RenderPlan prints one resource's header, note when not empty, and change -// tree. A delete prints only its header and note, Terraform-style, though it -// carries actual-only changes. -func RenderPlan(w io.Writer, p *ResourcePlan, note string) { +// RenderPlan prints one resource's header, its health when it is not +// healthy, note when not empty, and change tree. A delete prints only its +// header, health and note, Terraform-style, though it carries actual-only +// changes. With fullMessages a health condition message prints in full, +// wrapped, rather than cut to one line. +func RenderPlan(w io.Writer, p *ResourcePlan, note string, fullMessages bool) { _, _ = fmt.Fprintln(w, header(p)) + for i, l := range health.Lines(p.Health, fullMessages) { + indent := " " + if i > 0 { + indent += " " + } + _, _ = fmt.Fprintln(w, indent+l) + } if note != "" { _, _ = fmt.Fprintf(w, " %s\n", note) } diff --git a/internal/simulate/exit.go b/internal/simulate/exit.go index 29937e77..a4a3f773 100644 --- a/internal/simulate/exit.go +++ b/internal/simulate/exit.go @@ -23,4 +23,9 @@ const ( // ExitCodeChanges is the status a simulate command exits with when the // simulation succeeded and found changes. ExitCodeChanges = 3 + // ExitCodeFailing is the bit a simulate command's exit status carries + // when the simulation succeeded and a resource was failing (Synced=False) + // before apply. It composes with ExitCodeChanges: a run that finds + // changes and a failing resource exits 7. + ExitCodeFailing = 4 ) diff --git a/internal/simulate/flags.go b/internal/simulate/flags.go index 1e727fa8..9031b67c 100644 --- a/internal/simulate/flags.go +++ b/internal/simulate/flags.go @@ -45,6 +45,7 @@ type Flags struct { NoColor bool `help:"Disable colorized output."` Compact bool `help:"Show compact diffs with minimal context."` + FullMessages bool `help:"Print health condition messages in full in plan and diff output, rather than cut to one line."` MaxNestedDepth int `default:"10" help:"Maximum depth for nested XR recursion."` IgnorePaths []string `help:"Paths to ignore in diffs (e.g., 'metadata.annotations[argocd.argoproj.io/tracking-id]')."` FunctionCredentials string `help:"A YAML file or directory of YAML files specifying Secret credentials to pass to Functions." placeholder:"PATH" predictor:"yaml_file_or_directory" type:"path"` diff --git a/internal/simulate/help/exit.md b/internal/simulate/help/exit.md index ecc54afc..ca71a130 100644 --- a/internal/simulate/help/exit.md +++ b/internal/simulate/help/exit.md @@ -12,7 +12,16 @@ the result: - 2: only schema validation failed. - 3: the simulation succeeded and found changes, including drift a provider plan found that the cluster diff didn't. +- 4: the simulation succeeded, found no changes, and a composite resource or + a resource it composes was failing (Synced=False) before apply, including + one the change would delete. A resource that's only not ready, or is + paused, doesn't set it. +- 7: the simulation succeeded, found changes, and a resource was failing: + 3 and 4 combined. - 80: a flag was unknown or had an invalid value, so nothing was simulated. - 130: the simulation was interrupted. -When more than one applies, the lowest of 1, 2 and 3 wins. +An error wins over what the simulation found: 130 over 1 over 2, and any of +them over 3, 4 and 7. Without an error, the status adds 4 for a failing +resource to 3 for changes, so 3 and 7 both mean changes, and 4 and 7 both mean +a failing resource. diff --git a/internal/simulate/report.go b/internal/simulate/report.go index d742e935..a0b1e89b 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -25,7 +25,6 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" apiextensionsv1 "github.com/crossplane/crossplane/apis/v2/apiextensions/v1" @@ -261,37 +260,25 @@ func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { // resource is listed under the most deeply nested composite entry that // composes it, once. func (a *assembler) unhealthy() { - planned := map[objectID]bool{} + planned := map[string]bool{} for _, p := range a.plans { - planned[idOf(p.APIVersion, p.Kind, p.Namespace, p.Name)] = true + planned[health.Key(p.APIVersion, p.Kind, p.Namespace, p.Name)] = true } - composes := make([]map[objectID]bool, len(a.composed)) - entries := map[objectID][]int{} + entries := make([]health.Entry, len(a.composed)) for i, composed := range a.composed { - composes[i] = map[objectID]bool{} + c := a.composites[i] + entries[i] = health.Entry{Key: healthKey(c.Ref), HasHealth: c.Health != nil} for _, r := range composed { - composes[i][idOf(r.APIVersion, r.Kind, r.Namespace, r.Name)] = true - } - if c := a.composites[i]; c.Health != nil { - id := idOf(c.Ref.APIVersion, c.Ref.Kind, c.Ref.Namespace, c.Ref.Name) - entries[id] = append(entries[id], i) + entries[i].Composes = append(entries[i].Composes, health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name)) } } + ownedElsewhere := health.OwnedElsewhere(entries) for i, composed := range a.composed { - // What a nested composite entry lists, and the entry itself. - ownedElsewhere := map[objectID]bool{} - for id := range composes[i] { - for _, j := range entries[id] { - ownedElsewhere[id] = true - maps.Copy(ownedElsewhere, composes[j]) - } - } - for _, r := range composed { - id := idOf(r.APIVersion, r.Kind, r.Namespace, r.Name) - if !r.Health.Unhealthy() || planned[id] || ownedElsewhere[id] { + id := health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name) + if !r.Health.Unhealthy() || planned[id] || ownedElsewhere[i][id] { continue } u := UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health} @@ -304,16 +291,6 @@ func (a *assembler) unhealthy() { } } -// objectID is an object's identity across API versions. -type objectID struct { - gk schema.GroupKind - namespace, name string -} - -func idOf(apiVersion, kind, namespace, name string) objectID { - return objectID{gk: schema.FromAPIVersionAndKind(apiVersion, kind).GroupKind(), namespace: namespace, name: name} -} - // addDiffs adds a plan per diff, in the structured renderer's canonical order. // It reports whether a provider plan changed any of them, which the engine's // verdict alone does not show. diff --git a/internal/simulate/result.go b/internal/simulate/result.go index 8ae6f792..1e219010 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -216,64 +216,54 @@ func (r Result) Deferred() int { // state, from Composites and Plans. A resource counts once, under the state // its first live copy reports, matched across API versions. func (r Result) Health() HealthSummary { - var s HealthSummary - composites := map[schema.GroupKind]map[[2]string]bool{} - isComposite := func(ref plan.ResourceRef) bool { - return composites[groupKind(ref)][[2]string{ref.Namespace, ref.Name}] - } - for _, c := range r.Composites { - gk, id := groupKind(c.Ref), [2]string{c.Ref.Namespace, c.Ref.Name} - // A composite with no health of its own here (one not simulated) is - // counted as a resource where its parent lists it, if anywhere. - if c.Health == nil || composites[gk][id] { - continue - } - if composites[gk] == nil { - composites[gk] = map[[2]string]bool{} - } - composites[gk][id] = true - if c.Health.Unhealthy() { - s.Composites++ - } - } + c := r.healthTally().Counts() + return HealthSummary{Composites: c.UnhealthyComposites, Failing: c.Failing, NotReady: c.NotReady, Paused: c.Paused} +} - seen := map[schema.GroupKind]map[[2]string]bool{} - count := func(ref plan.ResourceRef, h *health.Health) { - if h == nil || isComposite(ref) { - return - } - gk, id := groupKind(ref), [2]string{ref.Namespace, ref.Name} - if seen[gk][id] { - return - } - if seen[gk] == nil { - seen[gk] = map[[2]string]bool{} - } - seen[gk][id] = true - switch h.State { - case health.Failing: - s.Failing++ - case health.NotReady: - s.NotReady++ - case health.Paused: - s.Paused++ - case health.Healthy: +// healthTally adds r's composites and resources to a health.Tally. A +// composite with no health of its own here (one not simulated) isn't added as +// a composite, so it counts as a resource where its parent lists it, if +// anywhere. +func (r Result) healthTally() *health.Tally { + t := &health.Tally{} + for _, c := range r.Composites { + if c.Health != nil { + t.Composite(healthKey(c.Ref), c.Health) } } for _, p := range r.Plans { - count(p.ResourceRef(), p.Health) + t.Resource(healthKey(p.ResourceRef()), p.Health) } for _, c := range r.Composites { for _, u := range c.Unhealthy { - count(u.Ref, u.Health) + t.Resource(healthKey(u.Ref), u.Health) } } - return s + return t +} + +// Failing reports whether a composite or any resource in r is failing, which +// sets exit bit 4. +func (r Result) Failing() bool { + failing := func(h *health.Health) bool { return h != nil && h.State == health.Failing } + for _, c := range r.Composites { + if failing(c.Health) || slices.ContainsFunc(c.Unhealthy, func(u UnhealthyResource) bool { return failing(u.Health) }) { + return true + } + } + return slices.ContainsFunc(r.Plans, func(p *plan.ResourcePlan) bool { return failing(p.Health) }) +} + +// HealthLine returns the Health: line summarizing r, or "" when nothing in +// it is unhealthy. Its XRs are the composites with health of their own, each +// once. +func (r Result) HealthLine() string { + return health.SummaryLine(r.healthTally().Counts()) } -// groupKind is ref's version-independent type. -func groupKind(ref plan.ResourceRef) schema.GroupKind { - return schema.FromAPIVersionAndKind(ref.APIVersion, ref.Kind).GroupKind() +// healthKey identifies ref across API versions, as health.Key does. +func healthKey(ref plan.ResourceRef) string { + return health.Key(ref.APIVersion, ref.Kind, ref.Namespace, ref.Name) } // MarshalJSON writes the result with summary, composites and compositions @@ -319,10 +309,13 @@ type Renderer interface { // NewRenderer returns the Renderer for the given output format: one of // plan.FormatPlan, plan.FormatJSON or plan.FormatYAML. -func NewRenderer(format string) (Renderer, error) { +// With fullMessages the plan format prints health condition messages in full, +// wrapped, rather than cut to one line; the structured formats always carry +// them in full. +func NewRenderer(format string, fullMessages bool) (Renderer, error) { switch format { case plan.FormatPlan: - return planRenderer{}, nil + return planRenderer{fullMessages: fullMessages}, nil case plan.FormatJSON: return jsonRenderer{}, nil case plan.FormatYAML: @@ -361,21 +354,28 @@ func (yamlRenderer) Render(w io.Writer, r Result) error { // tree per resource, then a summary with warnings, then any Notes. When any // plan or composite names a composite, plans print grouped under an // "XR: Kind.group name" header. A Composition's revision impact prints as -// one line under its plan. Run-level Errors and Warnings are not printed; -// the command reports them on stderr. -type planRenderer struct{} +// one line under its plan. What is not healthy before apply is marked where +// it is listed, and summarized after the "Plan:" line. Run-level Errors and +// Warnings are not printed; the command reports them on stderr. +type planRenderer struct { + // fullMessages prints health condition messages in full. + fullMessages bool +} // Render writes the result to w in the human-readable plan format. -func (planRenderer) Render(w io.Writer, r Result) error { +func (pr planRenderer) Render(w io.Writer, r Result) error { impacts := revisionImpactLines(r.Compositions) if len(r.Composites) == 0 && !slices.ContainsFunc(r.Plans, func(p *plan.ResourcePlan) bool { return p.Composite != nil }) { for _, p := range r.Plans { - plan.RenderPlan(w, p, impacts[p.ResourceRef()]) + plan.RenderPlan(w, p, impacts[p.ResourceRef()], pr.fullMessages) } } else { - renderGrouped(w, r, impacts) + pr.renderGrouped(w, r, impacts) } plan.RenderSummaryLine(w, r.Summary) + if line := r.HealthLine(); line != "" { + _, _ = fmt.Fprintln(w, line) + } if d := r.Deferred(); d > 0 { _, _ = fmt.Fprintf(w, "%s deferred (pinned to a composition revision).\n", pluralize(d, "composite resource", "composite resources")) } @@ -417,7 +417,7 @@ func revisionImpactLines(comps []CompositionResult) map[plan.ResourceRef]string // renderGrouped prints ungrouped plans first, then each composite (in // Composites order, then any only plans name) with its plans indented // beneath. A composite's own plan is omitted when it is a no-op. -func renderGrouped(w io.Writer, r Result, impacts map[plan.ResourceRef]string) { +func (pr planRenderer) renderGrouped(w io.Writer, r Result, impacts map[plan.ResourceRef]string) { var refs []plan.ResourceRef byRef := map[plan.ResourceRef][]*plan.ResourcePlan{} status := map[plan.ResourceRef]CompositeResult{} @@ -429,7 +429,7 @@ func renderGrouped(w io.Writer, r Result, impacts map[plan.ResourceRef]string) { } for _, p := range r.Plans { if p.Composite == nil { - plan.RenderPlan(w, p, impacts[p.ResourceRef()]) + plan.RenderPlan(w, p, impacts[p.ResourceRef()], pr.fullMessages) continue } ref := *p.Composite @@ -442,14 +442,23 @@ func renderGrouped(w io.Writer, r Result, impacts map[plan.ResourceRef]string) { } for _, ref := range refs { - renderComposite(w, status[ref], ref, byRef[ref]) + pr.renderComposite(w, status[ref], ref, byRef[ref]) } } // renderComposite prints one composite's header, its deferral or skip note, -// and its plans indented beneath. -func renderComposite(w io.Writer, c CompositeResult, ref plan.ResourceRef, plans []*plan.ResourcePlan) { - _, _ = fmt.Fprintln(w, compositeHeader(c, ref)) +// and its plans indented beneath, then the resources it composes that are not +// healthy and have no plan. +func (pr planRenderer) renderComposite(w io.Writer, c CompositeResult, ref plan.ResourceRef, plans []*plan.ResourcePlan) { + h := compositeHeader(c, ref) + desc := health.Lines(c.Health, pr.fullMessages) + if len(desc) > 0 { + h += " " + desc[0] + } + _, _ = fmt.Fprintln(w, h) + for _, l := range desc[min(1, len(desc)):] { + _, _ = fmt.Fprintf(w, " %s\n", l) + } if c.ComposedBy != nil { gvk := schema.FromAPIVersionAndKind(c.ComposedBy.APIVersion, c.ComposedBy.Kind) name := c.ComposedBy.Name @@ -477,7 +486,17 @@ func renderComposite(w io.Writer, c CompositeResult, ref plan.ResourceRef, plans if p.Action == plan.ActionNoOp && p.Error == "" && p.ResourceRef() == ref { continue } - plan.RenderPlan(&block, p, "") + if p.ResourceRef() == ref { + // The header already describes the composite's health. + own := *p + own.Health = nil + p = &own + } + plan.RenderPlan(&block, p, "", pr.fullMessages) + } + if lines := unhealthyBlock(c.Unhealthy, plans, pr.fullMessages); len(lines) > 0 { + _, _ = fmt.Fprintln(&block, strings.Join(lines, "\n")) + _, _ = fmt.Fprintln(&block) } for line := range strings.Lines(block.String()) { if line != "\n" { @@ -490,14 +509,43 @@ func renderComposite(w io.Writer, c CompositeResult, ref plan.ResourceRef, plans } } -// compositeHeader returns e.g. "XR: XNetwork.example.org prod-network". -func compositeHeader(c CompositeResult, ref plan.ResourceRef) string { +// unhealthyBlock returns the lines listing a composite's resources that are +// not healthy and have no plan, or nil when there are none. A resource a +// nested composite composes is nested under that composite's line: its own, +// or, when the composite has a plan in plans, one naming it. +func unhealthyBlock(unhealthy []UnhealthyResource, plans []*plan.ResourcePlan, full bool) []string { + if len(unhealthy) == 0 { + return nil + } + listed := map[string]string{} + for _, p := range plans { + listed[healthKey(p.ResourceRef())] = displayName(p.ResourceRef()) + } + items := make([]health.Item, 0, len(unhealthy)) + for _, u := range unhealthy { + it := health.Item{ID: healthKey(u.Ref), Name: displayName(u.Ref), Health: u.Health} + if u.Via != nil { + it.Via, it.ViaName = healthKey(*u.Via), displayName(*u.Via) + } + items = append(items, it) + } + return health.Block(items, listed, full) +} + +// displayName returns e.g. "XNetwork.example.org prod/network", as a plan's +// header names its resource. +func displayName(ref plan.ResourceRef) string { gvk := schema.FromAPIVersionAndKind(ref.APIVersion, ref.Kind) name := ref.Name if ref.Namespace != "" { name = ref.Namespace + "/" + name } - h := fmt.Sprintf("XR: %s.%s %s", gvk.Kind, gvk.Group, name) + return gvk.Kind + "." + gvk.Group + " " + name +} + +// compositeHeader returns e.g. "XR: XNetwork.example.org prod-network". +func compositeHeader(c CompositeResult, ref plan.ResourceRef) string { + h := "XR: " + displayName(ref) switch c.Status { case CompositeDeferred: h += " (deferred)" diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index 4c54caef..cadaad19 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -68,7 +68,7 @@ Plan: 0 to add, 1 to change, 1 to destroy. 1 composite resource deferred (pinned to a composition revision). ` var buf bytes.Buffer - r2, _ := NewRenderer(plan.FormatPlan) + r2, _ := NewRenderer(plan.FormatPlan, false) if err := r2.Render(&buf, r); err != nil { t.Fatalf("Render(plan): unexpected error: %v", err) } @@ -89,7 +89,7 @@ func TestRenderPlanCompositeDetail(t *testing.T) { Plan: 0 to add, 0 to change, 0 to destroy. ` var buf bytes.Buffer - r2, _ := NewRenderer(plan.FormatPlan) + r2, _ := NewRenderer(plan.FormatPlan, false) if err := r2.Render(&buf, r); err != nil { t.Fatalf("Render(plan): unexpected error: %v", err) } @@ -101,7 +101,7 @@ Plan: 0 to add, 0 to change, 0 to destroy. func TestRenderPlanPinnedHeader(t *testing.T) { xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod-network"} var buf bytes.Buffer - r, _ := NewRenderer(plan.FormatPlan) + r, _ := NewRenderer(plan.FormatPlan, false) if err := r.Render(&buf, Result{Composites: []CompositeResult{{Ref: xr, Status: CompositeUnchanged, Pinned: true}}}); err != nil { t.Fatalf("Render(plan): unexpected error: %v", err) } @@ -160,7 +160,7 @@ Plan: 0 to add, 2 to change, 0 to destroy. Note: Provider plan not run. ` var buf bytes.Buffer - pr, _ := NewRenderer(plan.FormatPlan) + pr, _ := NewRenderer(plan.FormatPlan, false) if err := pr.Render(&buf, r); err != nil { t.Fatalf("Render(plan): unexpected error: %v", err) } @@ -197,7 +197,7 @@ func TestRenderJSONProjectFields(t *testing.T) { }}, } var buf bytes.Buffer - r, _ := NewRenderer(plan.FormatJSON) + r, _ := NewRenderer(plan.FormatJSON, false) if err := r.Render(&buf, in); err != nil { t.Fatalf("Render(json): unexpected error: %v", err) } @@ -251,7 +251,7 @@ func TestRenderYAMLSummaryDeferred(t *testing.T) { xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod-network"} in := NewResult(nil, []CompositeResult{{Ref: xr, Status: CompositeDeferred}}, nil) var buf bytes.Buffer - r, _ := NewRenderer(plan.FormatYAML) + r, _ := NewRenderer(plan.FormatYAML, false) if err := r.Render(&buf, in); err != nil { t.Fatalf("Render(yaml): unexpected error: %v", err) } @@ -359,7 +359,7 @@ func TestRenderJSONHealth(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { var buf bytes.Buffer - r, _ := NewRenderer(plan.FormatJSON) + r, _ := NewRenderer(plan.FormatJSON, false) if err := r.Render(&buf, tc.args.in); err != nil { t.Fatalf("%s\nRender(json): unexpected error: %v", tc.reason, err) } @@ -388,3 +388,226 @@ func TestRenderJSONHealth(t *testing.T) { }) } } + +func TestRenderPlanHealth(t *testing.T) { + xr := plan.ResourceRef{APIVersion: "aws.platform.upbound.io/v1alpha1", Kind: "Network", Namespace: "crossplane-system", Name: "net"} + other := plan.ResourceRef{APIVersion: "aws.platform.upbound.io/v1alpha1", Kind: "Network", Namespace: "crossplane-system", Name: "other"} + nested := plan.ResourceRef{APIVersion: "aws.platform.upbound.io/v1alpha1", Kind: "XSubnet", Namespace: "crossplane-system", Name: "net-sn"} + rt := plan.ResourceRef{APIVersion: "ec2.aws.m.upbound.io/v1beta1", Kind: "RouteTable", Namespace: "crossplane-system", Name: "net-rt"} + sn := plan.ResourceRef{APIVersion: "ec2.aws.m.upbound.io/v1beta1", Kind: "Subnet", Namespace: "crossplane-system", Name: "net-sn-a"} + failing := func(msg string) *health.Health { + return &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: msg}} + } + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False", Reason: "Creating", Message: "14/15 unready"}} + update := func(name string, h *health.Health) *plan.ResourcePlan { + return &plan.ResourcePlan{ + APIVersion: "ec2.aws.m.upbound.io/v1beta1", Kind: "InternetGateway", Namespace: "crossplane-system", Name: name, + Action: plan.ActionUpdate, Composite: &xr, Health: h, + Changes: []plan.FieldChange{{Path: "spec.forProvider.region", Actual: &plan.Value{Value: "us-east-1"}, Planned: &plan.Value{Value: "us-west-2"}}}, + } + } + vpcMsg := "The vpc ID 'vpc-048777c3b8a8ee173' does not exist\nstatus code: 400" + + type args struct { + r Result + full bool + } + cases := map[string]struct { + reason string + args args + want string + }{ + "BrokenXR": { + reason: "An unhealthy XR's header, a failing plan, and the composed resources that are unhealthy without changes are marked, nested under their nested XR, and summarized.", + args: args{r: NewResult( + []*plan.ResourcePlan{ + // The XR's own no-op plan is not printed; its header carries its health. + {APIVersion: xr.APIVersion, Kind: xr.Kind, Namespace: xr.Namespace, Name: xr.Name, Action: plan.ActionNoOp, Composite: &xr, Health: notReady}, + update("net-igw", failing("cannot update: "+vpcMsg)), + }, + []CompositeResult{ + {Ref: xr, Status: CompositeChanged, Health: notReady, Unhealthy: []UnhealthyResource{ + {Ref: rt, Health: failing(vpcMsg)}, + {Ref: nested, Health: notReady}, + {Ref: sn, Via: &nested, Health: &health.Health{State: health.Paused}}, + }}, + {Ref: other, Status: CompositeUnchanged, Health: &health.Health{State: health.Healthy}}, + }, nil)}, + want: `XR: Network.aws.platform.upbound.io crossplane-system/net ⚠ not ready (Ready=False, Creating): 14/15 unready + [~] InternetGateway.ec2.aws.m.upbound.io crossplane-system/net-igw (update) + ⚠ failing (Synced=False, ReconcileError): cannot update: The vpc ID 'vpc-048777c3b8a8ee173' does not exist status code: 400 + spec: + forProvider: + ~ region: "us-east-1" -> "us-west-2" + + Unhealthy resources without changes: + RouteTable.ec2.aws.m.upbound.io crossplane-system/net-rt ⚠ failing (Synced=False, ReconcileError): The vpc ID 'vpc-048777c3b8a8ee173' does not exist status code: 400 + XSubnet.aws.platform.upbound.io crossplane-system/net-sn ⚠ not ready (Ready=False, Creating): 14/15 unready + Subnet.ec2.aws.m.upbound.io crossplane-system/net-sn-a ⚠ paused + +XR: Network.aws.platform.upbound.io crossplane-system/other + +Plan: 0 to add, 1 to change, 0 to destroy. +Health: 1 of 2 XRs unhealthy before apply; 2 resources failing (Synced=False), 1 not ready, 1 paused. +`, + }, + "FullMessages": { + reason: "With full messages, each message prints in full beneath its line, wrapped and indented.", + args: args{full: true, r: NewResult( + []*plan.ResourcePlan{update("net-igw", failing(vpcMsg))}, + []CompositeResult{{Ref: xr, Status: CompositeChanged, Health: failing("xr broken"), Unhealthy: []UnhealthyResource{{Ref: rt, Health: failing(vpcMsg)}}}}, + nil)}, + want: `XR: Network.aws.platform.upbound.io crossplane-system/net ⚠ failing (Synced=False, ReconcileError) + xr broken + [~] InternetGateway.ec2.aws.m.upbound.io crossplane-system/net-igw (update) + ⚠ failing (Synced=False, ReconcileError) + The vpc ID 'vpc-048777c3b8a8ee173' does not exist + status code: 400 + spec: + forProvider: + ~ region: "us-east-1" -> "us-west-2" + + Unhealthy resources without changes: + RouteTable.ec2.aws.m.upbound.io crossplane-system/net-rt ⚠ failing (Synced=False, ReconcileError) + The vpc ID 'vpc-048777c3b8a8ee173' does not exist + status code: 400 + +Plan: 0 to add, 1 to change, 0 to destroy. +Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "NestedUnderPlannedXR": { + reason: "A resource whose nested XR has a plan of its own is nested under a line naming that XR.", + args: args{r: NewResult( + []*plan.ResourcePlan{{APIVersion: nested.APIVersion, Kind: nested.Kind, Namespace: nested.Namespace, Name: nested.Name, Action: plan.ActionUpdate, Composite: &xr}}, + []CompositeResult{{Ref: xr, Status: CompositeChanged, Unhealthy: []UnhealthyResource{{Ref: sn, Via: &nested, Health: notReady}}}}, + nil)}, + want: `XR: Network.aws.platform.upbound.io crossplane-system/net + [~] XSubnet.aws.platform.upbound.io crossplane-system/net-sn (update) + + Unhealthy resources without changes: + XSubnet.aws.platform.upbound.io crossplane-system/net-sn + Subnet.ec2.aws.m.upbound.io crossplane-system/net-sn-a ⚠ not ready (Ready=False, Creating): 14/15 unready + +Plan: 0 to add, 1 to change, 0 to destroy. +Health: 1 resource not ready. +`, + }, + "NestedEntryListsItsOwn": { + reason: "A nested XR with an entry and health of its own is marked on its own header and lists what it composes; it counts as an XR, not a resource.", + args: args{r: NewResult(nil, + []CompositeResult{ + {Ref: xr, Status: CompositeUnchanged, Health: &health.Health{State: health.Healthy}, Unhealthy: []UnhealthyResource{{Ref: rt, Health: failing("gone")}}}, + {Ref: nested, ComposedBy: &xr, Status: CompositeUnchanged, Health: notReady, Unhealthy: []UnhealthyResource{{Ref: sn, Health: notReady}}}, + }, nil)}, + want: `XR: Network.aws.platform.upbound.io crossplane-system/net + Unhealthy resources without changes: + RouteTable.ec2.aws.m.upbound.io crossplane-system/net-rt ⚠ failing (Synced=False, ReconcileError): gone + +XR: XSubnet.aws.platform.upbound.io crossplane-system/net-sn ⚠ not ready (Ready=False, Creating): 14/15 unready + ↳ composed by Network.aws.platform.upbound.io crossplane-system/net + Unhealthy resources without changes: + Subnet.ec2.aws.m.upbound.io crossplane-system/net-sn-a ⚠ not ready (Ready=False, Creating): 14/15 unready + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. +`, + }, + "NestedEntryWithoutHealth": { + reason: "A nested XR whose entry has no health is listed under its parent and counts as a resource, not an XR.", + args: args{r: NewResult(nil, + []CompositeResult{ + {Ref: xr, Status: CompositeUnchanged, Health: notReady, Unhealthy: []UnhealthyResource{ + {Ref: nested, Health: failing("broken")}, + {Ref: sn, Via: &nested, Health: notReady}, + }}, + {Ref: nested, ComposedBy: &xr, Status: CompositeError}, + }, nil)}, + want: `XR: Network.aws.platform.upbound.io crossplane-system/net ⚠ not ready (Ready=False, Creating): 14/15 unready + Unhealthy resources without changes: + XSubnet.aws.platform.upbound.io crossplane-system/net-sn ⚠ failing (Synced=False, ReconcileError): broken + Subnet.ec2.aws.m.upbound.io crossplane-system/net-sn-a ⚠ not ready (Ready=False, Creating): 14/15 unready + +XR: XSubnet.aws.platform.upbound.io crossplane-system/net-sn + ↳ composed by Network.aws.platform.upbound.io crossplane-system/net + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. +`, + }, + "UngroupedDelete": { + reason: "A failing resource the plan deletes is marked like any other.", + args: args{r: NewResult( + []*plan.ResourcePlan{{APIVersion: rt.APIVersion, Kind: rt.Kind, Namespace: rt.Namespace, Name: rt.Name, Action: plan.ActionDelete, Health: failing("gone")}}, + nil, nil)}, + want: `[-] RouteTable.ec2.aws.m.upbound.io crossplane-system/net-rt (delete) + ⚠ failing (Synced=False, ReconcileError): gone + +Plan: 0 to add, 0 to change, 1 to destroy. +Health: 1 resource failing (Synced=False). +`, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + r, _ := NewRenderer(plan.FormatPlan, tc.args.full) + var buf bytes.Buffer + if err := r.Render(&buf, tc.args.r); err != nil { + t.Fatalf("\n%s\nRender(plan): unexpected error: %v", tc.reason, err) + } + if diff := cmp.Diff(tc.want, buf.String()); diff != "" { + t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestResultFailing(t *testing.T) { + xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod"} + failing := &health.Health{State: health.Failing} + notReady := &health.Health{State: health.NotReady} + + type args struct { + r Result + } + cases := map[string]struct { + reason string + args args + want bool + }{ + "Healthy": { + reason: "A run with nothing failing sets no exit bit.", + args: args{r: NewResult([]*plan.ResourcePlan{{Kind: "ConfigMap", Name: "cm", Action: plan.ActionUpdate}}, []CompositeResult{{Ref: xr}}, nil)}, + }, + "NotReadyAndPaused": { + reason: "Only failing counts: not ready and paused resources don't.", + args: args{r: NewResult( + []*plan.ResourcePlan{{Kind: "ConfigMap", Name: "cm", Health: notReady}}, + []CompositeResult{{Ref: xr, Health: notReady, Unhealthy: []UnhealthyResource{{Ref: xr, Health: &health.Health{State: health.Paused}}}}}, nil)}, + }, + "FailingComposite": { + reason: "A failing composite counts.", + args: args{r: NewResult(nil, []CompositeResult{{Ref: xr, Health: failing}}, nil)}, + want: true, + }, + "FailingUnchanged": { + reason: "A failing resource without changes counts.", + args: args{r: NewResult(nil, []CompositeResult{{Ref: xr, Unhealthy: []UnhealthyResource{{Ref: xr, Health: failing}}}}, nil)}, + want: true, + }, + "FailingDelete": { + reason: "A failing resource the plan deletes counts.", + args: args{r: NewResult([]*plan.ResourcePlan{{Kind: "ConfigMap", Name: "cm", Action: plan.ActionDelete, Health: failing}}, nil, nil)}, + want: true, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + if got := tc.args.r.Failing(); got != tc.want { + t.Errorf("\n%s\nFailing(): want %t, got %t", tc.reason, tc.want, got) + } + }) + } +} diff --git a/internal/simulate/run.go b/internal/simulate/run.go index 88e342fa..ec235660 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -56,6 +56,7 @@ import ( "github.com/crossplane/cli/v2/internal/docker" "github.com/crossplane/cli/v2/internal/exitcode" "github.com/crossplane/cli/v2/internal/kube" + "github.com/crossplane/cli/v2/internal/plan" "github.com/crossplane/cli/v2/internal/project" "github.com/crossplane/cli/v2/internal/terminal" clixpkg "github.com/crossplane/cli/v2/internal/xpkg" @@ -216,8 +217,8 @@ func changedFunctions(ctx context.Context, rc k8client.ResourceClient, digests m // diffCompositions returns the diff simulate runs for Compositions: their // impact on the composite resources in scope, rendered to k's writers. // Errors are wrapped with msg. -func (c *Runner) diffCompositions(k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter, progress *dp.Progress, proc dp.CompDiffProcessor, comps []*un.Unstructured, msg string) func(context.Context) (bool, error) { - return func(ctx context.Context) (bool, error) { +func (c *Runner) diffCompositions(k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter, progress *dp.Progress, proc dp.CompDiffProcessor, comps []*un.Unstructured, msg string) func(context.Context) (outcome, error) { + return func(ctx context.Context) (outcome, error) { var output *dt.CompDiffOutput var err error simulateWithProgress(sp, progress, func() { @@ -227,11 +228,11 @@ func (c *Runner) diffCompositions(k *kong.Context, logger logging.Logger, sp ter // Render the report even when there are errors (e.g. every // composition failed), so structured output stays valid. A render // failure is joined with the processing error, so neither is lost. - changed := output != nil && output.HasChanges() + var o outcome if output != nil { - changed, err = c.renderCompReport(k, logger, output, err) + o, err = c.renderCompReport(k, logger, output, err) } - return changed, errors.Wrap(err, msg) + return o, errors.Wrap(err, msg) } } @@ -240,10 +241,10 @@ func (c *Runner) diffCompositions(k *kong.Context, logger logging.Logger, sp ter // crossplane-diff's xr command. A claim is simulated as its XR, but the // report names the input, so its result is listed under the claim's name // (crossplane/cli#367). -func (c *Runner) diffComposites(k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter, progress *dp.Progress, proc dp.DiffProcessor, xp *xpclient.Clients, ns string, xrs []*un.Unstructured) func(context.Context) (bool, error) { - return func(ctx context.Context) (bool, error) { +func (c *Runner) diffComposites(k *kong.Context, logger logging.Logger, sp terminal.SpinnerPrinter, progress *dp.Progress, proc dp.DiffProcessor, xp *xpclient.Clients, ns string, xrs []*un.Unstructured) func(context.Context) (outcome, error) { + return func(ctx context.Context) (outcome, error) { if err := checkComposites(ctx, xp.Definition, ns, xrs); err != nil { - return false, err + return outcome{}, err } var report *dt.XRReport var err error @@ -254,11 +255,11 @@ func (c *Runner) diffComposites(k *kong.Context, logger logging.Logger, sp termi // Render the report even when there are errors, so successful XRs // are shown and structured output stays valid. The renderer // includes the errors in structured output. - changed := report != nil && report.HasChanges() + var o outcome if report != nil { - changed, err = c.renderXRReport(k, logger, report, err) + o, err = c.renderXRReport(k, logger, report, err) } - return changed, errors.Wrap(err, "cannot simulate composite resources") + return o, errors.Wrap(err, "cannot simulate composite resources") } } @@ -274,6 +275,16 @@ func setFlags(k *kong.Context) map[string]bool { return set } +// outcome is what a diff found that sets the exit status of a run without +// errors. +type outcome struct { + // changed is whether the run changed anything, provider plans included. + changed bool + // failing is whether a composite or a resource it composes was failing + // (Synced=False) before apply. + failing bool +} + // processor is what simulate initializes and cleans up around a diff. type processor interface { Initialize(ctx context.Context) error @@ -306,12 +317,13 @@ func simulateWithProgress(sp terminal.SpinnerPrinter, progress *dp.Progress, fn }) } -// simulate initializes the clients and processor and runs diff. A run that -// finds changes and fails nothing returns a silent ExitError that -// exits 3; one that fails only schema validation returns one that exits 2. +// simulate initializes the clients and processor and runs diff. A run without +// errors that finds changes or a failing resource returns a silent ExitError +// that exits 3, 4 or 7 (see DetermineExitCode); one that fails only schema +// validation returns one that exits 2. // ctx must not be cancelled by its owner until simulate returns, so a // cancellation reads as an interrupt. -func (c *Runner) simulate(ctx context.Context, logger logging.Logger, initClients func(context.Context, logging.Logger) error, proc processor, diff func(context.Context) (bool, error)) (err error) { +func (c *Runner) simulate(ctx context.Context, logger logging.Logger, initClients func(context.Context, logging.Logger) error, proc processor, diff func(context.Context) (outcome, error)) (err error) { // An interrupted run reports the interruption, not the cancelled calls it // caused. main exits 130 for it. defer func() { @@ -330,18 +342,26 @@ func (c *Runner) simulate(ctx context.Context, logger logging.Logger, initClient return errors.Wrap(err, "cannot initialize diff processor") } - // Exit codes rank by severity: a tool error (1) over schema - // validation (2) over changes found (3) over success (0). - hasDiffs, err := diff(ctx) - switch dp.DetermineExitCode(err, hasDiffs) { + // Errors rank by severity: a tool error (1) over schema validation (2). + // Without one, changes found (3) and a failing resource (4) are bits. + o, err := diff(ctx) + switch code := dp.DetermineExitCode(err, o.changed, o.failing); code { + case dp.ExitCodeSuccess, dp.ExitCodeToolError, dp.ExitCodeInterrupted: + return err case dp.ExitCodeSchemaValidation: return exitcode.ExitError{Err: err, Code: ExitCodeSchemaValidation} - case dp.ExitCodeDiffDetected: - // Changes found are a result, not an error, so nothing is printed. - return exitcode.ExitError{Code: ExitCodeChanges} + default: + // Changes found and failing resources are results, not errors, so + // nothing is printed. + ec := 0 + if code&dp.ExitCodeDiffDetected != 0 { + ec |= ExitCodeChanges + } + if code&dp.ExitCodeFailing != 0 { + ec |= ExitCodeFailing + } + return exitcode.ExitError{Code: ec} } - - return err } // scope returns the namespace and composite resource refs DiffComposition @@ -456,6 +476,7 @@ func (c *Runner) diffOptions(k *kong.Context) renderer.DiffOptions { opts := renderer.DefaultDiffOptions() opts.UseColors = !c.NoColor && (c.Hooks != nil && c.Hooks.Terminal || isTerminal(k.Stdout)) opts.Compact = c.Compact + opts.FullMessages = c.FullMessages opts.Stdout = k.Stdout opts.Stderr = k.Stderr return opts @@ -492,7 +513,7 @@ func (c *Runner) notes() []string { // renderXRReport writes an xr run's report in the format -o selects, as // renderReport does. -func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XRReport, runErr error) (bool, error) { +func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XRReport, runErr error) (outcome, error) { plans := c.providerPlans() return c.renderReport(k, logger, runErr, FromXRReport(r, plans, c.keep), r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { // Annotated even without plans, so a Secret's values are redacted. @@ -503,7 +524,7 @@ func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XR // renderCompReport writes a composition run's report in the format -o // selects, as renderReport does. -func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt.CompDiffOutput, runErr error) (bool, error) { +func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt.CompDiffOutput, runErr error) (outcome, error) { plans := c.providerPlans() return c.renderReport(k, logger, runErr, FromCompReport(o, plans, c.keep), o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { opts.MinimizeComposition = c.sel.MinimizeComposition @@ -515,10 +536,11 @@ func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt. // renderReport writes a run's report in the format -o selects: renderDiff's // human diff for diff, and res otherwise, followed by warnings. It returns -// whether the run changed anything, provider plans included, and runErr -// with any render failure joined to it, so neither is lost. changed is -// whether the report itself has changes. -func (c *Runner) renderReport(k *kong.Context, logger logging.Logger, runErr error, res Result, changed bool, warnings []dt.OutputWarning, renderDiff func(renderer.DiffOptions) error) (bool, error) { +// the run's outcome: whether it changed anything, provider plans included, +// and whether anything was failing; and runErr with any render failure +// joined to it, so neither is lost. changed is whether the report itself +// has changes. +func (c *Runner) renderReport(k *kong.Context, logger logging.Logger, runErr error, res Result, changed bool, warnings []dt.OutputWarning, renderDiff func(renderer.DiffOptions) error) (outcome, error) { opts := c.diffOptions(k) plans := c.providerPlans() if plans != nil { @@ -529,7 +551,7 @@ func (c *Runner) renderReport(k *kong.Context, logger logging.Logger, runErr err res.Notes = n } c.noteNoServers(k, n) - changed = changed || (plans != nil && res.Summary.Changes() > 0) + o := outcome{changed: changed || (plans != nil && res.Summary.Changes() > 0), failing: res.Failing()} var err error if c.Output == string(renderer.OutputFormatDiff) { @@ -539,9 +561,9 @@ func (c *Runner) renderReport(k *kong.Context, logger logging.Logger, runErr err } if err != nil { logger.Debug("Failed to render diffs", "error", err) - return changed, withRenderError(runErr, errors.Wrap(err, "failed to render diffs")) + return o, withRenderError(runErr, errors.Wrap(err, "failed to render diffs")) } - return changed, runErr + return o, runErr } // renderPlan writes res to stdout in the plan, json or yaml format, then @@ -549,7 +571,7 @@ func (c *Runner) renderReport(k *kong.Context, logger logging.Logger, runErr err // engine's renderers do. The run's other warnings went to stderr when they // were raised. func (c *Runner) renderPlan(k *kong.Context, res Result, derived []dt.OutputWarning) error { - r, err := NewRenderer(c.Output) + r, err := NewRenderer(c.Output, c.FullMessages) if err != nil { return err } @@ -618,7 +640,7 @@ func (c *Runner) Run(sigCtx context.Context, k *kong.Context, logger logging.Log c.sel = *in.Selection } project := in.Build != nil - warnIgnoredFlags(k.Stderr, setFlags(k), c.SkipPlan, project) + warnIgnoredFlags(k.Stderr, setFlags(k), c.Output, c.SkipPlan, project) if err := docker.Check(sigCtx); err != nil { return errors.Wrap(err, "cannot connect to Docker, which simulate needs to run functions") @@ -723,8 +745,10 @@ func (c *Flags) flagImageConfigs() ([]pkgv1beta1.ImageConfig, error) { // warnIgnoredFlags prints a warning to stderr for each flag set on the // command line that does nothing in this run: --skip-plan runs no diff // servers, so --providers and --session-id do nothing with it, and -// --cache-dir caches nothing with --skip-plan unless the run builds a project. -func warnIgnoredFlags(stderr io.Writer, set map[string]bool, skipPlan, project bool) { +// --cache-dir caches nothing with --skip-plan unless the run builds a project, +// and --full-messages changes nothing in json or yaml output, which always +// carries messages in full. +func warnIgnoredFlags(stderr io.Writer, set map[string]bool, output string, skipPlan, project bool) { for _, f := range []string{"providers", "session-id"} { if skipPlan && set[f] { _, _ = fmt.Fprintf(stderr, "Warning: ignoring --%s; --skip-plan runs no diff servers.\n", f) @@ -733,6 +757,9 @@ func warnIgnoredFlags(stderr io.Writer, set map[string]bool, skipPlan, project b if !project && skipPlan && set["cache-dir"] { _, _ = fmt.Fprintln(stderr, "Warning: ignoring --cache-dir; with --skip-plan and no project file there is nothing to cache.") } + if set["full-messages"] && (output == plan.FormatJSON || output == plan.FormatYAML) { + _, _ = fmt.Fprintf(stderr, "Warning: ignoring --full-messages; -o %s always prints messages in full.\n", output) + } } // Built is a built project: what Inputs.Build returns. diff --git a/internal/simulate/run_test.go b/internal/simulate/run_test.go index 699246b5..322f8938 100644 --- a/internal/simulate/run_test.go +++ b/internal/simulate/run_test.go @@ -51,6 +51,7 @@ import ( "github.com/crossplane/cli/v2/internal/diff/testutils" difftypes "github.com/crossplane/cli/v2/internal/diff/types" "github.com/crossplane/cli/v2/internal/exitcode" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" "github.com/crossplane/cli/v2/internal/terminal" xprender "github.com/crossplane/cli/v2/pkg/render" @@ -312,6 +313,14 @@ func TestSimulateDiffOptions(t *testing.T) { o.Compact = true }, }, + "FullMessagesCarryThrough": { + reason: "--full-messages should reach the renderer.", + cmd: Flags{NoColor: true, FullMessages: true}, + want: func(o *renderer.DiffOptions) { + o.UseColors = false + o.FullMessages = true + }, + }, "HooksColorizeAsTerminal": { reason: "The test hooks should colorize as for a terminal.", cmd: Flags{Hooks: &Hooks{Terminal: true}}, @@ -574,6 +583,19 @@ func TestSimulateRun(t *testing.T) { }}} } + // failing is a report of one Composition whose affected composite, in + // status, is failing before apply. + failing := func(status dt.XRStatus) *dt.CompDiffOutput { + return &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{{ + Name: "comp", + ImpactAnalysis: []dt.XRImpact{{ + APIVersion: "example.org/v1", Kind: "XDB", Name: "db", + Status: status, + Health: dt.CompositeHealth{XR: &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse}}}, + }}, + }}} + } + type args struct { cmd Runner initClients func(context.Context, logging.Logger) error @@ -608,6 +630,34 @@ func TestSimulateRun(t *testing.T) { }}}, want: want{code: dp.ExitCodeDiffDetected, diffed: true}, }, + "Failing": { + reason: "A run without changes whose composite is failing should exit 4, silently.", + args: args{initClients: noInit, proc: &fakeCompProc{diffFn: func(context.Context) (*dt.CompDiffOutput, error) { + return failing(dt.XRStatusUnchanged), nil + }}}, + want: want{code: ExitCodeFailing, diffed: true}, + }, + "ChangesAndFailing": { + reason: "A run with changes whose composite is failing should exit 7, silently.", + args: args{initClients: noInit, proc: &fakeCompProc{diffFn: func(context.Context) (*dt.CompDiffOutput, error) { + return failing(dt.XRStatusChanged), nil + }}}, + want: want{code: ExitCodeChanges | ExitCodeFailing, diffed: true}, + }, + "FailingDiffOutput": { + reason: "The failing bit should not depend on the output format.", + args: args{cmd: Runner{Flags: &Flags{Output: "diff"}}, initClients: noInit, proc: &fakeCompProc{diffFn: func(context.Context) (*dt.CompDiffOutput, error) { + return failing(dt.XRStatusUnchanged), nil + }}}, + want: want{code: ExitCodeFailing, diffed: true}, + }, + "ErrorOutranksFailing": { + reason: "A tool error should exit 1 even when a composite is failing.", + args: args{initClients: noInit, proc: &fakeCompProc{diffFn: func(context.Context) (*dt.CompDiffOutput, error) { + return failing(dt.XRStatusChanged), errBoom + }}}, + want: want{code: dp.ExitCodeToolError, err: errBoom, diffed: true}, + }, "ErrorWithChanges": { reason: "A tool error should exit 1, not 3, even when there are changes.", args: args{initClients: noInit, proc: &fakeCompProc{diffFn: func(context.Context) (*dt.CompDiffOutput, error) { @@ -745,6 +795,7 @@ func TestWarnIgnoredFlags(t *testing.T) { cases := map[string]struct { reason string args []string + output string skipPlan bool project bool warn string @@ -783,6 +834,28 @@ func TestWarnIgnoredFlags(t *testing.T) { skipPlan: true, warn: "ignoring --session-id", }, + "FullMessagesPlan": { + reason: "--full-messages applies to plan output.", + args: []string{"--full-messages"}, + output: "plan", + }, + "FullMessagesDiff": { + reason: "--full-messages applies to diff output.", + args: []string{"--full-messages"}, + output: "diff", + }, + "FullMessagesJSON": { + reason: "json always carries messages in full, so --full-messages is ignored with a warning.", + args: []string{"--full-messages"}, + output: "json", + warn: "ignoring --full-messages; -o json", + }, + "FullMessagesYAML": { + reason: "yaml always carries messages in full, so --full-messages is ignored with a warning.", + args: []string{"--full-messages"}, + output: "yaml", + warn: "ignoring --full-messages; -o yaml", + }, "DefaultsAreNotSet": { reason: "Flags left at their defaults, or set from the environment, are not warned about.", skipPlan: true, @@ -809,7 +882,7 @@ func TestWarnIgnoredFlags(t *testing.T) { } var stderr bytes.Buffer - warnIgnoredFlags(&stderr, setFlags(k), tc.skipPlan, tc.project) + warnIgnoredFlags(&stderr, setFlags(k), tc.output, tc.skipPlan, tc.project) if tc.warn == "" && stderr.Len() > 0 || !strings.Contains(stderr.String(), tc.warn) { t.Errorf("\n%s\nwarnIgnoredFlags(...): want warning containing %q, got %q", tc.reason, tc.warn, stderr.String()) } diff --git a/internal/simulate/simtest/plan_assertions.go b/internal/simulate/simtest/plan_assertions.go index e3582028..e40cb309 100644 --- a/internal/simulate/simtest/plan_assertions.go +++ b/internal/simulate/simtest/plan_assertions.go @@ -103,6 +103,61 @@ func AssertStructured(t *testing.T, jsonOutput string, e Expectation) { for _, want := range expected.compositions { assertComposition(t, res, want) } + + if want := expected.health; want != nil { + assertHealthSummary(t, jsonOutput, *want) + } +} + +// assertHealthSummary checks summary.health, which simulate.Result computes on marshal and so does not +// read back. +func assertHealthSummary(t *testing.T, jsonOutput string, want expectedHealth) { + t.Helper() + + var out struct { + Summary struct { + Health simulate.HealthSummary `json:"health"` + } `json:"summary"` + } + if err := json.Unmarshal([]byte(jsonOutput), &out); err != nil { + t.Fatalf("failed to parse summary.health: %v", err) + } + + got := out.Summary.Health + if g := (expectedHealth{composites: got.Composites, failing: got.Failing, notReady: got.NotReady, paused: got.Paused}); g != want { + t.Errorf("summary.health: expected %+v, got %+v", want, g) + } +} + +// assertXRHealth checks an xrs[] entry's health state and its unhealthy[] entries. +func assertXRHealth(t *testing.T, label string, got simulate.CompositeResult, want *XRExpectation) { + t.Helper() + + if want.health != "" { + state := "" + if got.Health != nil { + state = string(got.Health.State) + } + if state != want.health { + t.Errorf("xr %s: health: expected %q, got %q", label, want.health, state) + } + } + + if len(want.unhealthy) == 0 { + return + } + + gotU := make([]unhealthyExpectation, 0, len(got.Unhealthy)) + for _, u := range got.Unhealthy { + e := unhealthyExpectation{kind: u.Ref.Kind, name: u.Ref.Name} + if u.Health != nil { + e.state = string(u.Health.State) + } + gotU = append(gotU, e) + } + if !slices.Equal(gotU, want.unhealthy) { + t.Errorf("xr %s: unhealthy: expected %+v, got %+v", label, want.unhealthy, gotU) + } } func assertComposition(t *testing.T, res simulate.Result, want *CompositionExpectation) { @@ -357,6 +412,8 @@ func assertXRExpectations(t *testing.T, res simulate.Result, expected []*XRExpec t.Errorf("xr %s: status: expected %q, got %q", label, want.status, got.Status) } + assertXRHealth(t, label, got, want) + changes := changePlans(res.Plans, groupedUnder(got.Ref)) if s := want.summary; s != nil { diff --git a/internal/simulate/simtest/structured_assertions.go b/internal/simulate/simtest/structured_assertions.go index 13d759cd..93c7d747 100644 --- a/internal/simulate/simtest/structured_assertions.go +++ b/internal/simulate/simtest/structured_assertions.go @@ -30,6 +30,18 @@ type Expected struct { // noWarnings asserts warnings[] is empty. Separate from len(warnings)==0, which means "no opinion". noWarnings bool xrs []*XRExpectation + // health is summary.health, asserted when set. + health *expectedHealth +} + +// expectedHealth is summary.health's counts. +type expectedHealth struct { + composites, failing, notReady, paused int +} + +// unhealthyExpectation is one entry of an xrs[] entry's unhealthy[]. +type unhealthyExpectation struct { + kind, name, state string } // warningMatch describes one expected entry in warnings[], shared by the xr and comp builders. Matched @@ -436,6 +448,10 @@ type XRExpectation struct { summary *expectedSummary changes []*ResourceExpectation errorIDs []string + // health is the entry's live health state, asserted when set. + health string + // unhealthy pins the entry's unhealthy[] when set. + unhealthy []unhealthyExpectation } // XR begins a standalone expectation for one xrs[] entry, keyed by the input @@ -509,6 +525,26 @@ func (x *XRExpectation) Change(changeType, kind, name, namespace string) *Resour return r } +// WithHealthSummary asserts summary.health: the unhealthy top-level composites, and the failing, not +// ready and paused resources. +func (e *Expected) WithHealthSummary(composites, failing, notReady, paused int) *Expected { + e.health = &expectedHealth{composites: composites, failing: failing, notReady: notReady, paused: paused} + return e +} + +// Health asserts the entry's live health state (paused, failing, notReady or healthy). +func (x *XRExpectation) Health(state string) *XRExpectation { + x.health = state + return x +} + +// Unhealthy asserts the entry's unhealthy[] holds a resource of this kind and name in this health +// state. Pinning any pins the count too. +func (x *XRExpectation) Unhealthy(kind, name, state string) *XRExpectation { + x.unhealthy = append(x.unhealthy, unhealthyExpectation{kind: kind, name: name, state: state}) + return x +} + // WithErrorID asserts the top-level errors[] contains an error with the given resourceID. Unlike // WithError it pins neither the error's details nor the error count. func (e *Expected) WithErrorID(resourceID string) *Expected { diff --git a/internal/testutils/integration/fixtures.go b/internal/testutils/integration/fixtures.go index 9e690bc5..178b1d18 100644 --- a/internal/testutils/integration/fixtures.go +++ b/internal/testutils/integration/fixtures.go @@ -32,6 +32,7 @@ import ( authorizationv1 "k8s.io/api/authorization/v1" rbacv1 "k8s.io/api/rbac/v1" extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" + "k8s.io/apimachinery/pkg/api/equality" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -640,12 +641,34 @@ func createResourceFromFile(ctx context.Context, c client.Client, d *crossplaneD } } + if err := writeStatus(ctx, c, resource, serverResource); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } + // Store and return the created resource createdResources[path] = serverResource return serverResource, nil } +// writeStatus writes want's status to server, the object as created from want, through the status +// subresource when creating it dropped the status, as it does for a type with that subresource, such as +// an XR. Under envtest no controller writes status, so this is how a fixture carries live conditions. +// server is updated in place. +func writeStatus(ctx context.Context, c client.Client, want, server *un.Unstructured) error { + status, ok := want.Object["status"] + if !ok || equality.Semantic.DeepEqual(status, server.Object["status"]) { + return nil + } + + server.Object["status"] = status + if err := c.Status().Update(ctx, server); err != nil { + return fmt.Errorf("cannot write status: %w", err) + } + + return nil +} + // withoutCompositeReconcilerFields returns a copy of resource without the compositeReconcilerFields it // sets, and those fields' values keyed by their index in compositeReconcilerFields. resource is not // mutated. diff --git a/internal/testutils/integration/simharness/cases.go b/internal/testutils/integration/simharness/cases.go index 4fe44816..8f2e07ff 100644 --- a/internal/testutils/integration/simharness/cases.go +++ b/internal/testutils/integration/simharness/cases.go @@ -76,7 +76,7 @@ type IntegrationTestCase struct { ExpectedError bool ExpectedErrorContains string ExpectedStderrContains []string // substrings that must appear on stderr (warnings, error lines) - ExpectedExitCode int // Expected exit code (0=success, 1=tool error, 2=schema validation, 3=diff detected) + ExpectedExitCode int // Expected exit code (0=success, 1=tool error, 2=schema validation; without an error, 3=diff detected, 4=failing resource, 7=both) NoColor bool Namespace string // For composition tests (optional) XrdAPIVersion integration.XRDAPIVersion // For XR tests (optional) diff --git a/internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml b/internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml new file mode 100644 index 00000000..596383ba --- /dev/null +++ b/internal/testutils/integration/testdata/comp/resources/existing-downstream-1-not-ready.yaml @@ -0,0 +1,18 @@ +# existing-downstream-1.yaml while its provider is still creating it: Ready=False, so it is not ready. +apiVersion: ns.nop.example.org/v1alpha1 +kind: XDownstreamResource +metadata: + name: test-resource + namespace: default + annotations: + crossplane.io/composition-resource-name: nop-resource +spec: + forProvider: + configData: existing-value + resourceTier: basic +status: + conditions: + - type: Ready + status: "False" + reason: Creating + lastTransitionTime: "2024-01-01T00:00:00Z" diff --git a/internal/testutils/integration/testdata/comp/resources/existing-downstream-2-paused-annotation.yaml b/internal/testutils/integration/testdata/comp/resources/existing-downstream-2-paused-annotation.yaml new file mode 100644 index 00000000..568bd163 --- /dev/null +++ b/internal/testutils/integration/testdata/comp/resources/existing-downstream-2-paused-annotation.yaml @@ -0,0 +1,9 @@ +# Pauses existing-downstream-2.yaml's resource. Applied under a non-Crossplane field manager, as a +# user or tool would, so Crossplane's dry-run apply does not remove the annotation. +apiVersion: ns.nop.example.org/v1alpha1 +kind: XDownstreamResource +metadata: + name: another-resource + namespace: default + annotations: + crossplane.io/paused: "true" diff --git a/internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml b/internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml new file mode 100644 index 00000000..b1a2fdca --- /dev/null +++ b/internal/testutils/integration/testdata/comp/resources/existing-xr-1-failing.yaml @@ -0,0 +1,19 @@ +# existing-xr-1.yaml as Crossplane reports it once its composed resources cannot sync: Synced=False, +# so the XR is failing. Fixture setup writes the status through the status subresource. +apiVersion: ns.diff.example.org/v1alpha1 +kind: XNopResource +metadata: + name: test-resource + namespace: default +spec: + coolField: existing-value + crossplane: + compositionRef: + name: xnopresources.diff.example.org +status: + conditions: + - type: Synced + status: "False" + reason: ReconcileError + message: "cannot compose resources: the vpc does not exist" + lastTransitionTime: "2024-01-01T00:00:00Z" diff --git a/internal/testutils/integration/testdata/diff/resources/existing-downstream-resource-not-ready.yaml b/internal/testutils/integration/testdata/diff/resources/existing-downstream-resource-not-ready.yaml new file mode 100644 index 00000000..9421bab8 --- /dev/null +++ b/internal/testutils/integration/testdata/diff/resources/existing-downstream-resource-not-ready.yaml @@ -0,0 +1,20 @@ +# existing-downstream-resource.yaml while its provider is still creating it: Ready=False, so it is +# not ready. +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 +status: + conditions: + - type: Ready + status: "False" + reason: Creating + lastTransitionTime: "2024-01-01T00:00:00Z" diff --git a/internal/testutils/integration/testdata/diff/resources/existing-xr-failing.yaml b/internal/testutils/integration/testdata/diff/resources/existing-xr-failing.yaml new file mode 100644 index 00000000..0fa35e38 --- /dev/null +++ b/internal/testutils/integration/testdata/diff/resources/existing-xr-failing.yaml @@ -0,0 +1,20 @@ +# existing-xr.yaml as Crossplane reports it once its composed resources cannot sync: Synced=False, so +# the XR is failing. Fixture setup writes the status through the status subresource. +apiVersion: ns.diff.example.org/v1alpha1 +kind: XNopResource +metadata: + name: test-resource + namespace: default +spec: + coolField: "existing-value" + crossplane: + compositionRef: + name: xnopresources.diff.example.org + compositionUpdatePolicy: Automatic +status: + conditions: + - type: Synced + status: "False" + reason: ReconcileError + message: "cannot compose resources: the vpc does not exist" + lastTransitionTime: "2024-01-01T00:00:00Z"