Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/crossplane/simulate/simulate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
24 changes: 24 additions & 0 deletions cmd/crossplane/simulate/simulate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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"}}},
Expand All @@ -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)
}
})
}
}
Expand Down
92 changes: 38 additions & 54 deletions internal/diff/renderer/comp_diff_renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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")
}
Expand All @@ -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 {
Expand All @@ -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
Expand All @@ -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)
}
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
}
Expand All @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions internal/diff/renderer/diff_formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
44 changes: 24 additions & 20 deletions internal/diff/renderer/diff_renderer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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
}
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Loading
Loading