diff --git a/cmd/crossplane/simulate/simulate.go b/cmd/crossplane/simulate/simulate.go index 82b6b3016..304a6046a 100644 --- a/cmd/crossplane/simulate/simulate.go +++ b/cmd/crossplane/simulate/simulate.go @@ -192,7 +192,7 @@ func exitStatus(plans []*plan.ResourcePlan) error { if s.Changes() > 0 { code |= isimulate.ExitCodeChanges } - if plan.Failing(plans) { + if plan.HealthRun(plans).Failing { code |= isimulate.ExitCodeFailing } if code == 0 { diff --git a/cmd/crossplane/simulate/simulate_test.go b/cmd/crossplane/simulate/simulate_test.go index c16147cdd..c327ad058 100644 --- a/cmd/crossplane/simulate/simulate_test.go +++ b/cmd/crossplane/simulate/simulate_test.go @@ -27,6 +27,7 @@ import ( "github.com/crossplane/cli/v2/internal/exitcode" "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" + isimulate "github.com/crossplane/cli/v2/internal/simulate" ) func TestExitStatus(t *testing.T) { @@ -78,6 +79,26 @@ func TestExitStatus(t *testing.T) { }}, want: 0, }, + "BitsNone": { + reason: "Neither the changes bits (1|2) nor the failing bit 4 set: exit 0.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionNoOp, Health: &health.Health{State: health.Healthy}}}}, + want: 0, + }, + "BitsChangesOnly": { + reason: "Only the changes bits 1|2 set: exit 3. Failing agrees with the Health: line counting no failing resource.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionCreate}, {Action: plan.ActionNoOp, Health: &health.Health{State: health.Paused}}}}, + want: 3, + }, + "BitsFailingOnly": { + reason: "Only the failing bit 4 set: exit 4.", + args: args{plans: []*plan.ResourcePlan{{Kind: "VPC", Name: "a", Action: plan.ActionNoOp, Health: failing}, {Kind: "VPC", Name: "b", Action: plan.ActionNoOp, Health: &health.Health{State: health.NotReady}}}}, + want: 4, + }, + "BitsBoth": { + reason: "The changes bits 1|2 and the failing bit 4 set: exit 7, even when the failing resource is the one deleted.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionDelete, Health: failing}}}, + want: 7, + }, "ErroredWithFailing": { reason: "An errored plan should exit 1, not 4 or 7, even when a resource is failing.", args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionUpdate, Health: failing}, {Error: "boom"}}}, @@ -98,6 +119,9 @@ func TestExitStatus(t *testing.T) { if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("\n%s\nexitStatus(...): -want exit code, +got:\n%s", tc.reason, diff) } + if bit, line := got != 1 && got&isimulate.ExitCodeFailing != 0, plan.HealthRun(tc.args.plans).Counts.Failing > 0 && got != 1; bit != line { + t.Errorf("\n%s\nexit bit 4 = %t, but the Health: line counts failing = %t", tc.reason, bit, line) + } }) } } diff --git a/internal/diff/renderer/comp_diff_renderer.go b/internal/diff/renderer/comp_diff_renderer.go index 424038944..2052c59d3 100644 --- a/internal/diff/renderer/comp_diff_renderer.go +++ b/internal/diff/renderer/comp_diff_renderer.go @@ -67,7 +67,17 @@ 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) + impacts := 0 + for _, comp := range output.Compositions { + impacts += len(comp.ImpactAnalysis) + } + + allOwned, counts, err := runHealth(r.opts, impacts) + if err != nil { + return err + } + + base := 0 for i, comp := range output.Compositions { if i > 0 { @@ -76,21 +86,16 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro } } - if err := r.renderComposition(&comp, ownedElsewhere); err != nil { + owned := allOwned[base : base+len(comp.ImpactAnalysis)] + base += len(comp.ImpactAnalysis) + + if err := r.renderComposition(&comp, owned); 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 line := health.SummaryLine(counts); line != "" { if _, err := fmt.Fprintf(stdout, "\n%s\n", line); err != nil { return errors.Wrap(err, "cannot write health summary") } @@ -105,7 +110,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, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, owned [][]int) error { switch { case r.opts.MinimizeComposition: if err := r.renderMinimizedCompositionChanges(comp); err != nil { @@ -118,7 +123,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ow } if comp.Error == nil { - return r.renderCompositionImpact(comp, ownedElsewhere) + return r.renderCompositionImpact(comp, owned) } return nil @@ -127,7 +132,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ow // 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, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDiff, owned [][]int) error { if comp.ImpactAnalysisSkipped { return r.renderSkippedComposition(comp) } @@ -144,7 +149,7 @@ func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDi } // Render impact analysis (downstream diffs) - return r.renderImpactAnalysis(comp, ownedElsewhere) + return r.renderImpactAnalysis(comp, owned) } // renderSkippedComposition stands in for the affected-XR and impact-analysis sections when a @@ -364,19 +369,20 @@ func (r *DefaultCompDiffRenderer) renderMinimizedCompositionChanges(comp *dt.Com // them: the user asked about those composites by name. Default discovery reports them only through // the AffectedResources filter counters. func listedImpacts(comp *dt.CompositionDiff) []dt.XRImpact { - if comp.Scoped { - return comp.ImpactAnalysis - } - - listed := make([]dt.XRImpact, 0, len(comp.ImpactAnalysis)) + out := make([]dt.XRImpact, 0, len(comp.ImpactAnalysis)) for _, impact := range comp.ImpactAnalysis { - if impact.Status != dt.XRStatusFiltered { - listed = append(listed, impact) + if listed(comp, impact) { + out = append(out, impact) } } - return listed + return out +} + +// listed reports whether the output lists impact one by one; see listedImpacts. +func listed(comp *dt.CompositionDiff, impact dt.XRImpact) bool { + return comp.Scoped || impact.Status != dt.XRStatusFiltered } // renderAffectedResourcesList renders the affected XRs list with status indicators. @@ -421,7 +427,7 @@ func (r *DefaultCompDiffRenderer) renderAffectedResourcesList(comp *dt.Compositi } // renderImpactAnalysis renders the impact analysis section with downstream diffs. -func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, owned [][]int) error { stdout := r.opts.Stdout if _, err := fmt.Fprintf(stdout, headerImpactAnalysis+"\n\n"); err != nil { @@ -456,18 +462,22 @@ func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, } } - return r.renderUnhealthyBlocks(comp, ownedElsewhere, len(allDiffs) > 0) + return r.renderUnhealthyBlocks(comp, owned, 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 { +func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff, owned [][]int, 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) + for i, impact := range comp.ImpactAnalysis { + if !listed(comp, impact) { + continue + } + + block := ownedBlock(impact.Health, owned[i], impact.Diffs, r.opts.FullMessages) if len(block) == 0 { continue } @@ -486,32 +496,6 @@ func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff 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 { diff --git a/internal/diff/renderer/diff_formatter.go b/internal/diff/renderer/diff_formatter.go index 0164944be..a6cb59ce3 100644 --- a/internal/diff/renderer/diff_formatter.go +++ b/internal/diff/renderer/diff_formatter.go @@ -10,6 +10,7 @@ import ( "github.com/sergi/go-diff/diffmatchpatch" t "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" ) // DiffOptions holds configuration options for the diff output. @@ -54,6 +55,13 @@ type DiffOptions struct { // FullMessages prints health condition messages in full, wrapped, rather // than cut to one line. FullMessages bool + + // Health, when set, is the run's health: one composite per group of the + // xr diff, or per impact of each composition of the composition diff, in + // order. It gives which composite lists each unhealthy resource, and the + // Health: line's counts. Nil prints no Health: line and no unhealthy + // resources blocks. + Health *health.Run } // 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 1947cc465..0902b981f 100644 --- a/internal/diff/renderer/diff_renderer.go +++ b/internal/diff/renderer/diff_renderer.go @@ -270,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), xrGroups) + err = r.renderFlat(groups, xrGroups) } if err != nil { @@ -286,25 +286,29 @@ func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.Out // 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 { +func (r *DefaultDiffRenderer) renderFlat(groups, xrGroups []dt.XRDiffGroup) error { stdout := r.diffOpts.Stdout full := r.diffOpts.FullMessages + diffs := flattenGroups(groups) - var ( - head, block, described string - t health.Tally - ) + var head, block, described, healthLine string if len(xrGroups) == 1 { - g := xrGroups[0] + owned, counts, err := runHealth(r.diffOpts, len(groups)) + if err != nil { + return err + } + + i := slices.IndexFunc(groups, hasIdentity) + g := groups[i] 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) + block = joinLines(ownedBlock(g.Health, owned[i], g.Diffs, full)) + healthLine = joinLines([]string{health.SummaryLine(counts)}) } if err := write(stdout, head); err != nil { @@ -326,7 +330,7 @@ func (r *DefaultDiffRenderer) renderFlat(diffs map[string]*dt.ResourceDiff, xrGr // 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())})} { + for _, s := range []string{block, summaryText(summary), healthLine} { if s == "" || s == "\n" { continue } @@ -376,10 +380,12 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount int unchangedXR int errorXR int - t health.Tally ) - ownedElsewhere := groupsOwnedElsewhere(groups) + owned, healthCounts, err := runHealth(r.diffOpts, len(groups)) + if err != nil { + return err + } for i, g := range groups { // An identity-less group (should not normally be mixed in here) has no @@ -398,9 +404,7 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount++ - tallyComposite(&t, g.XR, g.Health, g.Diffs) - - counts, err := r.renderSection(g, ownedElsewhere[i]) + counts, err := r.renderSection(g, owned[i]) if err != nil { return err } @@ -419,15 +423,15 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { return err } - return writeHealthLine(stdout, &t) + return writeHealthLine(stdout, healthCounts) } // 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) { +// zero for an errored XR. Its unhealthy resources are those of g's composed +// at the indexes in owned, the ones its section lists in the run's health. +func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, owned []int) (diffCounts, error) { stdout := r.diffOpts.Stdout if _, err := fmt.Fprintf(stdout, "=== %s ===\n\n", groupTitle(g)); err != nil { @@ -456,7 +460,7 @@ func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, skip map[string]bo return counts, err } - block := joinLines(unhealthyBlock(g.Health, g.Diffs, skip, r.diffOpts.FullMessages)) + block := joinLines(ownedBlock(g.Health, owned, g.Diffs, r.diffOpts.FullMessages)) if counts.output == 0 { if _, err := fmt.Fprintf(stdout, "No changes.\n\n"); err != nil { diff --git a/internal/diff/renderer/health.go b/internal/diff/renderer/health.go index deba2452f..2d9fe6bc9 100644 --- a/internal/diff/renderer/health.go +++ b/internal/diff/renderer/health.go @@ -28,11 +28,31 @@ 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 { +// ownedBlock returns the lines listing the resources of h.Composed at the +// indexes in owned, the unhealthy ones its entry lists in the run's health, +// that have 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. +func ownedBlock(h dt.CompositeHealth, owned []int, diffs map[string]*dt.ResourceDiff, full bool) []string { + listed := listedDiffs(diffs) + + var items []health.Item + + for _, j := range owned { + r := h.Composed[j] + if listed[refKey(r.ObjectReference)] != "" { + continue + } + + items = append(items, blockItem(r)) + } + + return health.Block(items, listed, full) +} + +// listedDiffs returns, by key, how the diff list names each resource in diffs +// with changes. +func listedDiffs(diffs map[string]*dt.ResourceDiff) map[string]string { listed := map[string]string{} for _, d := range diffs { @@ -41,23 +61,33 @@ func unhealthyBlock(h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff, ski } } - var items []health.Item + return listed +} - for _, r := range h.Composed { - id := refKey(r.ObjectReference) - if !r.Health.Unhealthy() || listed[id] != "" || skip[id] { - continue - } +// blockItem returns r as an item of an unhealthy block. +func blockItem(r dt.ResourceHealth) health.Item { + it := health.Item{ID: refKey(r.ObjectReference), Name: refName(r.ObjectReference), Health: r.Health} + if r.Via != nil { + it.Via, it.ViaName = refKey(*r.Via), refName(*r.Via) + } - 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) - } + return it +} - items = append(items, it) +// runHealth returns, for a run of n composites, which composed resources +// each lists and the Health: line's counts, from opts.Health. When it is nil +// no composite lists any and the counts are zero, so no Health: line prints. +// It returns an error when opts.Health is not for n composites. +func runHealth(opts DiffOptions, n int) ([][]int, health.Counts, error) { + if opts.Health == nil { + return make([][]int, n), health.Counts{}, nil } - return health.Block(items, listed, full) + if len(opts.Health.Owned) != n { + return nil, health.Counts{}, errors.Errorf("run's health has %d composites, but the report has %d", len(opts.Health.Owned), n) + } + + return opts.Health.Owned, opts.Health.Counts, nil } // joinLines returns lines, each ended by a newline, or "" when there are @@ -92,28 +122,10 @@ func healthDescription(h *health.Health, full bool) []string { 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()) +func writeHealthLine(w io.Writer, c health.Counts) error { + line := health.SummaryLine(c) if line == "" { return nil } @@ -122,19 +134,3 @@ func writeHealthLine(w io.Writer, t *health.Tally) error { 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 index 845a936c1..326a7f74d 100644 --- a/internal/diff/renderer/health_test.go +++ b/internal/diff/renderer/health_test.go @@ -2,6 +2,7 @@ package renderer import ( "bytes" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -27,6 +28,70 @@ func liveWith(d *dt.ResourceDiff, msg string) *dt.ResourceDiff { return d } +// equalDiffFor returns modifiedDiffFor's diff marked unchanged. +func equalDiffFor(kind, name string) *dt.ResourceDiff { + d := modifiedDiffFor(kind, name) + d.DiffType = dt.DiffTypeEqual + + return d +} + +// groupsHealth returns the run's health for groups, each a composite, which +// show their diffs themselves, as simulate builds it. An identity-less group +// is an empty composite. +func groupsHealth(groups []dt.XRDiffGroup) *health.Run { + composites := make([]health.Composite, len(groups)) + + var shown []health.Item + + for i, g := range groups { + if !hasIdentity(g) { + continue + } + + composites[i] = health.Composite{Key: refKey(g.XR), Health: g.Health.XR} + for _, r := range g.Health.Composed { + composites[i].Composed = append(composites[i].Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) + } + + for _, d := range g.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } + } + + run := health.Build(composites, shown) + + return &run +} + +// compHealth returns the run's health for comps: every impact of each +// composition in order, each a composite, which shows its diffs itself. +func compHealth(comps []dt.CompositionDiff) *health.Run { + var ( + composites []health.Composite + shown []health.Item + ) + + for _, comp := range comps { + for _, impact := range comp.ImpactAnalysis { + c := health.Composite{Key: refKey(impact.ObjectReference), Health: impact.Health.XR} + for _, r := range impact.Health.Composed { + c.Composed = append(c.Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) + } + + composites = append(composites, c) + + for _, d := range impact.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } + } + } + + run := health.Build(composites, shown) + + return &run +} + 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"}} @@ -195,6 +260,157 @@ Health: 1 resource failing (Synced=False). Summary: 2 modified Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "FlatNested": { + reason: "A single XR's composed health holds the nested XR and what it composes, flattened with Via set; the nested XR is listed and its resource nests under it. With no diffs, the XR: line is followed by two blank lines (its own and the trailer separator).", + args: args{groups: []dt.XRDiffGroup{group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + })}}, + want: `XR: XNetwork/a ⚠ not ready (Ready=False, Creating) + + +Unhealthy resources without changes: + XNetwork/b ⚠ not ready (Ready=False, Creating) + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. +`, + }, + "FlatNestedThreeLevels": { + reason: "A single XR over a 3-level chain A > B > C lists every level, each resource nested under the XR that composes it.", + args: args{groups: []dt.XRDiffGroup{group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("XNetwork", "c"), Via: new(ref("XNetwork", "b")), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + })}}, + want: `XR: XNetwork/a ⚠ not ready (Ready=False, Creating) + + +Unhealthy resources without changes: + XNetwork/b ⚠ not ready (Ready=False, Creating) + XNetwork/c ⚠ not ready (Ready=False, Creating) + Subnet/sn ⚠ failing (Synced=False, ReconcileError): vpc does not exist + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False), 2 not ready. +`, + }, + "GroupedNested": { + reason: "A parent with health of its own and a nested input XR with health: the parent lists only its own resource, the nested XR lists what it composes.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("Bucket", "bk"), Health: failing}, + {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 === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + Bucket/bk ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +=== 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: 2 of 2 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "GroupedNestedThreeLevels": { + reason: "A 3-level chain A > B > C, all inputs with health: each resource is listed once, under the deepest XR that composes it.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("XNetwork", "c"), Via: new(ref("XNetwork", "b")), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + }), + group("b", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "c"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + }), + group("c", notReady, []dt.ResourceHealth{{ObjectReference: ref("Subnet", "sn"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +⚠ not ready (Ready=False, Creating) + +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 + +=== XNetwork/c === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + Subnet/sn ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +================================================================================ +Total: no changes across 3 XRs (3 unchanged) +Health: 3 of 3 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "GroupedNestedWithoutHealth": { + reason: "A nested input XR without health is not owned elsewhere, so its parent lists it and what it composes; the nested XR lists RouteTable/rt too, so it prints twice, but counts once.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: failing}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + }), + group("b", nil, []dt.ResourceHealth{{ObjectReference: ref("RouteTable", "rt"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + XNetwork/b ⚠ failing (Synced=False, ReconcileError): vpc does not exist + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +=== XNetwork/b === + +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; 2 resources failing (Synced=False). +`, + }, + "EqualDiffCounted": { + reason: "An unchanged diff with health prints nothing of its own but counts in the Health: line.", + args: args{groups: []dt.XRDiffGroup{group("net", nil, nil, liveWith(equalDiffFor("Bucket", "b"), "vpc does not exist"))}}, + want: `Health: 1 resource failing (Synced=False). `, }, } @@ -208,6 +424,7 @@ Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). opts.FullMessages = tc.args.full opts.Stdout = &buf opts.Stderr = &bytes.Buffer{} + opts.Health = groupsHealth(tc.args.groups) 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) @@ -229,8 +446,21 @@ func TestRenderCompDiffHealth(t *testing.T) { c := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "c"} sn := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "Subnet", Name: "sn"} + q := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "q"} + long := strings.Repeat("abcdefghi ", 15) + // Expected output is built from long so no literal repeated words sit in the source. + cut := long[:119] + "…" + wrap1 := strings.TrimSpace(long[:100]) + wrap2 := strings.TrimSpace(long[100:]) + failingLong := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: long}} + type args struct { impacts []dt.XRImpact + // other, when set, is a second composition's impacts, rendered after the first. + other []dt.XRImpact + // affected, when set, replaces the first composition's default summary of 2 unchanged. + affected *dt.AffectedResourcesSummary + full bool } cases := map[string]struct { reason string @@ -343,6 +573,254 @@ XR: XBucket/p XBucket/c ⚠ failing (Synced=False, ReconcileError): boom Health: 1 resource failing (Synced=False). +`, + }, + "NestedTwoLevels": { + reason: "A healthy parent's flattened composed list holds the nested XR and what it composes, with Via set; the nested XR, listed with health of its own, lists its resource and the parent lists nothing.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + }}}, + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: rt, 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: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "NestedThreeLevels": { + reason: "Over a 3-level chain p > c > q, each resource is listed once, under the most deeply nested XR that composes it.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: q, Via: &c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + {ObjectReference: sn, Via: &q, Health: failing}, + }}}, + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: q, Health: notReady}, + {ObjectReference: rt, Health: failing}, + {ObjectReference: sn, Via: &q, Health: failing}, + }}}, + {ObjectReference: q, Status: dt.XRStatusUnchanged, ComposedBy: &c, 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) + ✓ XBucket/q (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: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +XR: XBucket/q + Unhealthy resources without changes: + Subnet/sn ⚠ failing (Synced=False, ReconcileError): boom + +Health: 2 of 3 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "TruncatedMessage": { + reason: "Without --full-messages, a long message is cut to 119 runes plus an ellipsis on the affected line and in the block.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failingLong, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: failingLong}}}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): ` + cut + ` + +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: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): ` + cut + ` + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "FullMessages": { + reason: "With --full-messages, a long message prints in full beneath its line, wrapped at 100 runes, on the affected line and in the block.", + args: args{full: true, impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failingLong, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: failingLong}}}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError) + ` + wrap1 + ` + ` + wrap2 + ` + +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: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError) + ` + wrap1 + ` + ` + wrap2 + ` + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "SharedAcrossCompositions": { + reason: "A nested XR listed under a second composition still owns its resources: the parent under the first composition skips it, and the Health: line counts it once.", + args: args{ + impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + }}}, + }, + other: []dt.XRImpact{ + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: rt, Health: failing}, + }}}, + }, + }, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + + +================================================================================ + +=== Composition Changes === + +No changes detected in composition xnetworks.example.org + +=== Affected Composite Resources === + + ✓ XBucket/c (cluster-scoped) ⚠ not ready (Ready=False, Creating) + +Summary: 1 resource unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/c + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "ChangedXRMessageRepeats": { + reason: "A changed unhealthy XR's message prints on its affected line and again in its own diff header. Kept for now by decision; a follow-up will print it once.", + args: args{affected: &dt.AffectedResourcesSummary{Total: 1, WithChanges: 1}, impacts: []dt.XRImpact{ + { + ObjectReference: p, Status: dt.XRStatusChanged, + Health: dt.CompositeHealth{XR: failing}, + Diffs: map[string]*dt.ResourceDiff{"p": liveWith(modifiedDiffFor("XBucket", "p"), "boom")}, + }, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ⚠ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +Summary: 1 resource with changes + +=== Impact Analysis === + +~~~ XBucket/p ⚠ failing (Synced=False, ReconcileError): boom +- spec: +- field: old ++ spec: ++ field: new + +--- + +Summary: 1 modified + +Health: 1 of 1 XR unhealthy before apply. +`, + }, + "FilteredImpact": { + reason: "A filtered impact has no health and no diffs; it adds nothing to the blocks or the Health: line.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: notReady}}}}, + {ObjectReference: c, Status: dt.XRStatusFiltered}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +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: + RouteTable/rt ⚠ not ready (Ready=False, Creating) + +Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. `, }, } @@ -355,15 +833,31 @@ Health: 1 resource failing (Synced=False). opts.Stdout = &stdout opts.Stderr = &bytes.Buffer{} opts.UseColors = false + opts.FullMessages = tc.args.full - 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 tc.args.affected != nil { + comp.AffectedResources = *tc.args.affected + } - if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: []dt.CompositionDiff{comp}}); err != nil { + comps := []dt.CompositionDiff{comp} + if tc.args.other != nil { + comps = append(comps, dt.CompositionDiff{ + Name: "xnetworks.example.org", + AffectedResources: dt.AffectedResourcesSummary{Total: 1, Unchanged: 1}, + ImpactAnalysis: tc.args.other, + }) + } + + inner := NewDiffRenderer(tu.TestLogger(t, false), opts) + opts.Health = compHealth(comps) + r := NewDefaultCompDiffRenderer(tu.TestLogger(t, false), inner, opts) + + if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: comps}); err != nil { t.Fatalf("\n%s\nRenderCompDiff(...): unexpected error: %v", tc.reason, err) } @@ -373,3 +867,59 @@ Health: 1 resource failing (Synced=False). }) } } + +func TestRenderHealthMismatch(t *testing.T) { + g := xrGroup("XNetwork", "net", map[string]*dt.ResourceDiff{}) + impact := dt.XRImpact{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "net", Status: dt.XRStatusUnchanged} + + type args struct { + groups []dt.XRDiffGroup + comps []dt.CompositionDiff + } + cases := map[string]struct { + reason string + args args + want string + }{ + "XRDiffFlat": { + reason: "A run's health for another number of groups is an error, not a panic.", + args: args{groups: []dt.XRDiffGroup{g}}, + want: "run's health has 2 composites, but the report has 1", + }, + "XRDiffGrouped": { + reason: "A run's health for another number of groups is an error in the grouped layout too.", + args: args{groups: []dt.XRDiffGroup{g, xrGroup("XNetwork", "qa", map[string]*dt.ResourceDiff{}), xrGroup("XNetwork", "dev", map[string]*dt.ResourceDiff{})}}, + want: "run's health has 2 composites, but the report has 3", + }, + "CompDiff": { + reason: "A run's health for another number of impacts is an error, not a panic.", + args: args{comps: []dt.CompositionDiff{{Name: "net", ImpactAnalysis: []dt.XRImpact{impact}}, {Name: "other", ImpactAnalysis: []dt.XRImpact{impact, impact}}}}, + want: "run's health has 2 composites, but the report has 3", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + opts := DefaultDiffOptions() + opts.UseColors = false + opts.Stdout, opts.Stderr = &bytes.Buffer{}, &bytes.Buffer{} + opts.Health = &health.Run{Owned: make([][]int, 2)} + + var err error + if tc.args.comps != nil { + err = NewDefaultCompDiffRenderer(tu.TestLogger(t, false), NewDiffRenderer(tu.TestLogger(t, false), opts), opts).RenderCompDiff(&dt.CompDiffOutput{Compositions: tc.args.comps}) + } else { + err = NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(tc.args.groups, nil, nil) + } + + got := "" + if err != nil { + got = err.Error() + } + + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nRender...(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/diff/testutils/mock_builder.go b/internal/diff/testutils/mock_builder.go index 77893058b..d26013dc3 100644 --- a/internal/diff/testutils/mock_builder.go +++ b/internal/diff/testutils/mock_builder.go @@ -32,9 +32,10 @@ import ( ) const ( - fieldSpec = "spec" - jsonTypeObject = "object" - jsonTypeString = "string" + fieldSpec = "spec" + apiExtensionsV1 = "apiextensions.crossplane.io/v1" + jsonTypeObject = "object" + jsonTypeString = "string" ) // MockBuilder provides a fluent API for building mock objects used in testing. @@ -1451,7 +1452,7 @@ func (b *ResourceBuilder) WithCompositionRevisionSelector(apiGroup string, match // v2 XRs nest crossplane spec fields under spec.crossplane; v1 keeps them under spec. path := []string{fieldSpec, "compositionRevisionSelector"} - if apiGroup != "apiextensions.crossplane.io/v1" { + if apiGroup != apiExtensionsV1 { path = []string{fieldSpec, "crossplane", "compositionRevisionSelector"} } diff --git a/internal/health/format.go b/internal/health/format.go index 13b5677ee..277cc59db 100644 --- a/internal/health/format.go +++ b/internal/health/format.go @@ -258,18 +258,23 @@ func Key(apiVersion, kind, namespace, name string) string { return gk.String() + "/" + namespace + "/" + name } -// Tally counts a run's health: the composites it lists, and the other +// 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 { +type tally struct { composites map[string]bool resources map[string]State order []string + // failing is set when anything is added failing, before the first-add + // dedup, so a failing resource counted under another state still sets it. + failing bool } // Composite adds a composite with key and health h. -func (t *Tally) Composite(key string, h *Health) { +func (t *tally) Composite(key string, h *Health) { + t.failing = t.failing || (h != nil && h.State == Failing) + if t.composites == nil { t.composites = map[string]bool{} } @@ -281,11 +286,13 @@ func (t *Tally) Composite(key string, h *Health) { // 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) { +func (t *tally) Resource(key string, h *Health) { if h == nil { return } + t.failing = t.failing || h.State == Failing + if t.resources == nil { t.resources = map[string]State{} } @@ -297,7 +304,7 @@ func (t *Tally) Resource(key string, h *Health) { } // Counts returns what t counted. -func (t *Tally) Counts() Counts { +func (t *tally) Counts() Counts { c := Counts{Composites: len(t.composites)} for _, unhealthy := range t.composites { @@ -388,20 +395,20 @@ func SummaryLine(c Counts) string { return "Health: " + strings.Join(parts, "; ") + "." } -// Entry is a composite entry in a run's output, for OwnedElsewhere: its Key, +// 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 { +type entry struct { Key string HasHealth bool Composes []string } -// OwnedElsewhere returns, for each of entries, the Keys it must not list +// 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 { +func ownedElsewhere(entries []entry) []map[string]bool { composes := make([]map[string]bool, len(entries)) withHealth := map[string][]int{} diff --git a/internal/health/format_test.go b/internal/health/format_test.go index 3d44d86fc..6da847908 100644 --- a/internal/health/format_test.go +++ b/internal/health/format_test.go @@ -279,7 +279,7 @@ func TestTally(t *testing.T) { notReady := &Health{State: NotReady} type args struct { - add func(*Tally) + add func(*tally) } cases := map[string]struct { reason string @@ -288,11 +288,11 @@ func TestTally(t *testing.T) { }{ "Empty": { reason: "Nothing added counts nothing.", - args: args{add: func(*Tally) {}}, + 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) { + args: args{add: func(t *tally) { t.Resource("a", failing) t.Resource("a", notReady) t.Resource("b", &Health{State: Paused}) @@ -302,7 +302,7 @@ func TestTally(t *testing.T) { }, "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) { + args: args{add: func(t *tally) { t.Resource("x", failing) t.Composite("x", failing) t.Composite("y", nil) @@ -316,7 +316,7 @@ func TestTally(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { - var tl Tally + 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) @@ -368,3 +368,125 @@ func TestSummaryLine(t *testing.T) { }) } } + +func TestKey(t *testing.T) { + type args struct { + apiVersion, kind, namespace, name string + } + cases := map[string]struct { + reason string + args args + want string + }{ + "CoreGroup": { + reason: "A core group resource's key is just its kind, namespace and name.", + args: args{apiVersion: "v1", kind: "ConfigMap", namespace: "ns", name: "cm"}, + want: "ConfigMap/ns/cm", + }, + "NamedGroup": { + reason: "A named group resource's key includes its group after the kind.", + args: args{apiVersion: "example.org/v1", kind: "XBucket", namespace: "ns", name: "b"}, + want: "XBucket.example.org/ns/b", + }, + "VersionIgnored": { + reason: "Another version of the same kind gives the same key.", + args: args{apiVersion: "example.org/v2", kind: "XBucket", namespace: "ns", name: "b"}, + want: "XBucket.example.org/ns/b", + }, + "ClusterScoped": { + reason: "A cluster-scoped resource's key has an empty namespace.", + args: args{apiVersion: "example.org/v1", kind: "XBucket", name: "b"}, + want: "XBucket.example.org//b", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Key(tc.args.apiVersion, tc.args.kind, tc.args.namespace, tc.args.name) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nKey(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestOwnedElsewhere(t *testing.T) { + type args struct { + entries []entry + } + cases := map[string]struct { + reason string + args args + want []map[string]bool + }{ + "Single": { + reason: "A lone entry lists everything it composes.", + args: args{entries: []entry{{Key: "a", HasHealth: true, Composes: []string{"r"}}}}, + want: []map[string]bool{{}}, + }, + "ChildWithHealth": { + reason: "A parent doesn't list a child with health, nor what the child composes.", + args: args{entries: []entry{ + {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + }}, + want: []map[string]bool{{"b": true, "r2": true}, {}}, + }, + "ChildWithoutHealth": { + reason: "A child without health stays listed by its parent, with what it composes.", + args: args{entries: []entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", Composes: []string{"r"}}, + }}, + want: []map[string]bool{{}, {}}, + }, + "ThreeLevels": { + reason: "Each entry drops its child and the child's direct compositions only, not the grandchild's.", + args: args{entries: []entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", HasHealth: true, Composes: []string{"c"}}, + {Key: "c", HasHealth: true, Composes: []string{"r"}}, + }}, + want: []map[string]bool{{"b": true, "c": true}, {"c": true, "r": true}, {}}, + }, + "MiddleHasNoEntry": { + reason: "With no entry for the middle level, the top lists it and the bottom entry is owned by nobody.", + args: args{entries: []entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "c", HasHealth: true, Composes: []string{"r"}}, + }}, + want: []map[string]bool{{}, {}}, + }, + "DuplicateKeys": { + reason: "Entries sharing a key with health have their compositions merged.", + args: args{entries: []entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", HasHealth: true, Composes: []string{"r1"}}, + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + }}, + want: []map[string]bool{{"b": true, "r1": true, "r2": true}, {}, {}}, + }, + "ComposesItself": { + reason: "An entry that composes itself drops itself and everything it composes.", + args: args{entries: []entry{{Key: "a", HasHealth: true, Composes: []string{"a", "r"}}}}, + want: []map[string]bool{{"a": true, "r": true}}, + }, + "OrderIndependent": { + reason: "The child listed before its parent gives the same result, by position.", + args: args{entries: []entry{ + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, + }}, + want: []map[string]bool{{}, {"b": true, "r2": true}}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := ownedElsewhere(tc.args.entries) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nOwnedElsewhere(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/health/healthtest/builder.go b/internal/health/healthtest/builder.go new file mode 100644 index 000000000..703293ca4 --- /dev/null +++ b/internal/health/healthtest/builder.go @@ -0,0 +1,51 @@ +/* +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 healthtest provides builders for health values in tests. +package healthtest + +import ( + corev1 "k8s.io/api/core/v1" + + "github.com/crossplane/cli/v2/internal/health" +) + +// HealthBuilder helps construct a *health.Health for tests. +type HealthBuilder struct { + health *health.Health +} + +// NewHealth creates a new HealthBuilder in the given state, with no conditions. +func NewHealth(state health.State) *HealthBuilder { + return &HealthBuilder{health: &health.Health{State: state}} +} + +// WithSynced sets the Synced condition. +func (b *HealthBuilder) WithSynced(status corev1.ConditionStatus, reason, message string) *HealthBuilder { + b.health.Synced = &health.Condition{Status: status, Reason: reason, Message: message} + return b +} + +// WithReady sets the Ready condition. +func (b *HealthBuilder) WithReady(status corev1.ConditionStatus, reason, message string) *HealthBuilder { + b.health.Ready = &health.Condition{Status: status, Reason: reason, Message: message} + return b +} + +// Build returns the built health. +func (b *HealthBuilder) Build() *health.Health { + return b.health +} diff --git a/internal/health/run.go b/internal/health/run.go new file mode 100644 index 000000000..e164840ea --- /dev/null +++ b/internal/health/run.go @@ -0,0 +1,114 @@ +/* +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 ( + "strconv" + "strings" +) + +// Composite is one composite of a run as the engine observed it. +type Composite struct { + // Key is the composite's Key: the input's identity, a claim or an XR. + Key string + // Health is the composite's own live health, or nil when it has none: it + // is not in the cluster, it errored, or it was filtered out. + Health *Health + // Composed is every composed resource the engine observed, nested ones + // included with Via set, in the engine's order. Each ID is its Key. + Composed []Item +} + +// Run is a run's health, summarized once by Build. +type Run struct { + // Owned holds, for each composite, the indexes into its Composed of the + // unhealthy resources it lists, ownership resolved by ownedElsewhere, and + // before any renderer filters out the resources it shows elsewhere. + Owned [][]int + // Counts are the run's health counts, for its summary line. + Counts Counts + // Failing reports whether anything in the run is failing, which sets exit + // bit 4. + Failing bool +} + +// Build summarizes the health of a run of composites, which shows the shown +// resources (its plans) itself. It tallies, in order, the composites with +// health of their own, the shown resources, and each owned resource that is +// not shown. Failing is set when anything tallied is failing, before the +// tally drops repeats, so it can be set by a resource that counts under an +// earlier health. +// +// A shown resource whose ID has no kind and no name, as a plan's can, is +// never taken for another, so each counts. +func Build(composites []Composite, shown []Item) Run { + entries := make([]entry, len(composites)) + for i, c := range composites { + entries[i] = entry{Key: c.Key, HasHealth: c.Health != nil} + for _, it := range c.Composed { + entries[i].Composes = append(entries[i].Composes, it.ID) + } + } + owned := ownedElsewhere(entries) + + r := Run{Owned: make([][]int, len(composites))} + for i, c := range composites { + for j, it := range c.Composed { + if it.Health.Unhealthy() && !owned[i][it.ID] { + r.Owned[i] = append(r.Owned[i], j) + } + } + } + + t := &tally{} + for _, c := range composites { + if c.Health != nil { + t.Composite(c.Key, c.Health) + } + } + + isShown := map[string]bool{} + for i, it := range shown { + key := it.ID + if unnamed(key) { + // A Key starts with a kind or "/", so this one can match no other. + key = "#" + strconv.Itoa(i) + } + isShown[key] = true + t.Resource(key, it.Health) + } + + for i, owned := range r.Owned { + for _, j := range owned { + it := composites[i].Composed[j] + if !isShown[it.ID] { + t.Resource(it.ID, it.Health) + } + } + } + + r.Counts = t.Counts() + r.Failing = t.failing + + return r +} + +// unnamed reports whether id is the Key of a resource with no kind and no +// name, such as Key("", "", ns, ""), or empty. +func unnamed(id string) bool { + return id == "" || (strings.HasPrefix(id, "/") && strings.HasSuffix(id, "/") && strings.Count(id, "/") == 2) +} diff --git a/internal/health/run_test.go b/internal/health/run_test.go new file mode 100644 index 000000000..efae268f3 --- /dev/null +++ b/internal/health/run_test.go @@ -0,0 +1,141 @@ +/* +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 ( + "testing" + + "github.com/google/go-cmp/cmp" +) + +func TestBuild(t *testing.T) { + failing := &Health{State: Failing} + notReady := &Health{State: NotReady} + healthy := &Health{State: Healthy} + + xr := Key("example.org/v1", "XR", "", "xr") + child := Key("example.org/v1", "Child", "", "child") + grand := Key("example.org/v1", "Grand", "", "grand") + a := Key("v1", "ConfigMap", "ns", "a") + b := Key("v1", "ConfigMap", "ns", "b") + unnamedNs := Key("", "", "ns", "") + + type args struct { + composites []Composite + shown []Item + } + cases := map[string]struct { + reason string + args args + want Run + }{ + "Nil": { + reason: "No composites and nothing shown is an empty run.", + want: Run{Owned: [][]int{}}, + }, + "Empty": { + reason: "Empty input is an empty run.", + args: args{composites: []Composite{}, shown: []Item{}}, + want: Run{Owned: [][]int{}}, + }, + "CompositeWinsOverResource": { + reason: "A composite also shown as a resource counts only as a composite.", + args: args{ + composites: []Composite{{Key: xr, Health: notReady}}, + shown: []Item{{ID: xr, Health: failing}}, + }, + want: Run{Owned: [][]int{nil}, Counts: Counts{Composites: 1, UnhealthyComposites: 1}, Failing: true}, + }, + "CompositeWithoutHealthNotCounted": { + reason: "A composite with no health of its own is not counted as a composite.", + args: args{composites: []Composite{{Key: xr}}}, + want: Run{Owned: [][]int{nil}}, + }, + "FirstShownWins": { + reason: "A resource shown twice counts once, under the health it was first shown with.", + args: args{shown: []Item{{ID: a, Health: notReady}, {ID: a, Health: failing}}}, + want: Run{Owned: [][]int{}, Counts: Counts{NotReady: 1}, Failing: true}, + }, + "FailingFromComposite": { + reason: "A failing composite sets Failing.", + args: args{composites: []Composite{{Key: xr, Health: failing}}}, + want: Run{Owned: [][]int{nil}, Counts: Counts{Composites: 1, UnhealthyComposites: 1}, Failing: true}, + }, + "FailingFromOwned": { + reason: "A failing owned resource sets Failing and counts.", + args: args{composites: []Composite{{Key: xr, Health: healthy, Composed: []Item{ + {ID: a, Health: healthy}, + {ID: b, Health: failing}, + }}}}, + want: Run{Owned: [][]int{{1}}, Counts: Counts{Composites: 1, Failing: 1}, Failing: true}, + }, + "OwnedMinusShownCountedOnce": { + reason: "An owned resource that is also shown counts once, with its shown health, and its owned health is not tallied, as simulate lists it only on its plan.", + args: args{ + composites: []Composite{{Key: xr, Health: healthy, Composed: []Item{{ID: a, Health: failing}}}}, + shown: []Item{{ID: a, Health: notReady}}, + }, + want: Run{Owned: [][]int{{0}}, Counts: Counts{Composites: 1, NotReady: 1}}, + }, + "NestedOwnership": { + reason: "A resource is owned by the most deeply nested composite with health that composes it, three levels down.", + args: args{composites: []Composite{ + {Key: xr, Health: healthy, Composed: []Item{ + {ID: child, Health: notReady}, + {ID: grand, Via: child, Health: notReady}, + {ID: a, Via: grand, Health: failing}, + }}, + {Key: child, Health: notReady, Composed: []Item{ + {ID: grand, Health: notReady}, + {ID: a, Via: grand, Health: failing}, + }}, + {Key: grand, Health: notReady, Composed: []Item{{ID: a, Health: failing}}}, + }}, + want: Run{ + Owned: [][]int{nil, nil, {0}}, + Counts: Counts{Composites: 3, UnhealthyComposites: 2, Failing: 1}, + Failing: true, + }, + }, + "IdempotentOnResolved": { + reason: "Already resolved composites resolve to themselves: a nested entry without health stays with its parent.", + args: args{composites: []Composite{ + {Key: xr, Health: healthy, Composed: []Item{{ID: child, Health: notReady}}}, + {Key: child, Composed: []Item{{ID: a, Health: failing}}}, + }}, + want: Run{Owned: [][]int{{0}, {0}}, Counts: Counts{Composites: 1, NotReady: 1, Failing: 1}, Failing: true}, + }, + "UnnamedShownEachCount": { + reason: "Shown resources with no kind and no name never share a key, so the failing count agrees with Failing.", + args: args{shown: []Item{ + {ID: unnamedNs, Health: notReady}, + {ID: unnamedNs, Health: failing}, + {Health: failing}, + }}, + want: Run{Owned: [][]int{}, Counts: Counts{NotReady: 1, Failing: 2}, Failing: true}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Build(tc.args.composites, tc.args.shown) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nBuild(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/plan/output.go b/internal/plan/output.go index 7700717a8..f9e2ec6eb 100644 --- a/internal/plan/output.go +++ b/internal/plan/output.go @@ -114,24 +114,18 @@ type HealthSummary struct { Paused int `json:"paused"` } -// HealthCounts returns the health counts of plans: each resource once, under -// the state its first plan reports, matched across API versions. -func HealthCounts(plans []*ResourcePlan) health.Counts { - t := &health.Tally{} - for _, p := range plans { +// HealthRun returns the run's health: plans are the resources it shows, with +// no composites of its own. +func HealthRun(plans []*ResourcePlan) health.Run { + items := make([]health.Item, len(plans)) + for i, p := range plans { ns := p.Namespace if p.LiveNamespace != "" { ns = p.LiveNamespace } - t.Resource(health.Key(p.APIVersion, p.Kind, ns, p.Name), p.Health) + items[i] = health.Item{ID: health.Key(p.APIVersion, p.Kind, ns, p.Name), Health: p.Health} } - return t.Counts() -} - -// Failing reports whether any plan's resource is failing, which sets exit -// bit 4. -func Failing(plans []*ResourcePlan) bool { - return slices.ContainsFunc(plans, func(p *ResourcePlan) bool { return p.Health != nil && p.Health.State == health.Failing }) + return health.Build(nil, items) } // MarshalJSON writes the result with its plans' health counts under @@ -143,7 +137,7 @@ func (r Result) MarshalJSON() ([]byte, error) { Health HealthSummary `json:"health"` } - c := HealthCounts(r.Plans) + c := HealthRun(r.Plans).Counts return json.Marshal(struct { FormatVersion string `json:"formatVersion"` Errored bool `json:"errored"` @@ -230,7 +224,7 @@ func (pr planRenderer) Render(w io.Writer, plans []*ResourcePlan) error { } s := Summarize(plans) RenderSummaryLine(w, s) - if line := health.SummaryLine(HealthCounts(plans)); line != "" { + if line := health.SummaryLine(HealthRun(plans).Counts); line != "" { _, _ = fmt.Fprintln(w, line) } RenderSummaryWarnings(w, plans, s) diff --git a/internal/plan/output_test.go b/internal/plan/output_test.go index 3e8ea4dce..31dd71895 100644 --- a/internal/plan/output_test.go +++ b/internal/plan/output_test.go @@ -19,6 +19,7 @@ package plan import ( "bytes" "encoding/json" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -26,6 +27,7 @@ import ( "sigs.k8s.io/yaml" "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" ) func testPlans() []*ResourcePlan { @@ -311,6 +313,7 @@ func TestRenderPlanHealth(t *testing.T) { failing := func(msg string) *health.Health { return &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: msg}} } + longMsg := strings.Repeat("creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, ", 3) + "api error" vpcMsg := "The vpc ID 'vpc-048777c3b8a8ee173' does not exist\nstatus code: 400" update := &ResourcePlan{ APIVersion: "ec2.aws.upbound.io/v1beta1", Kind: "Subnet", Name: "my-subnet", Action: ActionUpdate, @@ -379,6 +382,75 @@ Health: 1 resource failing (Synced=False), 1 not ready, 1 paused. Plan: 0 to add, 1 to change, 0 to destroy. Health: 1 resource failing (Synced=False). +`, + }, + "EveryState": { + reason: "Healthy, failing, not ready, paused and unknown resources: only the unhealthy ones get a ⚠ line; Unknown conditions are healthy and print nothing.", + args: args{plans: []*ResourcePlan{ + noop("healthy-vpc", ht.NewHealth(health.Healthy).WithSynced("True", "ReconcileSuccess", "").WithReady("True", "Available", "").Build()), + noop("failing-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "boom").Build()), + noop("other-failing-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "bang").Build()), + noop("notready-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + noop("paused-vpc", ht.NewHealth(health.Paused).WithSynced("False", "ReconcileError", "ignored").Build()), + noop("unknown-vpc", ht.NewHealth(health.Healthy).WithSynced("Unknown", "", "").WithReady("Unknown", "", "").Build()), + }}, + want: `[=] VPC.ec2.aws.upbound.io healthy-vpc (no-op) + +[=] VPC.ec2.aws.upbound.io failing-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): boom + +[=] VPC.ec2.aws.upbound.io other-failing-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): bang + +[=] VPC.ec2.aws.upbound.io notready-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +[=] VPC.ec2.aws.upbound.io paused-vpc (no-op) + ⚠ paused + +[=] VPC.ec2.aws.upbound.io unknown-vpc (no-op) + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 resources failing (Synced=False), 1 not ready, 1 paused. +`, + }, + "OnlyNotReady": { + reason: "With nothing failing, the plural noun goes on the first non-zero part.", + args: args{plans: []*ResourcePlan{ + noop("a-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + noop("b-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + }}, + want: `[=] VPC.ec2.aws.upbound.io a-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +[=] VPC.ec2.aws.upbound.io b-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 resources not ready. +`, + }, + "FullMessagesLong": { + reason: "With full messages, a message longer than the wrap width wraps at the wrap width beneath the ⚠ line, indented 8.", + args: args{plans: []*ResourcePlan{noop("long-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", longMsg).Build())}, full: true}, + want: `[=] VPC.ec2.aws.upbound.io long-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError) + creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: + operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: operation error + EC2: CreateVpc, https response error StatusCode: 400, api error + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 resource failing (Synced=False). +`, + }, + "LongCut": { + reason: "Without full messages, a long message is cut to one line with an ellipsis.", + args: args{plans: []*ResourcePlan{noop("long-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", longMsg).Build())}}, + want: `[=] VPC.ec2.aws.upbound.io long-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: operation error EC2: … + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 resource failing (Synced=False). `, }, } @@ -392,6 +464,9 @@ Health: 1 resource failing (Synced=False). if diff := cmp.Diff(tc.want, buf.String()); diff != "" { t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) } + if run := HealthRun(tc.args.plans); run.Failing != (run.Counts.Failing > 0) { + t.Errorf("\n%s\nHealthRun(...).Failing = %t, but the Health: line counts failing = %t", tc.reason, run.Failing, run.Counts.Failing > 0) + } }) } } @@ -520,7 +595,7 @@ func TestRenderYAMLHealth(t *testing.T) { } } -func TestFailing(t *testing.T) { +func TestHealthRunFailing(t *testing.T) { type args struct { plans []*ResourcePlan } @@ -539,16 +614,60 @@ func TestFailing(t *testing.T) { args: args{plans: []*ResourcePlan{{Health: &health.Health{State: health.NotReady}}, {Health: &health.Health{State: health.Paused}}}}, want: false, }, + "Healthy": { + reason: "A healthy resource is not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Healthy).Build()}}}, + want: false, + }, + "Unknown": { + reason: "A resource whose conditions are Unknown is healthy, so not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Healthy).WithSynced("Unknown", "", "").Build()}}}, + want: false, + }, + "NotReady": { + reason: "A not ready resource is not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()}}}, + want: false, + }, + "Paused": { + reason: "A paused resource is not failing, even with Synced=False.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Paused).WithSynced("False", "ReconcileError", "boom").Build()}}}, + want: false, + }, + "Failing": { + reason: "A failing resource is failing.", + args: args{plans: []*ResourcePlan{{Action: ActionNoOp, Health: ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "boom").Build()}}}, + want: true, + }, + "FailingAmongHealthy": { + reason: "One failing resource among healthy ones makes the plans failing.", + args: args{plans: []*ResourcePlan{ + {Kind: "VPC", Name: "a", Health: ht.NewHealth(health.Healthy).Build()}, + {Kind: "VPC", Name: "b", Health: ht.NewHealth(health.Failing).Build()}, + }}, + want: true, + }, "FailingDelete": { reason: "A failing resource sets the bit, even one the plan deletes.", args: args{plans: []*ResourcePlan{{Action: ActionDelete, Health: &health.Health{State: health.Failing}}}}, want: true, }, + "FailingAmongUnnamed": { + reason: "Plans with no kind and no name each get their own key, so one failing among healthy ones is counted and failing.", + args: args{plans: []*ResourcePlan{ + {Health: ht.NewHealth(health.Healthy).Build()}, + {Health: ht.NewHealth(health.Failing).Build()}, + }}, + want: true, + }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - if diff := cmp.Diff(tc.want, Failing(tc.args.plans)); diff != "" { - t.Errorf("\n%s\nFailing(...): -want, +got:\n%s", tc.reason, diff) + if diff := cmp.Diff(tc.want, HealthRun(tc.args.plans).Failing); diff != "" { + t.Errorf("\n%s\nHealthRun(...).Failing: -want, +got:\n%s", tc.reason, diff) + } + if line := HealthRun(tc.args.plans).Counts.Failing > 0; line != tc.want { + t.Errorf("\n%s\nthe Health: line counts failing = %t, want %t", tc.reason, line, tc.want) } }) } diff --git a/internal/simulate/health_render_test.go b/internal/simulate/health_render_test.go new file mode 100644 index 000000000..f00998186 --- /dev/null +++ b/internal/simulate/health_render_test.go @@ -0,0 +1,171 @@ +/* +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 simulate + +import ( + "bytes" + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + + "github.com/crossplane/cli/v2/internal/diff/renderer" + 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" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" +) + +// TestRenderDiffHealth renders reports through the production path: the +// assembler, then the Run it stored, then the human diff renderer. +func TestRenderDiffHealth(t *testing.T) { + failing := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() + cm := func(name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Name: name} + } + qaRef := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "qa"} + child := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"} + + // Composition net reaches three nested XRs; composition other reaches the + // same top XR, and filters qa. + comp := nestedCompReport(3) + comp.Compositions = append(comp.Compositions, dt.CompositionDiff{Name: "other", ImpactAnalysis: []dt.XRImpact{ + {ObjectReference: qaRef, Status: dt.XRStatusFiltered, FilterReason: dt.FilterReasonDeleting}, + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: comp.Compositions[0].ImpactAnalysis[0].Health}, + }}) + + xr := &dt.XRReport{Groups: []dt.XRDiffGroup{ + {XR: xrRef, Diffs: map[string]*dt.ResourceDiff{}, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{ + {ObjectReference: cm("a-cm"), Health: failing}, + {ObjectReference: child, Health: notReady}, + {ObjectReference: cm("b-cm"), Via: &child, Health: notReady}, + }}}, + {XR: qaRef, Diffs: map[string]*dt.ResourceDiff{}, Health: dt.CompositeHealth{Composed: []dt.ResourceHealth{ + {ObjectReference: cm("q-cm"), Health: notReady}, + }}}, + }} + + type args struct { + xr *dt.XRReport + comp *dt.CompDiffOutput + } + cases := map[string]struct { + reason string + args args + want string + }{ + "CompDiff": { + reason: "Each impact, nested, filtered or shared across compositions, lists the unhealthy resources the stored Run gives it, and the Health: line counts the run once.", + args: args{comp: comp}, + want: `=== Composition Changes === + +No changes detected in composition net + +=== Affected Composite Resources === + + ✓ XNetwork/prod (cluster-scoped) + ✓ XSubnet/child (cluster-scoped) ⚠ not ready (Ready=False, Creating) + ✓ XZone/grand (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XNetwork/prod + Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet/child + Unhealthy resources without changes: + ConfigMap/b-cm ⚠ not ready (Ready=False, Creating) + +XR: XZone/grand + Unhealthy resources without changes: + ConfigMap/c-cm ⚠ paused + +================================================================================ + +=== Composition Changes === + +No changes detected in composition other + +=== Affected Composite Resources === + + ✓ XNetwork/prod (cluster-scoped) + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XNetwork/prod + Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + +Health: 2 of 3 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready, 1 paused. +`, + }, + "XRDiffGrouped": { + reason: "Each XR section lists the unhealthy resources the stored Run gives it, and the Health: line counts the run.", + args: args{xr: xr}, + want: `=== XNetwork/prod === + +⚠ failing (Synced=False, ReconcileError): boom + +No changes. + +Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + XSubnet/child ⚠ not ready (Ready=False, Creating) + ConfigMap/b-cm ⚠ not ready (Ready=False, Creating) + +=== XNetwork/qa === + +No changes. + +Unhealthy resources without changes: + ConfigMap/q-cm ⚠ not ready (Ready=False, Creating) + +================================================================================ +Total: no changes across 2 XRs (2 unchanged) +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 3 not ready. +`, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var buf bytes.Buffer + opts := renderer.DefaultDiffOptions() + opts.UseColors = false + opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} + + var err error + if tc.args.comp != nil { + err = renderCompDiff(tu.TestLogger(t, false), opts, tc.args.comp, nil, FromCompReport(tc.args.comp, nil, nil)) + } else { + err = renderXRDiff(tu.TestLogger(t, false), opts, tc.args.xr, nil, FromXRReport(tc.args.xr, nil, nil)) + } + if err != nil { + t.Fatalf("%s\nrender...Diff(...): unexpected error: %v", tc.reason, err) + } + if diff := cmp.Diff(tc.want, buf.String()); diff != "" { + t.Errorf("%s\nrender...Diff(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 81c1cf53a..6d3482376 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -252,35 +252,20 @@ func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { a.composed = append(a.composed, h.Composed) } -// unhealthy sets each composite's Unhealthy: what it composed that is not -// healthy and has no plan in the run, matched across API versions. A -// resource with a plan shows its health there. -// -// A nested composite with an entry and health of its own, as a composition -// run gives one of a diffed composition's type, shows its health on that -// entry and lists what it composes itself; its parent lists neither. So a -// resource is listed under the most deeply nested composite entry that -// composes it, once. -func (a *assembler) unhealthy() { +// unhealthy sets each composite's Unhealthy from run.Owned, which already +// lists each unhealthy resource under the most deeply nested composite entry +// that composes it, once. It drops each resource with a plan in the run, +// matched across API versions: that resource shows its health on its plan. +func (a *assembler) unhealthy(run health.Run) { planned := map[string]bool{} for _, p := range a.plans { planned[health.Key(p.APIVersion, p.Kind, p.Namespace, p.Name)] = true } - entries := make([]health.Entry, len(a.composed)) - for i, composed := range a.composed { - c := a.composites[i] - entries[i] = health.Entry{Key: healthKey(c.Ref), HasHealth: c.Health != nil} - for _, r := range composed { - 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 { - for _, r := range composed { - id := health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name) - if !r.Health.Unhealthy() || planned[id] || ownedElsewhere[i][id] { + for i, owned := range run.Owned { + for _, j := range owned { + r := a.composed[i][j] + if planned[health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name)] { continue } u := UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health} @@ -293,6 +278,19 @@ func (a *assembler) unhealthy() { } } +// run builds the run's health from every composite, what it composed, and +// the plans. +func (a *assembler) run() health.Run { + cs := make([]health.Composite, len(a.composites)) + for i, c := range a.composites { + cs[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} + for _, r := range a.composed[i] { + cs[i].Composed = append(cs[i].Composed, health.Item{ID: health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name), Health: r.Health}) + } + } + return health.Build(cs, planItems(a.plans)) +} + // 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. @@ -421,8 +419,10 @@ func (a *assembler) addRunErrors(all, owned []dt.OutputError) { } func (a *assembler) result(warnings []dt.OutputWarning) Result { - a.unhealthy() + run := a.run() + a.unhealthy(run) res := NewResult(a.plans, a.composites, a.errors) + res.run = &run if a.provider == nil { res.Notes = []string{noteProviderPlanNotRun} } diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 4f1d05c1b..28829700b 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -17,8 +17,10 @@ limitations under the License. package simulate import ( + "bytes" "maps" "slices" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -27,8 +29,11 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" + "github.com/crossplane/cli/v2/internal/diff/renderer" 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" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" "github.com/crossplane/cli/v2/internal/plan" ) @@ -318,7 +323,7 @@ func TestFromCompReport(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { got := FromCompReport(tc.in, nil, nil) - if diff := cmp.Diff(tc.want, got, cmpopts.IgnoreFields(plan.ResourcePlan{}, "Before", "After"), cmpopts.EquateEmpty()); diff != "" { + if diff := cmp.Diff(tc.want, got, cmpopts.IgnoreFields(plan.ResourcePlan{}, "Before", "After"), cmpopts.EquateEmpty(), cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("%s\nFromCompReport(...): -want, +got:\n%s", tc.reason, diff) } }) @@ -623,6 +628,10 @@ func TestHealth(t *testing.T) { d.Current.Raw = obj(d.Gvk, d.ResourceName, fields) return d } + desired := func(d *dt.ResourceDiff) *dt.ResourceDiff { + d.Desired.Raw = d.Desired.Clean + return d + } failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "R"}} notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: corev1.ConditionFalse, Reason: "R"}} healthy := &health.Health{State: health.Healthy} @@ -640,16 +649,23 @@ func TestHealth(t *testing.T) { compRef := func(name string) *plan.ResourceRef { return &plan.ResourceRef{APIVersion: "apiextensions.crossplane.io/v1", Kind: "Composition", Name: name} } + grandPlan := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XZone", Name: "grand"} + healthy3 := ht.NewHealth(health.Healthy).Build() + failing3 := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady3 := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() unhealthyXR := dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("cm"), Health: notReady}}} type want struct { plans map[string]*health.Health // plan name -> health composites []CompositeResult summary plan.HealthSummary + // diffLine, when set, is the Health: line -o diff prints for args.xr. + diffLine *string } type args struct { xr *dt.XRReport comp *dt.CompDiffOutput + keep func(*unstructured.Unstructured) bool } cases := map[string]struct { reason string @@ -788,13 +804,54 @@ func TestHealth(t *testing.T) { summary: plan.HealthSummary{Composites: 1, NotReady: 1}, }, }, + "NestedTwoLevels": { + reason: "A nested composite with health lists what it composes; its parent lists only its own.", + args: args{comp: nestedCompReport(2)}, + want: want{ + plans: map[string]*health.Health{"net": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: &compPlan, Status: CompositeUnchanged, Health: healthy3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("a-cm"), Health: failing3}}}, + {Ref: childPlan, Composition: &compPlan, ComposedBy: &xrPlan, Status: CompositeUnchanged, Health: notReady3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("b-cm"), Health: notReady3}}}, + }, + summary: plan.HealthSummary{Composites: 1, Failing: 1, NotReady: 1}, + }, + }, + "NestedThreeLevels": { + reason: "In a chain of three composites with health, each unhealthy resource is listed once, under the deepest composite.", + args: args{comp: nestedCompReport(3)}, + want: want{ + plans: map[string]*health.Health{"net": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: &compPlan, Status: CompositeUnchanged, Health: healthy3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("a-cm"), Health: failing3}}}, + {Ref: childPlan, Composition: &compPlan, ComposedBy: &xrPlan, Status: CompositeUnchanged, Health: notReady3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("b-cm"), Health: notReady3}}}, + {Ref: grandPlan, Composition: &compPlan, ComposedBy: &childPlan, Status: CompositeUnchanged, Health: failing3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("c-cm"), Health: &health.Health{State: health.Paused}}}}, + }, + summary: plan.HealthSummary{Composites: 2, Failing: 1, NotReady: 1, Paused: 1}, + }, + }, + "EqualKeptForMissingProviderPlan": { + reason: "An unhealthy equal diff kept only for a provider plan that has none, and composed by no entry, is dropped from the plans, so summary.health and exit bit 4 miss it; " + + "the -o diff Health: line now counts plans, the same as JSON (D-1), so it prints none.", + args: args{ + xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(desired(live(rdiff(cmGVK, "kept", dt.DiffTypeEqual, map[string]any{}, map[string]any{}), cond("Synced", "False")))), + }}}, + keep: func(*unstructured.Unstructured) bool { return true }, + }, + want: want{ + plans: map[string]*health.Health{}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeUnchanged}}, + diffLine: new(""), + }, + }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - got := FromXRReport(tc.args.xr, nil, nil) + got := FromXRReport(tc.args.xr, nil, tc.args.keep) if tc.args.comp != nil { - got = FromCompReport(tc.args.comp, nil, nil) + got = FromCompReport(tc.args.comp, nil, tc.args.keep) } gotPlans := map[string]*health.Health{} for _, p := range got.Plans { @@ -809,6 +866,41 @@ func TestHealth(t *testing.T) { if diff := cmp.Diff(tc.want.summary, got.Health()); diff != "" { t.Errorf("%s\nHealth(): -want, +got:\n%s", tc.reason, diff) } + // Exit bit 4 is set exactly when the Health: line counts a failing + // item: a failing resource, or a failing XR among its unhealthy XRs. + if line, want := got.HealthLine(), anyFailing(got); got.Failing() != want { + t.Errorf("%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got.Failing(), line) + } + if tc.want.diffLine != nil { + var buf bytes.Buffer + opts := renderer.DefaultDiffOptions() + opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} + opts.Health = got.run + r := AnnotateXRReport(tc.args.xr, nil) + if err := renderer.NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(r.Groups, r.Errors, r.Warnings); err != nil { + t.Fatalf("%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) + } + var line string + for l := range strings.Lines(buf.String()) { + if strings.HasPrefix(l, "Health:") { + line = strings.TrimSpace(l) + } + } + if diff := cmp.Diff(*tc.want.diffLine, line); diff != "" { + t.Errorf("%s\n-o diff Health: line: -want, +got:\n%s", tc.reason, diff) + } + } }) } } + +// anyFailing reports whether the Health: line of r counts a failing item: a +// failing resource, or a failing composite among the XRs it counts. +func anyFailing(r Result) bool { + if r.Health().Failing > 0 { + return true + } + return slices.ContainsFunc(r.Composites, func(c CompositeResult) bool { + return c.Health != nil && c.Health.State == health.Failing + }) +} diff --git a/internal/simulate/result.go b/internal/simulate/result.go index 2b1f2b364..45ae49fb9 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -181,6 +181,10 @@ type Result struct { // Notes are statements about how the result was produced, e.g. that the // provider plans did not run. Notes []string `json:"notes,omitempty"` + + // run is the run's health the assembler resolved Unhealthy from; nil + // for a Result it didn't build. + run *health.Run } // NewResult assembles the Result for the given plans and @@ -207,49 +211,50 @@ 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() plan.HealthSummary { - c := r.healthTally().Counts() + c := r.healthRun().Counts return plan.HealthSummary{Composites: c.UnhealthyComposites, Failing: c.Failing, NotReady: c.NotReady, Paused: c.Paused} } -// 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) - } +// healthRun returns the run's health: the Run the assembler stored, else one +// built from Composites and Plans. Each Unhealthy list is already resolved, +// which Build leaves as it is, so this matches the Run the assembler built +// them from. 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) healthRun() health.Run { + if r.run != nil { + return *r.run } - for _, p := range r.Plans { - t.Resource(healthKey(p.ResourceRef()), p.Health) - } - for _, c := range r.Composites { + composites := make([]health.Composite, len(r.Composites)) + for i, c := range r.Composites { + composites[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} for _, u := range c.Unhealthy { - t.Resource(healthKey(u.Ref), u.Health) + composites[i].Composed = append(composites[i].Composed, health.Item{ID: healthKey(u.Ref), Health: u.Health}) } } - return t + return health.Build(composites, planItems(r.Plans)) +} + +// planItems returns plans as the resources a run shows itself. +func planItems(plans []*plan.ResourcePlan) []health.Item { + items := make([]health.Item, len(plans)) + for i, p := range plans { + items[i] = health.Item{ID: healthKey(p.ResourceRef()), Health: p.Health} + } + return items } // 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) }) + return r.healthRun().Failing } // 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()) + return health.SummaryLine(r.healthRun().Counts) } // healthKey identifies ref across API versions, as health.Key does. diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index cadaad191..8345976c3 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -23,8 +23,12 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + corev1 "k8s.io/api/core/v1" + dt "github.com/crossplane/cli/v2/internal/diff/result" "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" "github.com/crossplane/cli/v2/internal/plan" ) @@ -205,7 +209,7 @@ func TestRenderJSONProjectFields(t *testing.T) { if err := json.Unmarshal(buf.Bytes(), &got); err != nil { t.Fatalf("Render(json): output is not valid JSON: %v", err) } - if diff := cmp.Diff(in, got); diff != "" { + if diff := cmp.Diff(in, got, cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("Render(json): -want, +got:\n%s", diff) } @@ -309,6 +313,9 @@ func TestRenderJSONHealth(t *testing.T) { xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod"} nested := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "a"} failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "boom"}} + comp := `{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net"}` + failingJSON := `{"state":"failing","synced":{"status":"False","reason":"ReconcileError","message":"boom"}}` + notReadyJSON := `{"state":"notReady","ready":{"status":"False","reason":"Creating"}}` type want struct { composites string @@ -354,6 +361,32 @@ func TestRenderJSONHealth(t *testing.T) { summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":1,"failing":0,"notReady":1,"paused":2},"deferred":0}`, }, }, + "NestedTwoLevels": { + reason: "Through the assembler, each unhealthy resource is under the deepest XR with health, and summary.health counts each once.", + args: args{in: FromCompReport(nestedCompReport(2), nil, nil)}, + want: want{ + composites: `[` + `{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged","composition":` + comp + `,"health":{"state":"healthy"},` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"a-cm"},"health":` + failingJSON + `}]},` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":` + notReadyJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"b-cm"},"health":` + notReadyJSON + `}]}` + `]`, + plans: `[{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net","action":"no-op"}]`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":1,"failing":1,"notReady":1,"paused":0},"deferred":0}`, + }, + }, + "NestedThreeLevels": { + reason: "Through the assembler, in a chain of three XRs with health each unhealthy resource is under the deepest XR, and summary.health counts each once.", + args: args{in: FromCompReport(nestedCompReport(3), nil, nil)}, + want: want{ + composites: `[` + `{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged","composition":` + comp + `,"health":{"state":"healthy"},` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"a-cm"},"health":` + failingJSON + `}]},` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":` + notReadyJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"b-cm"},"health":` + notReadyJSON + `}]}` + `,` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XZone","name":"grand"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"health":` + failingJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"c-cm"},"health":{"state":"paused"}}]}]`, + plans: `[{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net","action":"no-op"}]`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":2,"failing":1,"notReady":1,"paused":1},"deferred":0}`, + }, + }, } for name, tc := range cases { @@ -382,7 +415,7 @@ func TestRenderJSONHealth(t *testing.T) { if err := json.Unmarshal(buf.Bytes(), &back); err != nil { t.Fatalf("%s\nRender(json): cannot decode: %v", tc.reason, err) } - if diff := cmp.Diff(tc.args.in, back); diff != "" { + if diff := cmp.Diff(tc.args.in, back, cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("%s\nRender(json) round trip: -want, +got:\n%s", tc.reason, diff) } }) @@ -533,6 +566,51 @@ XR: XSubnet.aws.platform.upbound.io crossplane-system/net-sn 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. +`, + }, + "NestedTwoLevels": { + reason: "Through the assembler, a nested XR with health lists what it composes and its parent lists only its own.", + args: args{r: FromCompReport(nestedCompReport(2), nil, nil)}, + want: `[=] Composition.apiextensions.crossplane.io net (no-op) + +XR: XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet.example.org child ⚠ not ready (Ready=False, Creating) + ↳ composed by XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. b-cm ⚠ not ready (Ready=False, Creating) + +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. + +Note: Provider plan not run. +`, + }, + "NestedThreeLevels": { + reason: "Through the assembler, in a chain of three XRs with health each unhealthy resource is listed once, under the deepest XR.", + args: args{r: FromCompReport(nestedCompReport(3), nil, nil)}, + want: `[=] Composition.apiextensions.crossplane.io net (no-op) + +XR: XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet.example.org child ⚠ not ready (Ready=False, Creating) + ↳ composed by XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. b-cm ⚠ not ready (Ready=False, Creating) + +XR: XZone.example.org grand ⚠ failing (Synced=False, ReconcileError): boom + ↳ composed by XSubnet.example.org child + Unhealthy resources without changes: + ConfigMap. c-cm ⚠ paused + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 of 3 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready, 1 paused. + +Note: Provider plan not run. `, }, "UngroupedDelete": { @@ -559,6 +637,10 @@ Health: 1 resource failing (Synced=False). if diff := cmp.Diff(tc.want, buf.String()); diff != "" { t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) } + // Exit bit 4 is set exactly when the Health: line counts a failing item. + if got, want := tc.args.r.Failing(), anyFailing(tc.args.r); got != want { + t.Errorf("\n%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got, tc.args.r.HealthLine()) + } }) } } @@ -611,3 +693,34 @@ func TestResultFailing(t *testing.T) { }) } } + +// nestedCompReport returns a composition run whose one composition reaches +// the XR xrRef composing a nested XR XSubnet "child", which at depth 3 +// composes XZone "grand". Each XR has an impact with health of its own, and +// each composes one unhealthy ConfigMap named for it. A parent's composed +// health holds every level below it, with Via naming the XR between. +func nestedCompReport(depth int) *dt.CompDiffOutput { + failing := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() + paused := ht.NewHealth(health.Paused).Build() + cm := func(name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Name: name} + } + child := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"} + grand := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XZone", Name: "grand"} + + top := []dt.ResourceHealth{{ObjectReference: cm("a-cm"), Health: failing}, {ObjectReference: child, Health: notReady}, {ObjectReference: cm("b-cm"), Via: &child, Health: notReady}} + mid := []dt.ResourceHealth{{ObjectReference: cm("b-cm"), Health: notReady}} + if depth == 3 { + top = append(top, dt.ResourceHealth{ObjectReference: grand, Via: &child, Health: failing}, dt.ResourceHealth{ObjectReference: cm("c-cm"), Via: &grand, Health: paused}) + mid = append(mid, dt.ResourceHealth{ObjectReference: grand, Health: failing}, dt.ResourceHealth{ObjectReference: cm("c-cm"), Via: &grand, Health: paused}) + } + impacts := []dt.XRImpact{ + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: ht.NewHealth(health.Healthy).Build(), Composed: top}}, + {ObjectReference: child, ComposedBy: &xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: notReady, Composed: mid}}, + } + if depth == 3 { + impacts = append(impacts, dt.XRImpact{ObjectReference: grand, ComposedBy: &child, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: cm("c-cm"), Health: paused}}}}) + } + return &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{{Name: "net", ImpactAnalysis: impacts}}} +} diff --git a/internal/simulate/run.go b/internal/simulate/run.go index d063eafe8..4c7ace611 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -516,25 +516,46 @@ func (c *Runner) notes() []string { // renderReport does. 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. - r = AnnotateXRReport(r, plans) - return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) + res := FromXRReport(r, plans, c.keep) + return c.renderReport(k, logger, runErr, res, r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { + return renderXRDiff(logger, opts, r, plans, res) }) } +// renderXRDiff writes r, the xr run res came from, as the human diff, with +// res's health. +func renderXRDiff(logger logging.Logger, opts renderer.DiffOptions, r *dt.XRReport, plans *ProviderPlans, res Result) error { + // The Health: line counts the plans, as summary.health does. + opts.Health = res.run + // Annotated even without plans, so a Secret's values are redacted. + r = AnnotateXRReport(r, plans) + return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) +} + // 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) (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 { + res := FromCompReport(o, plans, c.keep) + return c.renderReport(k, logger, runErr, res, o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { opts.MinimizeComposition = c.sel.MinimizeComposition - // Annotated even without plans, so a Secret's values are redacted. - o = AnnotateCompReport(o, plans) - return renderer.NewDefaultCompDiffRenderer(logger, renderer.NewDiffRenderer(logger, opts), opts).RenderCompDiff(o) + return renderCompDiff(logger, opts, o, plans, res) }) } +// renderCompDiff writes o, the composition run res came from, as the human +// diff, with res's health. +func renderCompDiff(logger logging.Logger, opts renderer.DiffOptions, o *dt.CompDiffOutput, plans *ProviderPlans, res Result) error { + // The inner renderer sees only identity-less groups, whose composites + // are not the run's, so it gets no health. + inner := renderer.NewDiffRenderer(logger, opts) + // The Health: line counts the plans, as summary.health does. + opts.Health = res.run + // Annotated even without plans, so a Secret's values are redacted. + o = AnnotateCompReport(o, plans) + return renderer.NewDefaultCompDiffRenderer(logger, inner, opts).RenderCompDiff(o) +} + // 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 // the run's outcome: whether it changed anything, provider plans included,