Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve utilities for gwctl describe and add more info to gateway descriptions #2999

Merged
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
11 changes: 6 additions & 5 deletions gwctl/cmd/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/utils/clock"
)

func NewDescribeCommand() *cobra.Command {
Expand Down Expand Up @@ -81,12 +82,12 @@ func runDescribe(cmd *cobra.Command, args []string, params *utils.CmdParams) {
K8sClients: params.K8sClients,
PolicyManager: params.PolicyManager,
}
policiesPrinter := &printer.PoliciesPrinter{Out: params.Out}
httpRoutesPrinter := &printer.HTTPRoutesPrinter{Out: params.Out}
gwPrinter := &printer.GatewaysPrinter{Out: params.Out}
gwcPrinter := &printer.GatewayClassesPrinter{Out: params.Out}
policiesPrinter := &printer.PoliciesPrinter{Out: params.Out, Clock: clock.RealClock{}}
httpRoutesPrinter := &printer.HTTPRoutesPrinter{Out: params.Out, Clock: clock.RealClock{}}
gwPrinter := &printer.GatewaysPrinter{Out: params.Out, Clock: clock.RealClock{}}
gwcPrinter := &printer.GatewayClassesPrinter{Out: params.Out, Clock: clock.RealClock{}}
backendsPrinter := &printer.BackendsPrinter{Out: params.Out}
namespacesPrinter := &printer.NamespacesPrinter{Out: params.Out}
namespacesPrinter := &printer.NamespacesPrinter{Out: params.Out, Clock: clock.RealClock{}}

switch kind {
case "policy", "policies":
Expand Down
26 changes: 25 additions & 1 deletion gwctl/pkg/common/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"fmt"
"testing"

corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/discovery"
Expand Down Expand Up @@ -93,7 +94,30 @@ func MustClientsForTest(t *testing.T, initRuntimeObjects ...runtime.Object) *K8s
t.Fatal(err)
}

fakeClient := fakeclient.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(initRuntimeObjects...).Build()
// These extractorFuncs are used to properly mock the kubernetes client
// dependency in unit tests. They enable the ability to be able to list Events
// associated with a specific resource.
eventKindExtractorFunc := func(o client.Object) []string {
return []string{o.(*corev1.Event).InvolvedObject.Kind}
}
eventNameExtractorFunc := func(o client.Object) []string {
return []string{o.(*corev1.Event).InvolvedObject.Name}
}
eventNamespaceExtractorFunc := func(o client.Object) []string {
return []string{o.(*corev1.Event).InvolvedObject.Namespace}
}
eventUIDExtractorFunc := func(o client.Object) []string {
return []string{string(o.(*corev1.Event).InvolvedObject.UID)}
}

fakeClient := fakeclient.NewClientBuilder().
WithScheme(scheme).
WithRuntimeObjects(initRuntimeObjects...).
WithIndex(&corev1.Event{}, "involvedObject.kind", eventKindExtractorFunc).
WithIndex(&corev1.Event{}, "involvedObject.name", eventNameExtractorFunc).
WithIndex(&corev1.Event{}, "involvedObject.namespace", eventNamespaceExtractorFunc).
WithIndex(&corev1.Event{}, "involvedObject.uid", eventUIDExtractorFunc).
Build()
fakeDC := fakedynamicclient.NewSimpleDynamicClient(scheme, initRuntimeObjects...)
fakeDiscoveryClient := fakeclientset.NewSimpleClientset().Discovery()

Expand Down
150 changes: 150 additions & 0 deletions gwctl/pkg/printer/common.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
Copyright 2024 The Kubernetes 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 printer

import (
"fmt"
"io"
"os"
"strings"
"text/tabwriter"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/util/duration"
"k8s.io/utils/clock"
"sigs.k8s.io/yaml"
)

// DescriberKV stores key-value pairs that are used with Describing a resource.
type DescriberKV struct {
Key string
Value any
}

const (
// Default indentation for Tables that are printed in the Describe view.
defaultDescribeTableIndentSpaces = 2
)

// Describe writes the key-value paris to the writer. It handles things like
// properly writing special data types like Tables.
func Describe(w io.Writer, pairs []*DescriberKV) {
for _, pair := range pairs {
// If the Value is of type Table, it needs special handling.
if table, ok := pair.Value.(*Table); ok {
if len(table.Rows) == 0 {
fmt.Fprintf(w, "%v: <none>\n", pair.Key)
} else {
fmt.Fprintf(w, "%v:\n", pair.Key)
table.writeTable(w, defaultDescribeTableIndentSpaces)
}
continue
}

// If Value is NOT a Table, it can be handled through the yaml Marshaller.
data := map[string]any{pair.Key: pair.Value}
b, err := yaml.Marshal(data)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to marshal to yaml: %v\n", err)
os.Exit(1)
}
fmt.Fprint(w, string(b))
}
}

type Table struct {
ColumnNames []string
Rows [][]string
// UseSeparator indicates whether the header row and data rows will be
// separated through a separator.
UseSeparator bool
}

// writeTable will write a formatted table to the writer. indent controls the
// number of spaces at the beginning of each row.
func (t *Table) writeTable(w io.Writer, indent int) {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)

// Print column names.
if len(t.ColumnNames) > 0 {
row := t.indentRow(t.ColumnNames, indent)
_, err := tw.Write([]byte(strings.Join(row, "\t") + "\n"))
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}

// Optionally print a separator between header row and data rows.
if t.UseSeparator {
row := make([]string, len(t.ColumnNames))
for i, value := range t.ColumnNames {
row[i] = strings.Repeat("-", len(value))
}
row = t.indentRow(row, indent)
_, err := tw.Write([]byte(strings.Join(row, "\t") + "\n"))
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}

// Print data rows.
for _, row := range t.Rows {
row = t.indentRow(row, indent)
_, err := tw.Write([]byte(strings.Join(row, "\t") + "\n"))
if err != nil {
fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
}
tw.Flush()
}

// indentRow will add 'indent' spaces to the beginning of the row.
func (t *Table) indentRow(row []string, indent int) []string {
if len(row) == 0 {
return row
}

newRow := append([]string{}, row...)
newRow[0] = fmt.Sprintf("%s%s", strings.Repeat(" ", indent), newRow[0])
return newRow
}

func convertEventsSliceToTable(events []corev1.Event, clock clock.Clock) *Table {
table := &Table{
ColumnNames: []string{"Type", "Reason", "Age", "From", "Message"},
UseSeparator: true,
}
for _, event := range events {
age := "Unknown"
if !event.FirstTimestamp.IsZero() {
age = duration.HumanDuration(clock.Since(event.FirstTimestamp.Time))
}

row := []string{
event.Type, // Type
event.Reason, // Reason
age, // Age
event.Source.Component, // From
event.Message, // Message
}
table.Rows = append(table.Rows, row)
}
return table
}
158 changes: 158 additions & 0 deletions gwctl/pkg/printer/common_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
/*
Copyright 2024 The Kubernetes 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 printer

import (
"bytes"
"testing"

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

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

func TestDescribe(t *testing.T) {
pairs := []*DescriberKV{
{Key: "Key1", Value: "string"},
{Key: "Key2", Value: []any{"list-string1", 1234, "list-string-3"}},
{
Key: "Key3-with-nested-structures",
Value: map[string]any{
"a": "b",
"d": map[string]any{
"e": []string{"v1", "v2", "v3"},
},
"c": 123,
},
},
{
Key: "Key4-table",
Value: &Table{
ColumnNames: []string{"col1", "col2", "col3"},
Rows: [][]string{
{"row1-a", "row1-b", "row1-c"},
{"row2-a", "row2-b", "row2-c"},
{"row3-a", "row3-b", "row3-c"},
},
UseSeparator: true,
},
},
}

writable := &bytes.Buffer{}
Describe(writable, pairs)

got := writable.String()
want := `
Key1: string
Key2:
- list-string1
- 1234
- list-string-3
Key3-with-nested-structures:
a: b
c: 123
d:
e:
- v1
- v2
- v3
Key4-table:
col1 col2 col3
---- ---- ----
row1-a row1-b row1-c
row2-a row2-b row2-c
row3-a row3-b row3-c
`
if diff := cmp.Diff(common.YamlString(want), common.YamlString(got), common.YamlStringTransformer); diff != "" {
t.Errorf("Unexpected diff\ngot=\n%v\nwant=\n%v\ndiff (-want +got)=\n%v", got, want, diff)
}
}

func TestTable_writeTable(t *testing.T) {
testcases := []struct {
name string
table *Table
indent int
want string
}{
{
name: "without separator",
table: &Table{
ColumnNames: []string{"Kind", "Name"},
Rows: [][]string{
{"HTTPRoute", "default/my-httproute"},
{"TCPRoute", "ns2/my-tcproute"},
},
},
indent: 0,
want: `
Kind Name
HTTPRoute default/my-httproute
TCPRoute ns2/my-tcproute
`,
},
{
name: "with separator",
table: &Table{
ColumnNames: []string{"Kind", "Name"},
Rows: [][]string{
{"HTTPRoute", "default/my-httproute"},
{"TCPRoute", "ns2/my-tcproute"},
},
UseSeparator: true,
},
indent: 0,
want: `
Kind Name
---- ----
HTTPRoute default/my-httproute
TCPRoute ns2/my-tcproute
`,
},
{
name: "with indent and separator",
table: &Table{
ColumnNames: []string{"Kind", "Name"},
Rows: [][]string{
{"HTTPRoute", "default/my-httproute"},
{"TCPRoute", "ns2/my-tcproute"},
},
UseSeparator: true,
},
indent: 3, // We want 3 spaces at the start of each row.
want: `
Kind Name
---- ----
HTTPRoute default/my-httproute
TCPRoute ns2/my-tcproute
`,
},
}

for _, tc := range testcases {
t.Run(tc.name, func(t *testing.T) {
writable := &bytes.Buffer{}
tc.table.writeTable(writable, tc.indent)

got := writable.String()
if diff := cmp.Diff(common.YamlString(tc.want), common.YamlString(got), common.YamlStringTransformer); diff != "" {
t.Errorf("Unexpected diff\ngot=\n%v\nwant=\n%v\ndiff (-want +got)=\n%v", got, tc.want, diff)
}
})
}
}
Loading