Skip to content

Commit

Permalink
Start using DescriberKV struct to print all describe views and also p…
Browse files Browse the repository at this point in the history
…rint events

associated with the resource.
  • Loading branch information
gauravkghildiyal committed May 5, 2024
1 parent ae743a3 commit 42c411c
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 175 deletions.
2 changes: 1 addition & 1 deletion gwctl/cmd/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func runDescribe(cmd *cobra.Command, args []string, params *utils.CmdParams) {
httpRoutesPrinter := &printer.HTTPRoutesPrinter{Writer: params.Out, Clock: clock.RealClock{}}
gwPrinter := &printer.GatewaysPrinter{Writer: params.Out, Clock: clock.RealClock{}}
gwcPrinter := &printer.GatewayClassesPrinter{Writer: params.Out, Clock: clock.RealClock{}}
backendsPrinter := &printer.BackendsPrinter{Writer: params.Out}
backendsPrinter := &printer.BackendsPrinter{Writer: params.Out, Clock: clock.RealClock{}}
namespacesPrinter := &printer.NamespacesPrinter{Writer: params.Out, Clock: clock.RealClock{}}

switch kind {
Expand Down
74 changes: 41 additions & 33 deletions gwctl/pkg/printer/backends.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package printer
import (
"fmt"
"io"
"os"
"sort"
"strings"

Expand All @@ -28,10 +27,7 @@ import (

"sigs.k8s.io/controller-runtime/pkg/client"

"sigs.k8s.io/gateway-api/gwctl/pkg/common"
"sigs.k8s.io/gateway-api/gwctl/pkg/resourcediscovery"

"sigs.k8s.io/yaml"
)

type BackendsPrinter struct {
Expand Down Expand Up @@ -115,48 +111,60 @@ func (bp *BackendsPrinter) Print(resourceModel *resourcediscovery.ResourceModel)
table.Write(bp, 0)
}

type backendDescribeView struct {
Group string `json:",omitempty"`
Kind string `json:",omitempty"`
Name string `json:",omitempty"`
Namespace string `json:",omitempty"`
DirectlyAttachedPolicies []common.ObjRef `json:",omitempty"`
EffectivePolicies any `json:",omitempty"`
}

func (bp *BackendsPrinter) PrintDescribeView(resourceModel *resourcediscovery.ResourceModel) {
index := 0
for _, backendNode := range resourceModel.Backends {
index++

views := []backendDescribeView{
{
Group: backendNode.Backend.GroupVersionKind().Group,
Kind: backendNode.Backend.GroupVersionKind().Kind,
Name: backendNode.Backend.GetName(),
Namespace: backendNode.Backend.GetNamespace(),
},
backend := backendNode.Backend.DeepCopy()
backend.SetLabels(nil)
backend.SetAnnotations(nil)

pairs := []*DescriberKV{
{Key: "Name", Value: backendNode.Backend.GetName()},
{Key: "Namespace", Value: backendNode.Backend.GetNamespace()},
{Key: "Labels", Value: backendNode.Backend.GetLabels()},
{Key: "Annotations", Value: backendNode.Backend.GetAnnotations()},
{Key: "Backend", Value: backend},
}
if policyRefs := resourcediscovery.ConvertPoliciesMapToPolicyRefs(backendNode.Policies); len(policyRefs) != 0 {
views = append(views, backendDescribeView{
DirectlyAttachedPolicies: policyRefs,
})

// ReferencedByRoutes
routes := &Table{
ColumnNames: []string{"Kind", "Name"},
UseSeparator: true,
}
for _, httpRouteNode := range backendNode.HTTPRoutes {
row := []string{
httpRouteNode.HTTPRoute.Kind, // Kind
fmt.Sprintf("%v/%v", httpRouteNode.HTTPRoute.Namespace, httpRouteNode.HTTPRoute.Name), // Name
}
routes.Rows = append(routes.Rows, row)
}
pairs = append(pairs, &DescriberKV{Key: "ReferencedByRoutes", Value: routes})

// DirectlyAttachedPolicies
policyRefs := resourcediscovery.ConvertPoliciesMapToPolicyRefs(backendNode.Policies)
pairs = append(pairs, &DescriberKV{Key: "DirectlyAttachedPolicies", Value: convertPolicyRefsToTable(policyRefs)})

// EffectivePolicies
if len(backendNode.EffectivePolicies) != 0 {
views = append(views, backendDescribeView{
EffectivePolicies: backendNode.EffectivePolicies,
})
pairs = append(pairs, &DescriberKV{Key: "EffectivePolicies", Value: backendNode.EffectivePolicies})
}

for _, view := range views {
b, err := yaml.Marshal(view)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to marshal to yaml: %v\n", err)
os.Exit(1)
// ReferenceGrants
if len(backendNode.ReferenceGrants) != 0 {
var names []string
for _, refGrantNode := range backendNode.ReferenceGrants {
names = append(names, refGrantNode.ReferenceGrant.Name)
}
fmt.Fprint(bp, string(b))
pairs = append(pairs, &DescriberKV{Key: "ReferenceGrants", Value: names})
}

// Events
pairs = append(pairs, &DescriberKV{Key: "Events", Value: convertEventsSliceToTable(backendNode.Events, bp.Clock)})

Describe(bp, pairs)

if index+1 <= len(resourceModel.Backends) {
fmt.Fprintf(bp, "\n\n")
}
Expand Down
19 changes: 19 additions & 0 deletions gwctl/pkg/printer/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,25 @@ func convertEventsSliceToTable(events []corev1.Event, clock clock.Clock) *Table
return table
}

func convertPolicyRefsToTable(policyRefs []common.ObjRef) *Table {
table := &Table{
ColumnNames: []string{"Type", "Name"},
UseSeparator: true,
}
for _, policyRef := range policyRefs {
name := policyRef.Name
if policyRef.Namespace != "" {
name = fmt.Sprintf("%v/%v", policyRef.Namespace, name)
}
row := []string{
fmt.Sprintf("%v.%v", policyRef.Kind, policyRef.Group), // Type
name, // Name
}
table.Rows = append(table.Rows, row)
}
return table
}

type NodeResource interface {
ClientObject() client.Object
}
Expand Down
94 changes: 19 additions & 75 deletions gwctl/pkg/printer/gatewayclasses.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,12 @@ package printer
import (
"fmt"
"io"
"os"
"strings"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/duration"
"k8s.io/utils/clock"
"k8s.io/utils/ptr"

gatewayv1 "sigs.k8s.io/gateway-api/apis/v1"
"sigs.k8s.io/gateway-api/gwctl/pkg/common"
"sigs.k8s.io/gateway-api/gwctl/pkg/resourcediscovery"

"sigs.k8s.io/yaml"
)

var _ Printer = (*GatewayClassesPrinter)(nil)
Expand All @@ -41,23 +34,6 @@ type GatewayClassesPrinter struct {
Clock clock.Clock
}

type gatewayClassDescribeView struct {
APIVersion string `json:",omitempty"`
Kind string `json:",omitempty"`
Metadata *metav1.ObjectMeta `json:",omitempty"`
Labels *map[string]string `json:",omitempty"`
Annotations *map[string]string `json:",omitempty"`

// GatewayClass name
Name string `json:",omitempty"`
ControllerName string `json:",omitempty"`
// GatewayClass description
Description *string `json:",omitempty"`

Status *gatewayv1.GatewayClassStatus `json:",omitempty"`
DirectlyAttachedPolicies []common.ObjRef `json:",omitempty"`
}

func (gcp *GatewayClassesPrinter) GetPrintableNodes(resourceModel *resourcediscovery.ResourceModel) []NodeResource {
return NodeResources(common.MapToValues(resourceModel.GatewayClasses))
}
Expand Down Expand Up @@ -96,65 +72,33 @@ func (gcp *GatewayClassesPrinter) PrintDescribeView(resourceModel *resourcedisco
index := 0
for _, gatewayClassNode := range resourceModel.GatewayClasses {
index++
apiVersion, kind := gatewayClassNode.GatewayClass.GetObjectKind().GroupVersionKind().ToAPIVersionAndKind()

metadata := gatewayClassNode.GatewayClass.ObjectMeta.DeepCopy()
metadata.Labels = nil
metadata.Annotations = nil
metadata.Name = ""
metadata.Namespace = ""

// views ordered with respect to https://gateway-api.sigs.k8s.io/geps/gep-2722/
views := []gatewayClassDescribeView{
{
Name: gatewayClassNode.GatewayClass.GetName(),
},
{
Labels: ptr.To(gatewayClassNode.GatewayClass.GetLabels()),
},
{
Annotations: ptr.To(gatewayClassNode.GatewayClass.GetAnnotations()),
},
{
APIVersion: apiVersion,
},
{
Kind: kind,
},
{
Metadata: metadata,
},
{
ControllerName: string(gatewayClassNode.GatewayClass.Spec.ControllerName),
},
}
if gatewayClassNode.GatewayClass.Spec.Description != nil {
views = append(views, gatewayClassDescribeView{
Description: gatewayClassNode.GatewayClass.Spec.Description,
})
}
views = append(views, gatewayClassDescribeView{
Status: &gatewayClassNode.GatewayClass.Status,
})

if policyRefs := resourcediscovery.ConvertPoliciesMapToPolicyRefs(gatewayClassNode.Policies); len(policyRefs) != 0 {
views = append(views, gatewayClassDescribeView{
DirectlyAttachedPolicies: policyRefs,
})
metadata.ManagedFields = nil

pairs := []*DescriberKV{
{Key: "Name", Value: gatewayClassNode.GatewayClass.GetName()},
{Key: "Labels", Value: gatewayClassNode.GatewayClass.GetLabels()},
{Key: "Annotations", Value: gatewayClassNode.GatewayClass.GetAnnotations()},
{Key: "APIVersion", Value: gatewayClassNode.GatewayClass.APIVersion},
{Key: "Kind", Value: gatewayClassNode.GatewayClass.Kind},
{Key: "Metadata", Value: metadata},
{Key: "Spec", Value: &gatewayClassNode.GatewayClass.Spec},
{Key: "Status", Value: &gatewayClassNode.GatewayClass.Status},
}

for _, view := range views {
b, err := yaml.Marshal(view)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to marshal to yaml: %v\n", err)
os.Exit(1)
}
output := string(b)
// DirectlyAttachedPolicies
policyRefs := resourcediscovery.ConvertPoliciesMapToPolicyRefs(gatewayClassNode.Policies)
pairs = append(pairs, &DescriberKV{Key: "DirectlyAttachedPolicies", Value: convertPolicyRefsToTable(policyRefs)})

emptyOutput := strings.TrimSpace(output) == "{}"
if !emptyOutput {
fmt.Fprint(gcp, output)
}
}
// Events
pairs = append(pairs, &DescriberKV{Key: "Events", Value: convertEventsSliceToTable(gatewayClassNode.Events, gcp.Clock)})

Describe(gcp, pairs)

if index+1 <= len(resourceModel.GatewayClasses) {
fmt.Fprintf(gcp, "\n\n")
Expand Down
51 changes: 45 additions & 6 deletions gwctl/pkg/printer/gatewayclasses_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (

"github.com/google/go-cmp/cmp"

corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
Expand Down Expand Up @@ -140,8 +141,13 @@ func TestGatewayClassesPrinter_PrintDescribeView(t *testing.T) {
name: "GatewayClass with description and policy",
objects: []runtime.Object{
&gatewayv1.GatewayClass{
TypeMeta: metav1.TypeMeta{
APIVersion: gatewayv1.GroupVersion.String(),
Kind: "GatewayClass",
},
ObjectMeta: metav1.ObjectMeta{
Name: "foo-gatewayclass",
UID: "00000000-0000-0000-0000-000000000001",
},
Spec: gatewayv1.GatewayClassSpec{
ControllerName: "example.net/gateway-controller",
Expand Down Expand Up @@ -180,27 +186,55 @@ func TestGatewayClassesPrinter_PrintDescribeView(t *testing.T) {
},
},
},
&corev1.Event{
ObjectMeta: metav1.ObjectMeta{
Name: "event-1",
},
Type: corev1.EventTypeNormal,
Reason: "SYNC",
Source: corev1.EventSource{
Component: "my-gateway-controller",
},
InvolvedObject: corev1.ObjectReference{
Kind: "GatewayClass",
Name: "foo-gatewayclass",
UID: "00000000-0000-0000-0000-000000000001",
},
Message: "some random message",
},
},
want: `
Name: foo-gatewayclass
Labels: null
Annotations: null
APIVersion: gateway.networking.k8s.io/v1
Kind: GatewayClass
Metadata:
creationTimestamp: null
resourceVersion: "999"
ControllerName: example.net/gateway-controller
Description: random
uid: 00000000-0000-0000-0000-000000000001
Spec:
controllerName: example.net/gateway-controller
description: random
Status: {}
DirectlyAttachedPolicies:
- Group: foo.com
Kind: HealthCheckPolicy
Name: policy-name
Type Name
---- ----
HealthCheckPolicy.foo.com policy-name
Events:
Type Reason Age From Message
---- ------ --- ---- -------
Normal SYNC Unknown my-gateway-controller some random message
`,
},
{
name: "GatewayClass with no description",
objects: []runtime.Object{
&gatewayv1.GatewayClass{
TypeMeta: metav1.TypeMeta{
APIVersion: gatewayv1.GroupVersion.String(),
Kind: "GatewayClass",
},
ObjectMeta: metav1.ObjectMeta{
Name: "foo-gatewayclass",
Labels: map[string]string{
Expand All @@ -217,11 +251,16 @@ Name: foo-gatewayclass
Labels:
foo: bar
Annotations: null
APIVersion: gateway.networking.k8s.io/v1
Kind: GatewayClass
Metadata:
creationTimestamp: null
resourceVersion: "999"
ControllerName: example.net/gateway-controller
Spec:
controllerName: example.net/gateway-controller
Status: {}
DirectlyAttachedPolicies: <none>
Events: <none>
`,
},
}
Expand Down
Loading

0 comments on commit 42c411c

Please sign in to comment.