From 46d4d17045e7cf126dca4571dbe0f0ae82b26dfd Mon Sep 17 00:00:00 2001 From: Christopher Haar Date: Tue, 3 Nov 2026 10:07:08 +0100 Subject: [PATCH 1/5] feat(trace): add operations trace option Signed-off-by: Christopher Haar --- cmd/crossplane/trace/help/trace.md | 27 ++ .../trace/internal/printer/default.go | 35 +- cmd/crossplane/trace/internal/printer/dot.go | 7 + cmd/crossplane/trace/trace.go | 26 +- cmd/crossplane/trace/watch.go | 7 + pkg/resource/ops/ops.go | 344 ++++++++++++++++++ pkg/resource/ops/ops_test.go | 297 +++++++++++++++ pkg/resource/resource.go | 7 +- 8 files changed, 744 insertions(+), 6 deletions(-) create mode 100644 pkg/resource/ops/ops.go create mode 100644 pkg/resource/ops/ops_test.go diff --git a/cmd/crossplane/trace/help/trace.md b/cmd/crossplane/trace/help/trace.md index cb249c4e..c86df9dc 100644 --- a/cmd/crossplane/trace/help/trace.md +++ b/cmd/crossplane/trace/help/trace.md @@ -46,6 +46,26 @@ Use `--show-connection-secrets` to include connection-secret names alongside the other resources. Secret values are never printed. Output includes the secret name and namespace. +## Print related operations + +The `--show-operations` flag controls the display of operations +(`ops.crossplane.io`) related to each traced resource: + +- `none` (default): hide operations. +- `triggered`: show the WatchOperations watching each resource, with the + Operations they created in response to changes to it as children. +- `all`: additionally show the Operations that applied changes to each + resource, grouped under the CronOperation or WatchOperation that created + them, if any. + +Operations are not part of the resource tree, they only relate to it, so the +default output marks them with an arrow (`├◀`) pointing at the resource they +relate to. The structured output formats include the relation (`watching`, +`triggered` or `applied`) as a `relation` field instead. + +The flag has no effect when tracing packages, or when the cluster doesn't +support operations. + ## Print package dependencies The `--show-package-dependencies` flag controls how the display of package @@ -89,6 +109,13 @@ Show connection secret names alongside the resources: crossplane resource trace mykind my-res -n my-ns --show-connection-secrets ``` +Show all operations related to the resources, e.g. the WatchOperations +watching them and the Operations that changed them: + +```shell +crossplane resource trace mykind my-res -n my-ns --show-operations=all +``` + Output a Graphviz dot graph and pipe to dot to generate a PNG: ```shell diff --git a/cmd/crossplane/trace/internal/printer/default.go b/cmd/crossplane/trace/internal/printer/default.go index 32f69618..c749e5d1 100644 --- a/cmd/crossplane/trace/internal/printer/default.go +++ b/cmd/crossplane/trace/internal/printer/default.go @@ -32,6 +32,7 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/xcrd" xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2" + opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" pkgv1 "github.com/crossplane/crossplane/apis/v2/pkg/v1" "github.com/crossplane/cli/v2/pkg/resource" @@ -207,6 +208,9 @@ func (p *DefaultPrinter) printResourceTree(tw *tabwriter.Writer, root *resource. depth int isLast bool prefix string + // related is true if an ancestor of this resource is not part of + // the tree, but only related to it, e.g. an operation watching it. + related bool } // Initialize LIFO queue with root element to traverse the tree depth-first, @@ -224,17 +228,27 @@ func (p *DefaultPrinter) printResourceTree(tw *tabwriter.Writer, root *resource. // show the tree structure name := strings.Builder{} + // Resources that are not part of the tree, but only related to it, + // e.g. an operation watching the parent resource, get an arrow + // pointing at the resource they relate to instead of a tree line. + // Their own children are real children, e.g. an Operation created + // by a WatchOperation, so they get regular tree lines. + line := "─" + if item.resource.Relation != "" && !item.related { + line = "◀" + } + childPrefix := item.prefix // Inherited prefix for all the children of the current node switch { case item.depth == 0: // We don't need a prefix for the root, nor a custom // prefix for its children case item.isLast: - name.WriteString(item.prefix + "└─ ") + name.WriteString(item.prefix + "└" + line + " ") childPrefix += " " default: - name.WriteString(item.prefix + "├─ ") + name.WriteString(item.prefix + "├" + line + " ") childPrefix += "│ " } @@ -262,7 +276,8 @@ func (p *DefaultPrinter) printResourceTree(tw *tabwriter.Writer, root *resource. // the way they are defined by the resources. for idx, child := range slices.Backward(item.resource.Children) { isLast := idx == len(item.resource.Children)-1 - queue = append(queue, &queueItem{resource: child, depth: item.depth + 1, isLast: isLast, prefix: childPrefix}) + related := item.related || item.resource.Relation != "" + queue = append(queue, &queueItem{resource: child, depth: item.depth + 1, isLast: isLast, prefix: childPrefix, related: related}) } } return nil @@ -271,7 +286,19 @@ func (p *DefaultPrinter) printResourceTree(tw *tabwriter.Writer, root *resource. // getResourceStatus returns a string that represents an entire row of status // information for the resource. func getResourceStatus(r *resource.Resource, name string, wide bool) fmt.Stringer { - readyCond := r.GetCondition(xpv2.TypeReady) + // Operations don't have a Ready condition, show the condition + // representing their lifecycle in the READY column instead. + readyType := xpv2.TypeReady + switch r.Unstructured.GroupVersionKind().GroupKind() { + case opsv1alpha1.OperationGroupVersionKind.GroupKind(): + readyType = opsv1alpha1.TypeSucceeded + case opsv1alpha1.WatchOperationGroupVersionKind.GroupKind(): + readyType = opsv1alpha1.TypeWatching + case opsv1alpha1.CronOperationGroupVersionKind.GroupKind(): + readyType = opsv1alpha1.TypeScheduling + } + + readyCond := r.GetCondition(readyType) syncedCond := r.GetCondition(xpv2.TypeSynced) var status, m string diff --git a/cmd/crossplane/trace/internal/printer/dot.go b/cmd/crossplane/trace/internal/printer/dot.go index 3fd18887..4deb8010 100644 --- a/cmd/crossplane/trace/internal/printer/dot.go +++ b/cmd/crossplane/trace/internal/printer/dot.go @@ -28,6 +28,7 @@ type dotLabel struct { name string ready string synced string + relation string error string } @@ -50,6 +51,11 @@ func (r *dotLabel) String() string { "Ready: "+r.ready, "Synced: "+r.synced, ) + if r.relation != "" { + out = append(out, + "Relation: "+r.relation, + ) + } if r.error != "" { out = append(out, "Error: "+r.error, @@ -196,6 +202,7 @@ func printGraphQueue(g *dot.Graph, queue []*queueItem) { name: fmt.Sprintf("%s/%s", item.resource.Unstructured.GetKind(), item.resource.Unstructured.GetName()), ready: string(item.resource.GetCondition(xpv2.TypeReady).Status), synced: string(item.resource.GetCondition(xpv2.TypeSynced).Status), + relation: item.resource.Relation, } } diff --git a/cmd/crossplane/trace/trace.go b/cmd/crossplane/trace/trace.go index c8cb2ed8..48630ecb 100644 --- a/cmd/crossplane/trace/trace.go +++ b/cmd/crossplane/trace/trace.go @@ -31,12 +31,14 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/errors" "github.com/crossplane/crossplane-runtime/v2/pkg/logging" + opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" "github.com/crossplane/crossplane/apis/v2/pkg" "github.com/crossplane/cli/v2/cmd/crossplane/internal" "github.com/crossplane/cli/v2/cmd/crossplane/trace/internal/printer" "github.com/crossplane/cli/v2/internal/kube" "github.com/crossplane/cli/v2/pkg/resource" + "github.com/crossplane/cli/v2/pkg/resource/ops" "github.com/crossplane/cli/v2/pkg/resource/xpkg" "github.com/crossplane/cli/v2/pkg/resource/xrm" @@ -57,6 +59,7 @@ const ( errGetDiscoveryClient = "cannot get discovery client" errGetMapping = "cannot get mapping for resource" errInitPrinter = "cannot init new printer" + errGetOperations = "cannot get related operations" errNameDoubled = "name provided twice, must be provided separately 'TYPE[.VERSION][.GROUP] [NAME]' or in the 'TYPE[.VERSION][.GROUP][/NAME]' format" errInvalidResource = "invalid resource, must be provided in the 'TYPE[.VERSION][.GROUP][/NAME]' format" errInvalidResourceAndName = "invalid resource and name" @@ -72,6 +75,7 @@ type Cmd struct { Namespace string `default:"" help:"Namespace of the resource." name:"namespace" predictor:"namespace" short:"n"` Output string `default:"default" enum:"default,wide,json,dot,yaml" help:"Output format. One of: default, wide, json, dot, yaml." name:"output" short:"o"` ShowConnectionSecrets bool `help:"Show connection secrets in the output." name:"show-connection-secrets" short:"s"` + ShowOperations string `default:"none" enum:"none,triggered,all" help:"Show operations related to each resource. One of: none, triggered, all." name:"show-operations"` ShowPackageDependencies string `default:"unique" enum:"unique,all,none" help:"Show package dependencies in the output. One of: unique, all, none." name:"show-package-dependencies"` ShowPackageRevisions string `default:"active" enum:"active,all,none" help:"Show package revisions in the output. One of: active, all, none." name:"show-package-revisions"` ShowPackageRuntimeConfigs bool `default:"false" help:"Show package runtime configs in the output." name:"show-package-runtime-configs"` @@ -121,8 +125,9 @@ func (c *Cmd) setupKubeClient(logger logging.Logger) (clientcmd.ClientConfig, cl return nil, nil, nil, errors.Wrap(err, errInitKubeClient) } - // add package scheme + // add package and operations schemes _ = pkg.AddToScheme(cl.Scheme()) + _ = opsv1alpha1.AddToScheme(cl.Scheme()) // TODO(phisco): properly handle flags and switch to file backed cache // (restmapper.NewDeferredDiscoveryRESTMapper), as cli-runtime @@ -224,6 +229,14 @@ func (c *Cmd) Run(k *kong.Context, logger logging.Logger) error { resourceList.Items[i] = root } + // Attach related operations, if requested. Operations target Crossplane + // resources, not packages, so there's nothing to attach on package trees. + if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { + if err := c.enrichOperations(ctx, client, resourceList.Items...); err != nil { + return errors.Wrap(err, errGetOperations) + } + } + // Watch mode for a single resource if c.Watch && !shouldPrintAsList && len(resourceList.Items) > 0 { root := resourceList.Items[0] @@ -284,6 +297,17 @@ func (c *Cmd) getResourceAndName() (string, string, error) { return "", "", errors.New(errInvalidResource) } +// enrichOperations attaches the operations related to each resource in the +// given trees, per the --show-operations flag. +func (c *Cmd) enrichOperations(ctx context.Context, client client.Client, roots ...*resource.Resource) error { + mode := ops.Mode(c.ShowOperations) + if mode == ops.ModeNone { + return nil + } + + return ops.NewEnricher(client, mode).Enrich(ctx, roots...) +} + func (c *Cmd) getResourceTree(ctx context.Context, root *resource.Resource, mapping *meta.RESTMapping, client client.Client, logger logging.Logger) (*resource.Resource, error) { var treeClient resource.TreeClient var err error diff --git a/cmd/crossplane/trace/watch.go b/cmd/crossplane/trace/watch.go index a49e0ff6..1311e718 100644 --- a/cmd/crossplane/trace/watch.go +++ b/cmd/crossplane/trace/watch.go @@ -36,6 +36,7 @@ import ( "github.com/crossplane/cli/v2/cmd/crossplane/trace/internal/printer" "github.com/crossplane/cli/v2/pkg/resource" + "github.com/crossplane/cli/v2/pkg/resource/xpkg" ) // Bubble Tea messages for watch mode. @@ -166,6 +167,12 @@ func (c *Cmd) watchProducer(ctx context.Context, logger logging.Logger, kClient return err } + if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { + if err := c.enrichOperations(ctx, kClient, tree); err != nil { + return errors.Wrap(err, errGetOperations) + } + } + logger.Debug("Got resource tree", "root", tree) rendered, err := renderTreeToString(p, tree) diff --git a/pkg/resource/ops/ops.go b/pkg/resource/ops/ops.go new file mode 100644 index 00000000..0ede1a28 --- /dev/null +++ b/pkg/resource/ops/ops.go @@ -0,0 +1,344 @@ +/* +Copyright 2025 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 ops enriches a tree of Resource with the operations +// (ops.crossplane.io) related to each resource: the WatchOperations watching +// it, the Operations they created in response to changes to it, and the +// Operations that applied changes to it. +package ops + +import ( + "context" + "sort" + + "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + + "github.com/crossplane/crossplane-runtime/v2/pkg/errors" + + opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" + + "github.com/crossplane/cli/v2/pkg/resource" +) + +const ( + errListWatchOperations = "cannot list watch operations" + errListCronOperations = "cannot list cron operations" + errListOperations = "cannot list operations" +) + +// Mode determines which operations related to a resource are shown. +type Mode string + +const ( + // ModeNone shows no operations. + ModeNone Mode = "none" + // ModeTriggered shows the WatchOperations watching a resource and the + // Operations they created in response to changes to it. + ModeTriggered Mode = "triggered" + // ModeAll additionally shows the Operations that applied changes to a + // resource, grouped under the CronOperation or WatchOperation that + // created them, if any. + ModeAll Mode = "all" +) + +// Relations set on the operations attached to a resource, to make clear they +// are not part of the resource tree, but only related to it. +const ( + // RelationWatching marks a WatchOperation watching the resource. + RelationWatching = "watching" + // RelationTriggered marks an Operation created in response to a change + // to the resource. + RelationTriggered = "triggered" + // RelationApplied marks an Operation that applied changes to the + // resource, or the CronOperation or WatchOperation that created one. + RelationApplied = "applied" +) + +// Enricher attaches the operations related to each resource in a tree of +// Resource as children of the resource they relate to. +type Enricher struct { + client client.Client + mode Mode +} + +// NewEnricher returns a new Enricher showing operations per the given Mode. +func NewEnricher(c client.Client, m Mode) *Enricher { + return &Enricher{client: c, mode: m} +} + +// Enrich attaches the operations related to each resource in the given trees +// as children of the resource they relate to. It's a no-op if the operations +// API is not available in the cluster. +func (e *Enricher) Enrich(ctx context.Context, roots ...*resource.Resource) error { + if e.mode == ModeNone { + return nil + } + + s, err := e.load(ctx) + if err != nil { + return err + } + + if s == nil { + // The cluster doesn't support operations at all. + return nil + } + + for _, r := range roots { + enrich(r, s, e.mode) + } + + return nil +} + +// snapshot holds all the operations in the cluster, to be matched against the +// resources in the tree. +type snapshot struct { + watchOps []opsv1alpha1.WatchOperation + cronOps map[string]opsv1alpha1.CronOperation + ops []opsv1alpha1.Operation +} + +// load returns a snapshot of all the operations in the cluster, or a nil +// snapshot without error if the cluster doesn't support the operations API. +func (e *Enricher) load(ctx context.Context) (*snapshot, error) { + wl := &opsv1alpha1.WatchOperationList{} + if err := e.client.List(ctx, wl); err != nil { + if meta.IsNoMatchError(err) || runtime.IsNotRegisteredError(err) { + return nil, nil + } + + return nil, errors.Wrap(err, errListWatchOperations) + } + + ol := &opsv1alpha1.OperationList{} + if err := e.client.List(ctx, ol); err != nil { + return nil, errors.Wrap(err, errListOperations) + } + + s := &snapshot{watchOps: wl.Items, ops: ol.Items} + + // CronOperations never target a specific resource themselves, they are + // only needed to group the Operations they created that applied one. + if e.mode == ModeAll { + cl := &opsv1alpha1.CronOperationList{} + if err := e.client.List(ctx, cl); err != nil { + return nil, errors.Wrap(err, errListCronOperations) + } + + s.cronOps = make(map[string]opsv1alpha1.CronOperation, len(cl.Items)) + for _, co := range cl.Items { + s.cronOps[co.GetName()] = co + } + } + + return s, nil +} + +func (s *snapshot) watchOp(name string) *opsv1alpha1.WatchOperation { + for i := range s.watchOps { + if s.watchOps[i].GetName() == name { + return &s.watchOps[i] + } + } + + return nil +} + +// enrich walks the tree depth-first and appends the operations related to +// each resource as its children. Only the original tree is walked, the +// attached operations are not enriched themselves. +func enrich(r *resource.Resource, s *snapshot, mode Mode) { + for _, c := range r.Children { + enrich(c, s, mode) + } + + r.Children = append(r.Children, relatedOperations(r, s, mode)...) +} + +// relatedOperations returns the operations related to the given resource: +// WatchOperations watching it with the Operations they created for it as +// children and, in ModeAll, the Operations that applied changes to it grouped +// under the WatchOperation or CronOperation that created them, if any. +func relatedOperations(r *resource.Resource, s *snapshot, mode Mode) []*resource.Resource { + var related []*resource.Resource + + branches := map[string]*resource.Resource{} + branchFor := func(o client.Object, gvk schema.GroupVersionKind, relation string) *resource.Resource { + key := gvk.Kind + "/" + o.GetName() + if b, ok := branches[key]; ok { + return b + } + + b := asResource(o, gvk, relation) + branches[key] = b + related = append(related, b) + + return b + } + + attached := map[string]bool{} + + // WatchOperations watching this resource, with the Operations they + // created in response to changes to it as children. + for i := range s.watchOps { + wo := &s.watchOps[i] + if !watchMatches(wo.Spec.Watch, &r.Unstructured) { + continue + } + + b := branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationWatching) + + for j := range s.ops { + op := &s.ops[j] + if op.GetLabels()[opsv1alpha1.LabelWatchOperationName] != wo.GetName() || !triggeredBy(op, &r.Unstructured) { + continue + } + + b.Children = append(b.Children, asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationTriggered)) + attached[op.GetName()] = true + } + } + + if mode == ModeAll { + // Operations that applied changes to this resource, grouped under + // the WatchOperation or CronOperation that created them, if any. + for i := range s.ops { + op := &s.ops[i] + if attached[op.GetName()] || !applied(op, &r.Unstructured) { + continue + } + + attached[op.GetName()] = true + child := asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationApplied) + + if owner := metav1.GetControllerOf(op); owner != nil && owner.APIVersion == opsv1alpha1.SchemeGroupVersion.String() { + switch owner.Kind { + case opsv1alpha1.WatchOperationKind: + if wo := s.watchOp(owner.Name); wo != nil { + b := branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationApplied) + appendChild(b, child) + + continue + } + case opsv1alpha1.CronOperationKind: + if co, ok := s.cronOps[owner.Name]; ok { + b := branchFor(&co, opsv1alpha1.CronOperationGroupVersionKind, RelationApplied) + appendChild(b, child) + + continue + } + } + } + + related = append(related, child) + } + } + + for _, b := range related { + sortByCreation(b.Children) + } + + return related +} + +// appendChild appends the child to the branch, dropping the child's relation +// if it would just repeat the branch's one. +func appendChild(b, child *resource.Resource) { + if child.Relation == b.Relation { + child.Relation = "" + } + + b.Children = append(b.Children, child) +} + +// watchMatches returns true if the given watch spec selects the given +// resource. +func watchMatches(w opsv1alpha1.WatchSpec, u *unstructured.Unstructured) bool { + if w.APIVersion != u.GetAPIVersion() || w.Kind != u.GetKind() { + return false + } + + if w.Namespace != "" && w.Namespace != u.GetNamespace() { + return false + } + + labels := u.GetLabels() + for k, v := range w.MatchLabels { + if labels[k] != v { + return false + } + } + + return true +} + +// triggeredBy returns true if the Operation is annotated as having been +// created in response to a change to the given resource. +func triggeredBy(op *opsv1alpha1.Operation, u *unstructured.Unstructured) bool { + a := op.GetAnnotations() + + return a[opsv1alpha1.AnnotationWatchedResourceAPIVersion] == u.GetAPIVersion() && + a[opsv1alpha1.AnnotationWatchedResourceKind] == u.GetKind() && + a[opsv1alpha1.AnnotationWatchedResourceName] == u.GetName() && + a[opsv1alpha1.AnnotationWatchedResourceNamespace] == u.GetNamespace() +} + +// applied returns true if the Operation reports having applied changes to the +// given resource. +func applied(op *opsv1alpha1.Operation, u *unstructured.Unstructured) bool { + for _, ref := range op.Status.AppliedResourceRefs { + if ref.APIVersion == u.GetAPIVersion() && ref.Kind == u.GetKind() && + ref.Name == u.GetName() && ptr.Deref(ref.Namespace, "") == u.GetNamespace() { + return true + } + } + + return false +} + +func asResource(o client.Object, gvk schema.GroupVersionKind, relation string) *resource.Resource { + obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(o) + if err != nil { + u := unstructured.Unstructured{} + u.SetGroupVersionKind(gvk) + u.SetName(o.GetName()) + + return &resource.Resource{Unstructured: u, Error: err, Relation: relation} + } + + u := unstructured.Unstructured{Object: obj} + u.SetGroupVersionKind(gvk) + + return &resource.Resource{Unstructured: u, Relation: relation} +} + +func sortByCreation(rs []*resource.Resource) { + sort.SliceStable(rs, func(i, j int) bool { + ti, tj := rs[i].Unstructured.GetCreationTimestamp(), rs[j].Unstructured.GetCreationTimestamp() + if ti.Equal(&tj) { + return rs[i].Unstructured.GetName() < rs[j].Unstructured.GetName() + } + + return ti.Before(&tj) + }) +} diff --git a/pkg/resource/ops/ops_test.go b/pkg/resource/ops/ops_test.go new file mode 100644 index 00000000..ef7d6095 --- /dev/null +++ b/pkg/resource/ops/ops_test.go @@ -0,0 +1,297 @@ +/* +Copyright 2025 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 ops + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/utils/ptr" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + + opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" + + "github.com/crossplane/cli/v2/pkg/resource" +) + +func buildResource(apiVersion, kind, namespace, name string, labels map[string]string) *resource.Resource { + u := unstructured.Unstructured{} + u.SetAPIVersion(apiVersion) + u.SetKind(kind) + u.SetNamespace(namespace) + u.SetName(name) + u.SetLabels(labels) + + return &resource.Resource{Unstructured: u} +} + +func buildWatchOp(name string, watch opsv1alpha1.WatchSpec) *opsv1alpha1.WatchOperation { + return &opsv1alpha1.WatchOperation{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: opsv1alpha1.WatchOperationSpec{Watch: watch}, + } +} + +type operationOpt func(*opsv1alpha1.Operation) + +func triggeredByResource(apiVersion, kind, namespace, name string) operationOpt { + return func(op *opsv1alpha1.Operation) { + op.SetAnnotations(map[string]string{ + opsv1alpha1.AnnotationWatchedResourceAPIVersion: apiVersion, + opsv1alpha1.AnnotationWatchedResourceKind: kind, + opsv1alpha1.AnnotationWatchedResourceNamespace: namespace, + opsv1alpha1.AnnotationWatchedResourceName: name, + }) + } +} + +func ownedBy(kind, name string) operationOpt { + return func(op *opsv1alpha1.Operation) { + op.SetOwnerReferences([]metav1.OwnerReference{{ + APIVersion: opsv1alpha1.SchemeGroupVersion.String(), + Kind: kind, + Name: name, + Controller: ptr.To(true), + }}) + if kind == opsv1alpha1.WatchOperationKind { + op.SetLabels(map[string]string{opsv1alpha1.LabelWatchOperationName: name}) + } + } +} + +func appliedResource(apiVersion, kind, namespace, name string) operationOpt { + return func(op *opsv1alpha1.Operation) { + ref := opsv1alpha1.AppliedResourceRef{APIVersion: apiVersion, Kind: kind, Name: name} + if namespace != "" { + ref.Namespace = ptr.To(namespace) + } + + op.Status.AppliedResourceRefs = append(op.Status.AppliedResourceRefs, ref) + } +} + +func buildOperation(name string, opts ...operationOpt) *opsv1alpha1.Operation { + op := &opsv1alpha1.Operation{ObjectMeta: metav1.ObjectMeta{Name: name}} + for _, o := range opts { + o(op) + } + + return op +} + +// kindNames flattens a tree of Resource into "Kind/name relation=" +// strings, children indented by depth, to easily assert on the tree shape and +// the Relation field set on the nodes attached by the Enricher. +func kindNames(r *resource.Resource, depth int) []string { + prefix := "" + for range depth { + prefix += " " + } + + line := prefix + r.Unstructured.GetKind() + "/" + r.Unstructured.GetName() + if r.Relation != "" { + line += " relation=" + r.Relation + } + + out := []string{line} + for _, c := range r.Children { + out = append(out, kindNames(c, depth+1)...) + } + + return out +} + +func TestEnrich(t *testing.T) { + s := runtime.NewScheme() + if err := opsv1alpha1.AddToScheme(s); err != nil { + t.Fatalf("cannot build scheme: %v", err) + } + + type args struct { + mode Mode + objects []client.Object + root *resource.Resource + } + + cases := map[string]struct { + reason string + args args + want []string + }{ + "ModeNoneAttachesNothing": { + reason: "Should not attach anything when mode is none.", + args: args{ + mode: ModeNone, + objects: []client.Object{ + buildWatchOp("watch-all", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + }, + }, + "TriggeredAttachesWatchOperationsAndTheirOperations": { + reason: "Should attach WatchOperations watching the resource, with the Operations they created for it as children, excluding Operations triggered by other resources.", + args: args{ + mode: ModeTriggered, + objects: []client.Object{ + buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), + buildWatchOp("watch-others", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Other"}), + buildOperation("watch-things-123", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + triggeredByResource("example.org/v1", "Thing", "default", "my-thing")), + buildOperation("watch-things-456", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + triggeredByResource("example.org/v1", "Thing", "default", "another-thing")), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + " WatchOperation/watch-things relation=watching", + " Operation/watch-things-123 relation=triggered", + }, + }, + "TriggeredRespectsNamespaceAndLabels": { + reason: "Should not attach WatchOperations whose watch namespace or labels don't match the resource.", + args: args{ + mode: ModeTriggered, + objects: []client.Object{ + buildWatchOp("wrong-namespace", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing", Namespace: "other"}), + buildWatchOp("wrong-labels", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing", MatchLabels: map[string]string{"type": "wall"}}), + buildWatchOp("matching-labels", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing", Namespace: "default", MatchLabels: map[string]string{"type": "radiator"}}), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", map[string]string{"type": "radiator"}), + }, + want: []string{ + "Thing/my-thing", + " WatchOperation/matching-labels relation=watching", + }, + }, + "AllGroupsAppliedOperationsUnderTheirCreator": { + reason: "Should attach Operations that applied the resource under the CronOperation that created them, and standalone ones directly.", + args: args{ + mode: ModeAll, + objects: []client.Object{ + &opsv1alpha1.CronOperation{ObjectMeta: metav1.ObjectMeta{Name: "nightly"}}, + buildOperation("nightly-123", + ownedBy(opsv1alpha1.CronOperationKind, "nightly"), + appliedResource("example.org/v1", "Thing", "default", "my-thing")), + buildOperation("standalone", + appliedResource("example.org/v1", "Thing", "default", "my-thing")), + buildOperation("other-resource", + appliedResource("example.org/v1", "Thing", "default", "another-thing")), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + " CronOperation/nightly relation=applied", + " Operation/nightly-123", + " Operation/standalone relation=applied", + }, + }, + "AllDoesNotDuplicateTriggeredOperations": { + reason: "Should attach an Operation both triggered by and applying the resource only once, under its WatchOperation.", + args: args{ + mode: ModeAll, + objects: []client.Object{ + buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), + buildOperation("watch-things-123", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + triggeredByResource("example.org/v1", "Thing", "default", "my-thing"), + appliedResource("example.org/v1", "Thing", "default", "my-thing")), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + " WatchOperation/watch-things relation=watching", + " Operation/watch-things-123 relation=triggered", + }, + }, + "EnrichesChildrenToo": { + reason: "Should attach operations to the resources deeper in the tree, e.g. an Operation triggered by a watched resource applying a sibling.", + args: args{ + mode: ModeAll, + objects: []client.Object{ + buildWatchOp("watch-walls", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing", MatchLabels: map[string]string{"type": "wall"}}), + buildOperation("watch-walls-123", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-walls"), + triggeredByResource("example.org/v1", "Thing", "default", "wall"), + appliedResource("example.org/v1", "Thing", "default", "radiator")), + }, + root: func() *resource.Resource { + root := buildResource("example.org/v1", "XThings", "default", "my-xr", nil) + root.Children = []*resource.Resource{ + buildResource("example.org/v1", "Thing", "default", "wall", map[string]string{"type": "wall"}), + buildResource("example.org/v1", "Thing", "default", "radiator", map[string]string{"type": "radiator"}), + } + + return root + }(), + }, + want: []string{ + "XThings/my-xr", + " Thing/wall", + " WatchOperation/watch-walls relation=watching", + " Operation/watch-walls-123 relation=triggered", + " Thing/radiator", + " WatchOperation/watch-walls relation=applied", + " Operation/watch-walls-123", + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(s).WithObjects(tc.args.objects...).Build() + + e := NewEnricher(c, tc.args.mode) + if err := e.Enrich(context.Background(), tc.args.root); err != nil { + t.Fatalf("\n%s\nEnrich(...): unexpected error: %v", tc.reason, err) + } + + if diff := cmp.Diff(tc.want, kindNames(tc.args.root, 0)); diff != "" { + t.Errorf("\n%s\nEnrich(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestEnrichNoOpsAPI(t *testing.T) { + // A scheme without the ops types registered, as a stand-in for a cluster + // that doesn't support operations. + c := fake.NewClientBuilder().WithScheme(runtime.NewScheme()).Build() + + root := buildResource("example.org/v1", "Thing", "default", "my-thing", nil) + + e := NewEnricher(c, ModeAll) + if err := e.Enrich(context.Background(), root); err != nil { + t.Errorf("Enrich(...): expected no error when the ops API is not available, got: %v", err) + } + + if diff := cmp.Diff([]string{"Thing/my-thing"}, kindNames(root, 0)); diff != "" { + t.Errorf("Enrich(...): -want, +got:\n%s", diff) + } +} diff --git a/pkg/resource/resource.go b/pkg/resource/resource.go index f959cb01..0d6abb29 100644 --- a/pkg/resource/resource.go +++ b/pkg/resource/resource.go @@ -30,7 +30,12 @@ import ( type Resource struct { Unstructured unstructured.Unstructured `json:"object"` Error error `json:"error,omitempty"` - Children []*Resource `json:"children,omitempty"` + + // Relation describes why this resource is in the tree when it's not + // actually part of it, e.g. an operation watching the parent resource. + Relation string `json:"relation,omitempty"` + + Children []*Resource `json:"children,omitempty"` } // ResourceList struct represents a list of kubernetes resources. From dd5f6d120577996941910348bf9637f94b5e4dc1 Mon Sep 17 00:00:00 2001 From: Christopher Haar Date: Tue, 3 Nov 2026 10:24:43 +0100 Subject: [PATCH 2/5] lint(refactor): make the linter happy Signed-off-by: Christopher Haar --- cmd/crossplane/trace/trace.go | 62 ++++++++++------- cmd/crossplane/trace/watch.go | 68 ++++++++++-------- pkg/resource/ops/ops.go | 125 +++++++++++++++++++++------------- pkg/resource/ops/ops_test.go | 9 +-- 4 files changed, 158 insertions(+), 106 deletions(-) diff --git a/cmd/crossplane/trace/trace.go b/cmd/crossplane/trace/trace.go index 48630ecb..fc8d1e1c 100644 --- a/cmd/crossplane/trace/trace.go +++ b/cmd/crossplane/trace/trace.go @@ -71,16 +71,16 @@ type Cmd struct { Name string `arg:"" help:"Name of the Crossplane resource, if not passed as part of the resource." optional:"" predictor:"k8s_resource_name"` // TODO(phisco): add support for all the usual kubectl flags; configFlags := genericclioptions.NewConfigFlags(true).AddFlags(...) - Context string `default:"" help:"Kubernetes context." name:"context" predictor:"context" short:"c"` - Namespace string `default:"" help:"Namespace of the resource." name:"namespace" predictor:"namespace" short:"n"` - Output string `default:"default" enum:"default,wide,json,dot,yaml" help:"Output format. One of: default, wide, json, dot, yaml." name:"output" short:"o"` + Context string `default:"" help:"Kubernetes context." name:"context" predictor:"context" short:"c"` + Namespace string `default:"" help:"Namespace of the resource." name:"namespace" predictor:"namespace" short:"n"` + Output string `default:"default" enum:"default,wide,json,dot,yaml" help:"Output format. One of: default, wide, json, dot, yaml." name:"output" short:"o"` ShowConnectionSecrets bool `help:"Show connection secrets in the output." name:"show-connection-secrets" short:"s"` ShowOperations string `default:"none" enum:"none,triggered,all" help:"Show operations related to each resource. One of: none, triggered, all." name:"show-operations"` - ShowPackageDependencies string `default:"unique" enum:"unique,all,none" help:"Show package dependencies in the output. One of: unique, all, none." name:"show-package-dependencies"` - ShowPackageRevisions string `default:"active" enum:"active,all,none" help:"Show package revisions in the output. One of: active, all, none." name:"show-package-revisions"` + ShowPackageDependencies string `default:"unique" enum:"unique,all,none" help:"Show package dependencies in the output. One of: unique, all, none." name:"show-package-dependencies"` + ShowPackageRevisions string `default:"active" enum:"active,all,none" help:"Show package revisions in the output. One of: active, all, none." name:"show-package-revisions"` ShowPackageRuntimeConfigs bool `default:"false" help:"Show package runtime configs in the output." name:"show-package-runtime-configs"` Concurrency int `default:"5" help:"load concurrency" name:"concurrency"` - Watch bool `default:"false" help:"Watch for changes until resource deletion." name:"watch" short:"w"` + Watch bool `default:"false" help:"Watch for changes until resource deletion." name:"watch" short:"w"` Impersonation kube.ImpersonationFlags `embed:""` } @@ -215,26 +215,8 @@ func (c *Cmd) Run(k *kong.Context, logger logging.Logger) error { return errors.Wrapf(err, errFmtGetResource, mapping.GroupVersionKind.Kind, nameDisplay, rootRef.Namespace) } - for i := range resourceList.Items { - root := resourceList.Items[i] - itemKind, itemName, itemNamespace := root.Unstructured.GetKind(), root.Unstructured.GetName(), root.Unstructured.GetNamespace() - root, err = c.getResourceTree(ctx, root, mapping, client, logger) - if err != nil { - logger.Debug(errGetResource, "error", err) - return errors.Wrapf(err, errFmtGetResourceTree, itemKind, itemName, itemNamespace) - } - - logger.Debug("Got resource tree", "root", root) - - resourceList.Items[i] = root - } - - // Attach related operations, if requested. Operations target Crossplane - // resources, not packages, so there's nothing to attach on package trees. - if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { - if err := c.enrichOperations(ctx, client, resourceList.Items...); err != nil { - return errors.Wrap(err, errGetOperations) - } + if err := c.getResourceTrees(ctx, resourceList, mapping, client, logger); err != nil { + return err } // Watch mode for a single resource @@ -297,6 +279,34 @@ func (c *Cmd) getResourceAndName() (string, string, error) { return "", "", errors.New(errInvalidResource) } +// getResourceTrees builds the resource tree of each resource in the list in +// place, attaching the related operations if requested. +func (c *Cmd) getResourceTrees(ctx context.Context, resourceList *resource.ResourceList, mapping *meta.RESTMapping, client client.Client, logger logging.Logger) error { + for i := range resourceList.Items { + root := resourceList.Items[i] + itemKind, itemName, itemNamespace := root.Unstructured.GetKind(), root.Unstructured.GetName(), root.Unstructured.GetNamespace() + root, err := c.getResourceTree(ctx, root, mapping, client, logger) + if err != nil { + logger.Debug(errGetResource, "error", err) + return errors.Wrapf(err, errFmtGetResourceTree, itemKind, itemName, itemNamespace) + } + + logger.Debug("Got resource tree", "root", root) + + resourceList.Items[i] = root + } + + // Attach related operations, if requested. Operations target Crossplane + // resources, not packages, so there's nothing to attach on package trees. + if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { + if err := c.enrichOperations(ctx, client, resourceList.Items...); err != nil { + return errors.Wrap(err, errGetOperations) + } + } + + return nil +} + // enrichOperations attaches the operations related to each resource in the // given trees, per the --show-operations flag. func (c *Cmd) enrichOperations(ctx context.Context, client client.Client, roots ...*resource.Resource) error { diff --git a/cmd/crossplane/trace/watch.go b/cmd/crossplane/trace/watch.go index 1311e718..92447c45 100644 --- a/cmd/crossplane/trace/watch.go +++ b/cmd/crossplane/trace/watch.go @@ -146,38 +146,15 @@ func (c *Cmd) watchProducer(ctx context.Context, logger logging.Logger, kClient // Helper to fetch and render the resource tree, then send to Bubble Tea renderAndSend := func() error { - current := resource.GetResource(ctx, kClient, &v1.ObjectReference{ - Kind: root.Unstructured.GetKind(), - APIVersion: root.Unstructured.GetAPIVersion(), - Name: root.Unstructured.GetName(), - Namespace: root.Unstructured.GetNamespace(), - }) - - if current.Error != nil { - if apierrors.IsNotFound(current.Error) { - logger.Debug("Resource deleted, stopping watch") - prog.Send(treeQuitMsg{}) - return nil - } - return current.Error - } - - tree, err := c.getResourceTree(ctx, current, mapping, kClient, logger) + rendered, err := c.renderCurrentTree(ctx, logger, kClient, root, mapping, p) if err != nil { return err } - if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { - if err := c.enrichOperations(ctx, kClient, tree); err != nil { - return errors.Wrap(err, errGetOperations) - } - } - - logger.Debug("Got resource tree", "root", tree) - - rendered, err := renderTreeToString(p, tree) - if err != nil { - return err + // The resource was deleted, stop watching + if rendered == "" { + prog.Send(treeQuitMsg{}) + return nil } // Only send if changed @@ -226,6 +203,41 @@ func (c *Cmd) watchProducer(ctx context.Context, logger logging.Logger, kClient } } +// renderCurrentTree re-fetches the resource tree and renders it, returning an +// empty string once the resource is deleted. +func (c *Cmd) renderCurrentTree(ctx context.Context, logger logging.Logger, kClient client.Client, root *resource.Resource, mapping *meta.RESTMapping, p printer.Printer) (string, error) { + current := resource.GetResource(ctx, kClient, &v1.ObjectReference{ + Kind: root.Unstructured.GetKind(), + APIVersion: root.Unstructured.GetAPIVersion(), + Name: root.Unstructured.GetName(), + Namespace: root.Unstructured.GetNamespace(), + }) + + if current.Error != nil { + if apierrors.IsNotFound(current.Error) { + logger.Debug("Resource deleted, stopping watch") + return "", nil + } + + return "", current.Error + } + + tree, err := c.getResourceTree(ctx, current, mapping, kClient, logger) + if err != nil { + return "", err + } + + if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { + if err := c.enrichOperations(ctx, kClient, tree); err != nil { + return "", errors.Wrap(err, errGetOperations) + } + } + + logger.Debug("Got resource tree", "root", tree) + + return renderTreeToString(p, tree) +} + // handleProducerError handles errors from the watch producer. func (c *Cmd) handleProducerError(prog *tea.Program, err error) { if apierrors.IsNotFound(err) { diff --git a/pkg/resource/ops/ops.go b/pkg/resource/ops/ops.go index 0ede1a28..78f4e271 100644 --- a/pkg/resource/ops/ops.go +++ b/pkg/resource/ops/ops.go @@ -180,33 +180,59 @@ func enrich(r *resource.Resource, s *snapshot, mode Mode) { // children and, in ModeAll, the Operations that applied changes to it grouped // under the WatchOperation or CronOperation that created them, if any. func relatedOperations(r *resource.Resource, s *snapshot, mode Mode) []*resource.Resource { - var related []*resource.Resource + a := &attacher{ + branches: map[string]*resource.Resource{}, + attached: map[string]bool{}, + } - branches := map[string]*resource.Resource{} - branchFor := func(o client.Object, gvk schema.GroupVersionKind, relation string) *resource.Resource { - key := gvk.Kind + "/" + o.GetName() - if b, ok := branches[key]; ok { - return b - } + a.attachWatching(r, s) + + if mode == ModeAll { + a.attachApplied(r, s) + } - b := asResource(o, gvk, relation) - branches[key] = b - related = append(related, b) + for _, b := range a.related { + sortByCreation(b.Children) + } + return a.related +} + +// attacher accumulates the operations related to a resource. +type attacher struct { + // related are the operations to attach to the resource. + related []*resource.Resource + // branches dedupes the WatchOperations and CronOperations in related. + branches map[string]*resource.Resource + // attached tracks the Operations already attached to a branch. + attached map[string]bool +} + +// branchFor returns the existing branch for the given WatchOperation or +// CronOperation, creating it with the given relation if needed. +func (a *attacher) branchFor(o client.Object, gvk schema.GroupVersionKind, relation string) *resource.Resource { + key := gvk.Kind + "/" + o.GetName() + if b, ok := a.branches[key]; ok { return b } - attached := map[string]bool{} + b := asResource(o, gvk, relation) + a.branches[key] = b + a.related = append(a.related, b) - // WatchOperations watching this resource, with the Operations they - // created in response to changes to it as children. + return b +} + +// attachWatching attaches the WatchOperations watching the given resource, +// with the Operations they created in response to changes to it as children. +func (a *attacher) attachWatching(r *resource.Resource, s *snapshot) { for i := range s.watchOps { wo := &s.watchOps[i] if !watchMatches(wo.Spec.Watch, &r.Unstructured) { continue } - b := branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationWatching) + b := a.branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationWatching) for j := range s.ops { op := &s.ops[j] @@ -215,50 +241,53 @@ func relatedOperations(r *resource.Resource, s *snapshot, mode Mode) []*resource } b.Children = append(b.Children, asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationTriggered)) - attached[op.GetName()] = true + a.attached[op.GetName()] = true } } +} - if mode == ModeAll { - // Operations that applied changes to this resource, grouped under - // the WatchOperation or CronOperation that created them, if any. - for i := range s.ops { - op := &s.ops[i] - if attached[op.GetName()] || !applied(op, &r.Unstructured) { - continue - } +// attachApplied attaches the Operations that applied changes to the given +// resource, grouped under the WatchOperation or CronOperation that created +// them, if any. +func (a *attacher) attachApplied(r *resource.Resource, s *snapshot) { + for i := range s.ops { + op := &s.ops[i] + if a.attached[op.GetName()] || !applied(op, &r.Unstructured) { + continue + } - attached[op.GetName()] = true - child := asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationApplied) - - if owner := metav1.GetControllerOf(op); owner != nil && owner.APIVersion == opsv1alpha1.SchemeGroupVersion.String() { - switch owner.Kind { - case opsv1alpha1.WatchOperationKind: - if wo := s.watchOp(owner.Name); wo != nil { - b := branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationApplied) - appendChild(b, child) - - continue - } - case opsv1alpha1.CronOperationKind: - if co, ok := s.cronOps[owner.Name]; ok { - b := branchFor(&co, opsv1alpha1.CronOperationGroupVersionKind, RelationApplied) - appendChild(b, child) - - continue - } - } - } + a.attached[op.GetName()] = true + child := asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationApplied) - related = append(related, child) + if b := a.creatorBranch(op, s); b != nil { + appendChild(b, child) + continue } + + a.related = append(a.related, child) } +} - for _, b := range related { - sortByCreation(b.Children) +// creatorBranch returns the branch for the WatchOperation or CronOperation +// that created the given Operation, or nil if it was created by neither. +func (a *attacher) creatorBranch(op *opsv1alpha1.Operation, s *snapshot) *resource.Resource { + owner := metav1.GetControllerOf(op) + if owner == nil || owner.APIVersion != opsv1alpha1.SchemeGroupVersion.String() { + return nil } - return related + switch owner.Kind { + case opsv1alpha1.WatchOperationKind: + if wo := s.watchOp(owner.Name); wo != nil { + return a.branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationApplied) + } + case opsv1alpha1.CronOperationKind: + if co, ok := s.cronOps[owner.Name]; ok { + return a.branchFor(&co, opsv1alpha1.CronOperationGroupVersionKind, RelationApplied) + } + } + + return nil } // appendChild appends the child to the branch, dropping the child's relation diff --git a/pkg/resource/ops/ops_test.go b/pkg/resource/ops/ops_test.go index ef7d6095..c0577eb4 100644 --- a/pkg/resource/ops/ops_test.go +++ b/pkg/resource/ops/ops_test.go @@ -24,7 +24,6 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/utils/ptr" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" @@ -70,7 +69,7 @@ func ownedBy(kind, name string) operationOpt { APIVersion: opsv1alpha1.SchemeGroupVersion.String(), Kind: kind, Name: name, - Controller: ptr.To(true), + Controller: new(true), }}) if kind == opsv1alpha1.WatchOperationKind { op.SetLabels(map[string]string{opsv1alpha1.LabelWatchOperationName: name}) @@ -82,7 +81,7 @@ func appliedResource(apiVersion, kind, namespace, name string) operationOpt { return func(op *opsv1alpha1.Operation) { ref := opsv1alpha1.AppliedResourceRef{APIVersion: apiVersion, Kind: kind, Name: name} if namespace != "" { - ref.Namespace = ptr.To(namespace) + ref.Namespace = new(namespace) } op.Status.AppliedResourceRefs = append(op.Status.AppliedResourceRefs, ref) @@ -112,7 +111,9 @@ func kindNames(r *resource.Resource, depth int) []string { line += " relation=" + r.Relation } - out := []string{line} + out := make([]string, 0, len(r.Children)+1) + out = append(out, line) + for _, c := range r.Children { out = append(out, kindNames(c, depth+1)...) } From 4de5e39e3f6ba2f7c8a80b022ca27142adbbc29e Mon Sep 17 00:00:00 2001 From: Christopher Haar Date: Tue, 3 Nov 2026 12:32:12 +0100 Subject: [PATCH 3/5] lint(vale): make vale wording right Signed-off-by: Christopher Haar --- cmd/crossplane/trace/help/trace.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cmd/crossplane/trace/help/trace.md b/cmd/crossplane/trace/help/trace.md index c86df9dc..ddf772f8 100644 --- a/cmd/crossplane/trace/help/trace.md +++ b/cmd/crossplane/trace/help/trace.md @@ -54,11 +54,11 @@ The `--show-operations` flag controls the display of operations - `none` (default): hide operations. - `triggered`: show the WatchOperations watching each resource, with the Operations they created in response to changes to it as children. -- `all`: additionally show the Operations that applied changes to each - resource, grouped under the CronOperation or WatchOperation that created - them, if any. +- `all`: also show the Operations that applied changes to each resource, + grouped under the CronOperation or WatchOperation that created them, if + any. -Operations are not part of the resource tree, they only relate to it, so the +Operations aren't part of the resource tree, they only relate to it, so the default output marks them with an arrow (`├◀`) pointing at the resource they relate to. The structured output formats include the relation (`watching`, `triggered` or `applied`) as a `relation` field instead. @@ -109,7 +109,7 @@ Show connection secret names alongside the resources: crossplane resource trace mykind my-res -n my-ns --show-connection-secrets ``` -Show all operations related to the resources, e.g. the WatchOperations +Show all operations related to the resources, for example the WatchOperations watching them and the Operations that changed them: ```shell From bb060a708ede266a032793b583040882707a91ae Mon Sep 17 00:00:00 2001 From: Christopher Haar Date: Sat, 21 Nov 2026 12:12:20 +0100 Subject: [PATCH 4/5] Address trace operations review feedback Match operations to their creator by controller owner UID, not only by name and label: an Operation surviving a WatchOperation or CronOperation that was deleted and recreated under the same name belongs to the deleted creator, so it's neither shown as triggered nor grouped under the new one. Similarly, triggeredBy now rejects Operations created before the watched resource: they were triggered by a deleted predecessor of the same name. applied is unchanged, since an Operation that created the resource legitimately predates it. The DOT printer now fills the Ready column from the condition representing an operation's lifecycle, through a readyConditionType helper shared with the default printer. List mode skips operations enrichment when there are no trees to attach to, so structured output of an empty list stays an empty list. Watch mode renders the already-fetched tree when enrichment fails and logs the error at debug level instead of ending the watch. asResource moves to pkg/resource as the exported FromObject helper, and the test fixtures build resources through the shared testutils builder. Signed-off-by: Christopher Haar --- .../trace/internal/printer/default.go | 15 +-- cmd/crossplane/trace/internal/printer/dot.go | 2 +- .../trace/internal/printer/dot_test.go | 44 ++++++++ .../trace/internal/printer/printer.go | 19 ++++ cmd/crossplane/trace/trace.go | 3 +- cmd/crossplane/trace/watch.go | 5 +- pkg/resource/ops/ops.go | 50 +++++---- pkg/resource/ops/ops_test.go | 105 +++++++++++++++--- pkg/resource/resource.go | 23 ++++ 9 files changed, 212 insertions(+), 54 deletions(-) diff --git a/cmd/crossplane/trace/internal/printer/default.go b/cmd/crossplane/trace/internal/printer/default.go index c749e5d1..92dd8831 100644 --- a/cmd/crossplane/trace/internal/printer/default.go +++ b/cmd/crossplane/trace/internal/printer/default.go @@ -32,7 +32,6 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/xcrd" xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2" - opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" pkgv1 "github.com/crossplane/crossplane/apis/v2/pkg/v1" "github.com/crossplane/cli/v2/pkg/resource" @@ -286,19 +285,7 @@ func (p *DefaultPrinter) printResourceTree(tw *tabwriter.Writer, root *resource. // getResourceStatus returns a string that represents an entire row of status // information for the resource. func getResourceStatus(r *resource.Resource, name string, wide bool) fmt.Stringer { - // Operations don't have a Ready condition, show the condition - // representing their lifecycle in the READY column instead. - readyType := xpv2.TypeReady - switch r.Unstructured.GroupVersionKind().GroupKind() { - case opsv1alpha1.OperationGroupVersionKind.GroupKind(): - readyType = opsv1alpha1.TypeSucceeded - case opsv1alpha1.WatchOperationGroupVersionKind.GroupKind(): - readyType = opsv1alpha1.TypeWatching - case opsv1alpha1.CronOperationGroupVersionKind.GroupKind(): - readyType = opsv1alpha1.TypeScheduling - } - - readyCond := r.GetCondition(readyType) + readyCond := r.GetCondition(readyConditionType(r)) syncedCond := r.GetCondition(xpv2.TypeSynced) var status, m string diff --git a/cmd/crossplane/trace/internal/printer/dot.go b/cmd/crossplane/trace/internal/printer/dot.go index 4deb8010..07be164d 100644 --- a/cmd/crossplane/trace/internal/printer/dot.go +++ b/cmd/crossplane/trace/internal/printer/dot.go @@ -200,7 +200,7 @@ func printGraphQueue(g *dot.Graph, queue []*queueItem) { namespace: item.resource.Unstructured.GetNamespace(), apiVersion: item.resource.Unstructured.GetObjectKind().GroupVersionKind().GroupVersion().String(), name: fmt.Sprintf("%s/%s", item.resource.Unstructured.GetKind(), item.resource.Unstructured.GetName()), - ready: string(item.resource.GetCondition(xpv2.TypeReady).Status), + ready: string(item.resource.GetCondition(readyConditionType(item.resource)).Status), synced: string(item.resource.GetCondition(xpv2.TypeSynced).Status), relation: item.resource.Relation, } diff --git a/cmd/crossplane/trace/internal/printer/dot_test.go b/cmd/crossplane/trace/internal/printer/dot_test.go index c28ec6c3..dc20f7ec 100644 --- a/cmd/crossplane/trace/internal/printer/dot_test.go +++ b/cmd/crossplane/trace/internal/printer/dot_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "github.com/crossplane/crossplane-runtime/v2/pkg/test" @@ -79,6 +80,49 @@ func TestPrintDotGraphPrint(t *testing.T) { n5--n6; n5--n7; +} +`, + err: nil, + }, + }, + "OperationLifecycleCondition": { + reason: "Should fill the Ready column from the condition representing an operation's lifecycle, like the default printer, not the Ready condition operations never have.", + args: args{ + resource: &resource.Resource{ + Unstructured: unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "ops.crossplane.io/v1alpha1", + "kind": "WatchOperation", + "metadata": map[string]any{"name": "watch-things"}, + "status": map[string]any{ + "conditions": []any{ + map[string]any{"type": "Watching", "status": "True"}, + map[string]any{"type": "Synced", "status": "True"}, + }, + }, + }}, + Relation: "watching", + Children: []*resource.Resource{{ + Unstructured: unstructured.Unstructured{Object: map[string]any{ + "apiVersion": "ops.crossplane.io/v1alpha1", + "kind": "Operation", + "metadata": map[string]any{"name": "watch-things-123"}, + "status": map[string]any{ + "conditions": []any{ + map[string]any{"type": "Succeeded", "status": "True"}, + }, + }, + }}, + Relation: "triggered", + }}, + }, + }, + want: want{ + dotString: `graph { + + n1[label="Name: WatchOperation/watch-things\nApiVersion: ops.crossplane.io/v1alpha1\nReady: True\nSynced: True\nRelation: watching\n",penwidth="2"]; + n2[label="Name: Operation/watch-things-123\nApiVersion: ops.crossplane.io/v1alpha1\nReady: True\nSynced: \nRelation: triggered\n",penwidth="2"]; + n1--n2; + } `, err: nil, diff --git a/cmd/crossplane/trace/internal/printer/printer.go b/cmd/crossplane/trace/internal/printer/printer.go index 9a954557..2fb811c9 100644 --- a/cmd/crossplane/trace/internal/printer/printer.go +++ b/cmd/crossplane/trace/internal/printer/printer.go @@ -23,6 +23,9 @@ import ( "github.com/pkg/errors" + xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2" + opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" + "github.com/crossplane/cli/v2/pkg/resource" ) @@ -71,3 +74,19 @@ func New(typeStr string) (Printer, error) { return p, nil } + +// readyConditionType returns the condition type shown in the READY column +// for the given resource. Operations don't have a Ready condition; the +// condition representing their lifecycle is shown instead. +func readyConditionType(r *resource.Resource) xpv2.ConditionType { + switch r.Unstructured.GroupVersionKind().GroupKind() { + case opsv1alpha1.OperationGroupVersionKind.GroupKind(): + return opsv1alpha1.TypeSucceeded + case opsv1alpha1.WatchOperationGroupVersionKind.GroupKind(): + return opsv1alpha1.TypeWatching + case opsv1alpha1.CronOperationGroupVersionKind.GroupKind(): + return opsv1alpha1.TypeScheduling + } + + return xpv2.TypeReady +} diff --git a/cmd/crossplane/trace/trace.go b/cmd/crossplane/trace/trace.go index fc8d1e1c..1674df06 100644 --- a/cmd/crossplane/trace/trace.go +++ b/cmd/crossplane/trace/trace.go @@ -298,7 +298,8 @@ func (c *Cmd) getResourceTrees(ctx context.Context, resourceList *resource.Resou // Attach related operations, if requested. Operations target Crossplane // resources, not packages, so there's nothing to attach on package trees. - if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { + // An empty list has nothing to attach to either. + if len(resourceList.Items) > 0 && !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { if err := c.enrichOperations(ctx, client, resourceList.Items...); err != nil { return errors.Wrap(err, errGetOperations) } diff --git a/cmd/crossplane/trace/watch.go b/cmd/crossplane/trace/watch.go index 92447c45..1482de95 100644 --- a/cmd/crossplane/trace/watch.go +++ b/cmd/crossplane/trace/watch.go @@ -229,7 +229,10 @@ func (c *Cmd) renderCurrentTree(ctx context.Context, logger logging.Logger, kCli if !xpkg.IsPackageType(mapping.GroupVersionKind.GroupKind()) { if err := c.enrichOperations(ctx, kClient, tree); err != nil { - return "", errors.Wrap(err, errGetOperations) + // The tree was already fetched and can still render without + // operations; keep the watch alive and try again on the next + // refresh instead of ending it. + logger.Debug(errGetOperations, "error", err) } } diff --git a/pkg/resource/ops/ops.go b/pkg/resource/ops/ops.go index 78f4e271..6b350fcb 100644 --- a/pkg/resource/ops/ops.go +++ b/pkg/resource/ops/ops.go @@ -216,7 +216,7 @@ func (a *attacher) branchFor(o client.Object, gvk schema.GroupVersionKind, relat return b } - b := asResource(o, gvk, relation) + b := resource.FromObject(o, gvk, relation) a.branches[key] = b a.related = append(a.related, b) @@ -236,11 +236,11 @@ func (a *attacher) attachWatching(r *resource.Resource, s *snapshot) { for j := range s.ops { op := &s.ops[j] - if op.GetLabels()[opsv1alpha1.LabelWatchOperationName] != wo.GetName() || !triggeredBy(op, &r.Unstructured) { + if !controlledBy(op, opsv1alpha1.WatchOperationKind, wo) || !triggeredBy(op, &r.Unstructured) { continue } - b.Children = append(b.Children, asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationTriggered)) + b.Children = append(b.Children, resource.FromObject(op, opsv1alpha1.OperationGroupVersionKind, RelationTriggered)) a.attached[op.GetName()] = true } } @@ -257,7 +257,7 @@ func (a *attacher) attachApplied(r *resource.Resource, s *snapshot) { } a.attached[op.GetName()] = true - child := asResource(op, opsv1alpha1.OperationGroupVersionKind, RelationApplied) + child := resource.FromObject(op, opsv1alpha1.OperationGroupVersionKind, RelationApplied) if b := a.creatorBranch(op, s); b != nil { appendChild(b, child) @@ -276,13 +276,16 @@ func (a *attacher) creatorBranch(op *opsv1alpha1.Operation, s *snapshot) *resour return nil } + // The UID must match too: an Operation whose creator was deleted and + // recreated under the same name belongs to the deleted creator, not the + // current one. switch owner.Kind { case opsv1alpha1.WatchOperationKind: - if wo := s.watchOp(owner.Name); wo != nil { + if wo := s.watchOp(owner.Name); wo != nil && wo.GetUID() == owner.UID { return a.branchFor(wo, opsv1alpha1.WatchOperationGroupVersionKind, RelationApplied) } case opsv1alpha1.CronOperationKind: - if co, ok := s.cronOps[owner.Name]; ok { + if co, ok := s.cronOps[owner.Name]; ok && co.GetUID() == owner.UID { return a.branchFor(&co, opsv1alpha1.CronOperationGroupVersionKind, RelationApplied) } } @@ -321,9 +324,28 @@ func watchMatches(w opsv1alpha1.WatchSpec, u *unstructured.Unstructured) bool { return true } +// controlledBy returns true if the object's controller owner reference is +// the given ops.crossplane.io owner. The UID must match too: an object whose +// owner was deleted and recreated under the same name belongs to the deleted +// owner, not the current one. +func controlledBy(o client.Object, kind string, owner client.Object) bool { + ref := metav1.GetControllerOf(o) + + return ref != nil && ref.APIVersion == opsv1alpha1.SchemeGroupVersion.String() && + ref.Kind == kind && ref.Name == owner.GetName() && ref.UID == owner.GetUID() +} + // triggeredBy returns true if the Operation is annotated as having been // created in response to a change to the given resource. func triggeredBy(op *opsv1alpha1.Operation, u *unstructured.Unstructured) bool { + // A watch-triggered Operation is created after the resource it watches, + // so an Operation older than the resource was triggered by a deleted + // predecessor of the same name. + opCreated, resCreated := op.GetCreationTimestamp(), u.GetCreationTimestamp() + if opCreated.Before(&resCreated) { + return false + } + a := op.GetAnnotations() return a[opsv1alpha1.AnnotationWatchedResourceAPIVersion] == u.GetAPIVersion() && @@ -345,22 +367,6 @@ func applied(op *opsv1alpha1.Operation, u *unstructured.Unstructured) bool { return false } -func asResource(o client.Object, gvk schema.GroupVersionKind, relation string) *resource.Resource { - obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(o) - if err != nil { - u := unstructured.Unstructured{} - u.SetGroupVersionKind(gvk) - u.SetName(o.GetName()) - - return &resource.Resource{Unstructured: u, Error: err, Relation: relation} - } - - u := unstructured.Unstructured{Object: obj} - u.SetGroupVersionKind(gvk) - - return &resource.Resource{Unstructured: u, Relation: relation} -} - func sortByCreation(rs []*resource.Resource) { sort.SliceStable(rs, func(i, j int) bool { ti, tj := rs[i].Unstructured.GetCreationTimestamp(), rs[j].Unstructured.GetCreationTimestamp() diff --git a/pkg/resource/ops/ops_test.go b/pkg/resource/ops/ops_test.go index c0577eb4..adbf2a7a 100644 --- a/pkg/resource/ops/ops_test.go +++ b/pkg/resource/ops/ops_test.go @@ -19,28 +19,25 @@ package ops import ( "context" "testing" + "time" "github.com/google/go-cmp/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" opsv1alpha1 "github.com/crossplane/crossplane/apis/v2/ops/v1alpha1" + "github.com/crossplane/cli/v2/internal/diff/testutils" "github.com/crossplane/cli/v2/pkg/resource" ) func buildResource(apiVersion, kind, namespace, name string, labels map[string]string) *resource.Resource { - u := unstructured.Unstructured{} - u.SetAPIVersion(apiVersion) - u.SetKind(kind) - u.SetNamespace(namespace) - u.SetName(name) - u.SetLabels(labels) - - return &resource.Resource{Unstructured: u} + u := testutils.NewResource(apiVersion, kind, name).InNamespace(namespace).WithLabels(labels).Build() + + return &resource.Resource{Unstructured: *u} } func buildWatchOp(name string, watch opsv1alpha1.WatchSpec) *opsv1alpha1.WatchOperation { @@ -63,12 +60,13 @@ func triggeredByResource(apiVersion, kind, namespace, name string) operationOpt } } -func ownedBy(kind, name string) operationOpt { +func ownedBy(kind, name, uid string) operationOpt { return func(op *opsv1alpha1.Operation) { op.SetOwnerReferences([]metav1.OwnerReference{{ APIVersion: opsv1alpha1.SchemeGroupVersion.String(), Kind: kind, Name: name, + UID: types.UID(uid), Controller: new(true), }}) if kind == opsv1alpha1.WatchOperationKind { @@ -97,6 +95,21 @@ func buildOperation(name string, opts ...operationOpt) *opsv1alpha1.Operation { return op } +// withUID returns the object with the given UID set, to pin that owner +// references must match their owner by UID, not only by name. +func withUID(o client.Object, uid string) client.Object { + o.SetUID(types.UID(uid)) + + return o +} + +// createdAt sets the Operation's creation timestamp. +func createdAt(ts metav1.Time) operationOpt { + return func(op *opsv1alpha1.Operation) { + op.SetCreationTimestamp(ts) + } +} + // kindNames flattens a tree of Resource into "Kind/name relation=" // strings, children indented by depth, to easily assert on the tree shape and // the Relation field set on the nodes attached by the Enricher. @@ -159,10 +172,10 @@ func TestEnrich(t *testing.T) { buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), buildWatchOp("watch-others", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Other"}), buildOperation("watch-things-123", - ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", ""), triggeredByResource("example.org/v1", "Thing", "default", "my-thing")), buildOperation("watch-things-456", - ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", ""), triggeredByResource("example.org/v1", "Thing", "default", "another-thing")), }, root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), @@ -196,7 +209,7 @@ func TestEnrich(t *testing.T) { objects: []client.Object{ &opsv1alpha1.CronOperation{ObjectMeta: metav1.ObjectMeta{Name: "nightly"}}, buildOperation("nightly-123", - ownedBy(opsv1alpha1.CronOperationKind, "nightly"), + ownedBy(opsv1alpha1.CronOperationKind, "nightly", ""), appliedResource("example.org/v1", "Thing", "default", "my-thing")), buildOperation("standalone", appliedResource("example.org/v1", "Thing", "default", "my-thing")), @@ -219,7 +232,7 @@ func TestEnrich(t *testing.T) { objects: []client.Object{ buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), buildOperation("watch-things-123", - ownedBy(opsv1alpha1.WatchOperationKind, "watch-things"), + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", ""), triggeredByResource("example.org/v1", "Thing", "default", "my-thing"), appliedResource("example.org/v1", "Thing", "default", "my-thing")), }, @@ -238,7 +251,7 @@ func TestEnrich(t *testing.T) { objects: []client.Object{ buildWatchOp("watch-walls", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing", MatchLabels: map[string]string{"type": "wall"}}), buildOperation("watch-walls-123", - ownedBy(opsv1alpha1.WatchOperationKind, "watch-walls"), + ownedBy(opsv1alpha1.WatchOperationKind, "watch-walls", ""), triggeredByResource("example.org/v1", "Thing", "default", "wall"), appliedResource("example.org/v1", "Thing", "default", "radiator")), }, @@ -262,6 +275,68 @@ func TestEnrich(t *testing.T) { " Operation/watch-walls-123", }, }, + "TriggeredRequiresCurrentWatchOperationOwner": { + reason: "Should not attach an Operation whose controller owner UID is not the current WatchOperation's, e.g. one surviving a deleted and recreated WatchOperation of the same name.", + args: args{ + mode: ModeTriggered, + objects: []client.Object{ + withUID(buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), "uid-new"), + buildOperation("watch-things-123", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", "uid-old"), + triggeredByResource("example.org/v1", "Thing", "default", "my-thing")), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + " WatchOperation/watch-things relation=watching", + }, + }, + "TriggeredIgnoresOperationsOlderThanTheResource": { + reason: "Should not attach an Operation created before the resource: it was triggered by a deleted predecessor of the same name.", + args: args{ + mode: ModeTriggered, + objects: []client.Object{ + buildWatchOp("watch-things", opsv1alpha1.WatchSpec{APIVersion: "example.org/v1", Kind: "Thing"}), + buildOperation("watch-things-old", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", ""), + triggeredByResource("example.org/v1", "Thing", "default", "my-thing"), + createdAt(metav1.NewTime(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)))), + buildOperation("watch-things-new", + ownedBy(opsv1alpha1.WatchOperationKind, "watch-things", ""), + triggeredByResource("example.org/v1", "Thing", "default", "my-thing"), + createdAt(metav1.NewTime(time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC)))), + }, + root: func() *resource.Resource { + r := buildResource("example.org/v1", "Thing", "default", "my-thing", nil) + r.Unstructured.SetCreationTimestamp(metav1.NewTime(time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC))) + + return r + }(), + }, + want: []string{ + "Thing/my-thing", + " WatchOperation/watch-things relation=watching", + " Operation/watch-things-new relation=triggered", + }, + }, + "AllDoesNotGroupUnderRecreatedCreator": { + reason: "Should not group an applied Operation under a creator of the same name but another UID; the Operation belongs to the deleted creator.", + args: args{ + mode: ModeAll, + objects: []client.Object{ + withUID(&opsv1alpha1.CronOperation{ObjectMeta: metav1.ObjectMeta{Name: "nightly"}}, "uid-new"), + buildOperation("nightly-123", + ownedBy(opsv1alpha1.CronOperationKind, "nightly", "uid-old"), + appliedResource("example.org/v1", "Thing", "default", "my-thing")), + }, + root: buildResource("example.org/v1", "Thing", "default", "my-thing", nil), + }, + want: []string{ + "Thing/my-thing", + " Operation/nightly-123 relation=applied", + }, + }, } for name, tc := range cases { diff --git a/pkg/resource/resource.go b/pkg/resource/resource.go index 0d6abb29..399757b8 100644 --- a/pkg/resource/resource.go +++ b/pkg/resource/resource.go @@ -20,6 +20,9 @@ package resource import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" "github.com/crossplane/crossplane-runtime/v2/pkg/fieldpath" @@ -45,6 +48,26 @@ type ResourceList struct { Error error `json:"error,omitempty"` } +// FromObject returns a Resource wrapping the given typed object, converted +// to unstructured form under the given GVK, with the given relation. A failed +// conversion is carried on the Resource's Error, so it still renders as a +// node in the tree. +func FromObject(o client.Object, gvk schema.GroupVersionKind, relation string) *Resource { + obj, err := runtime.DefaultUnstructuredConverter.ToUnstructured(o) + if err != nil { + u := unstructured.Unstructured{} + u.SetGroupVersionKind(gvk) + u.SetName(o.GetName()) + + return &Resource{Unstructured: u, Error: err, Relation: relation} + } + + u := unstructured.Unstructured{Object: obj} + u.SetGroupVersionKind(gvk) + + return &Resource{Unstructured: u, Relation: relation} +} + // GetCondition of this resource. func (r *Resource) GetCondition(ct xpv2.ConditionType) xpv2.Condition { conditioned := xpv2.ConditionedStatus{} From a0b82bb7ab088988988ddd48ebb1d8f1c6c81999 Mon Sep 17 00:00:00 2001 From: Christopher Haar Date: Sat, 21 Nov 2026 12:32:10 +0100 Subject: [PATCH 5/5] Build test operations via setters to satisfy embedlit The modernize embedlit check wants the embedded ObjectMeta type elided from the struct literals, but that syntax needs language version 1.27 and the module is at 1.26. Set the names via setters instead, so there is no embedded-field literal to flag. Signed-off-by: Christopher Haar --- pkg/resource/ops/ops_test.go | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/pkg/resource/ops/ops_test.go b/pkg/resource/ops/ops_test.go index adbf2a7a..96f8ec15 100644 --- a/pkg/resource/ops/ops_test.go +++ b/pkg/resource/ops/ops_test.go @@ -41,10 +41,10 @@ func buildResource(apiVersion, kind, namespace, name string, labels map[string]s } func buildWatchOp(name string, watch opsv1alpha1.WatchSpec) *opsv1alpha1.WatchOperation { - return &opsv1alpha1.WatchOperation{ - ObjectMeta: metav1.ObjectMeta{Name: name}, - Spec: opsv1alpha1.WatchOperationSpec{Watch: watch}, - } + wo := &opsv1alpha1.WatchOperation{Spec: opsv1alpha1.WatchOperationSpec{Watch: watch}} + wo.SetName(name) + + return wo } type operationOpt func(*opsv1alpha1.Operation) @@ -87,7 +87,9 @@ func appliedResource(apiVersion, kind, namespace, name string) operationOpt { } func buildOperation(name string, opts ...operationOpt) *opsv1alpha1.Operation { - op := &opsv1alpha1.Operation{ObjectMeta: metav1.ObjectMeta{Name: name}} + op := &opsv1alpha1.Operation{} + op.SetName(name) + for _, o := range opts { o(op) } @@ -95,6 +97,14 @@ func buildOperation(name string, opts ...operationOpt) *opsv1alpha1.Operation { return op } +// buildCronOp returns a CronOperation with the given name. +func buildCronOp(name string) *opsv1alpha1.CronOperation { + co := &opsv1alpha1.CronOperation{} + co.SetName(name) + + return co +} + // withUID returns the object with the given UID set, to pin that owner // references must match their owner by UID, not only by name. func withUID(o client.Object, uid string) client.Object { @@ -207,7 +217,7 @@ func TestEnrich(t *testing.T) { args: args{ mode: ModeAll, objects: []client.Object{ - &opsv1alpha1.CronOperation{ObjectMeta: metav1.ObjectMeta{Name: "nightly"}}, + buildCronOp("nightly"), buildOperation("nightly-123", ownedBy(opsv1alpha1.CronOperationKind, "nightly", ""), appliedResource("example.org/v1", "Thing", "default", "my-thing")), @@ -325,7 +335,7 @@ func TestEnrich(t *testing.T) { args: args{ mode: ModeAll, objects: []client.Object{ - withUID(&opsv1alpha1.CronOperation{ObjectMeta: metav1.ObjectMeta{Name: "nightly"}}, "uid-new"), + withUID(buildCronOp("nightly"), "uid-new"), buildOperation("nightly-123", ownedBy(opsv1alpha1.CronOperationKind, "nightly", "uid-old"), appliedResource("example.org/v1", "Thing", "default", "my-thing")),