Skip to content
Merged
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
27 changes: 27 additions & 0 deletions cmd/crossplane/trace/help/trace.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`: also show the Operations that applied changes to each resource,
grouped under the CronOperation or WatchOperation that created them, if
any.

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.

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
Expand Down Expand Up @@ -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, for example 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
Expand Down
22 changes: 18 additions & 4 deletions cmd/crossplane/trace/internal/printer/default.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,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,
Expand All @@ -224,17 +227,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 += "│ "
}
Expand Down Expand Up @@ -262,7 +275,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
Expand All @@ -271,7 +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 {
readyCond := r.GetCondition(xpv2.TypeReady)
readyCond := r.GetCondition(readyConditionType(r))
syncedCond := r.GetCondition(xpv2.TypeSynced)

var status, m string
Expand Down
9 changes: 8 additions & 1 deletion cmd/crossplane/trace/internal/printer/dot.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type dotLabel struct {
name string
ready string
synced string
relation string
error string
}

Expand All @@ -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,
Expand Down Expand Up @@ -194,8 +200,9 @@ 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,
Comment thread
haarchri marked this conversation as resolved.
Resolved
}
}

Expand Down
44 changes: 44 additions & 0 deletions cmd/crossplane/trace/internal/printer/dot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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,
Expand Down
19 changes: 19 additions & 0 deletions cmd/crossplane/trace/internal/printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
}
73 changes: 54 additions & 19 deletions cmd/crossplane/trace/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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"
Expand All @@ -68,15 +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"`
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"`
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"`
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:""`
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -210,18 +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
if err := c.getResourceTrees(ctx, resourceList, mapping, client, logger); err != nil {
return err
}

// Watch mode for a single resource
Expand Down Expand Up @@ -284,6 +279,46 @@ 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.
// 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)
}
}

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 {
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
Expand Down
Loading
Loading