Skip to content

Commit

Permalink
Implement basic functionality of gwctl describe namespace (kubernetes…
Browse files Browse the repository at this point in the history
…-sigs#2836)

* Implement basic functionality of gwctl describe namespace

* Finalized printing of gwctl describe namespace command

* Added test for gwctl describe namespace and modified ResourceModel.addNamespace() function to accept corev1.Namespace

* Fixed failing httproutes test and Makefile
  • Loading branch information
Devaansh-Kumar authored and hanxiaop committed Mar 13, 2024
1 parent 08c181b commit 34e51fc
Show file tree
Hide file tree
Showing 10 changed files with 376 additions and 21 deletions.
2 changes: 1 addition & 1 deletion gwctl/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ deps:

build: deps
@echo "Building gwctl..."
@go build -o bin/gwctl cmd/main.go
@go build -o bin/gwctl main.go
16 changes: 15 additions & 1 deletion gwctl/cmd/describe.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func NewDescribeCommand() *cobra.Command {
var allNamespacesFlag bool

cmd := &cobra.Command{
Use: "describe {policies|httproutes|gateways|gatewayclasses|backends} RESOURCE_NAME",
Use: "describe {policies|httproutes|gateways|gatewayclasses|backends|namespace} RESOURCE_NAME",
Short: "Show details of a specific resource or group of resources",
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
Expand Down Expand Up @@ -78,6 +78,7 @@ func runDescribe(cmd *cobra.Command, args []string, params *utils.CmdParams) {
gwPrinter := &printer.GatewaysPrinter{Out: params.Out}
gwcPrinter := &printer.GatewayClassesPrinter{Out: params.Out}
backendsPrinter := &printer.BackendsPrinter{Out: params.Out}
namespacesPrinter := &printer.NamespacesPrinter{Out: params.Out}

switch kind {
case "policy", "policies":
Expand Down Expand Up @@ -146,6 +147,19 @@ func runDescribe(cmd *cobra.Command, args []string, params *utils.CmdParams) {
}
backendsPrinter.PrintDescribeView(resourceModel)

case "namespace", "namespaces":
filter := resourcediscovery.Filter{}
if len(args) > 1 {
filter.Name = args[1]
}

resourceModel, err := discoverer.DiscoverResourcesForNamespace(filter)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to discover Namespace resources: %v\n", err)
os.Exit(1)
}
namespacesPrinter.PrintDescribeView(resourceModel)

default:
fmt.Fprintf(os.Stderr, "Unrecognized RESOURCE_TYPE\n")
}
Expand Down
2 changes: 1 addition & 1 deletion gwctl/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
k8s.io/apimachinery v0.29.2
k8s.io/client-go v0.29.2
k8s.io/klog/v2 v2.120.1
k8s.io/utils v0.0.0-20240102154912-e7106e64919e
sigs.k8s.io/controller-runtime v0.17.2
sigs.k8s.io/gateway-api v1.0.0
sigs.k8s.io/yaml v1.4.0
Expand Down Expand Up @@ -53,7 +54,6 @@ require (
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/kube-openapi v0.0.0-20240105020646-a37d4de58910 // indirect
k8s.io/utils v0.0.0-20240102154912-e7106e64919e // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
)
4 changes: 2 additions & 2 deletions gwctl/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
Expand Down
17 changes: 17 additions & 0 deletions gwctl/pkg/printer/httproutes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (

"github.com/google/go-cmp/cmp"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
Expand Down Expand Up @@ -57,6 +58,22 @@ func TestHTTPRoutesPrinter_Print(t *testing.T) {
Description: common.PtrTo("random"),
},
},
&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "ns1",
},
Status: corev1.NamespaceStatus{
Phase: corev1.NamespaceActive,
},
},
&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "ns2",
},
Status: corev1.NamespaceStatus{
Phase: corev1.NamespaceActive,
},
},
&gatewayv1.Gateway{
ObjectMeta: metav1.ObjectMeta{
Name: "demo-gateway-1",
Expand Down
78 changes: 78 additions & 0 deletions gwctl/pkg/printer/namespace.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
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"

"sigs.k8s.io/gateway-api/gwctl/pkg/policymanager"
"sigs.k8s.io/gateway-api/gwctl/pkg/resourcediscovery"
"sigs.k8s.io/yaml"
)

type NamespacesPrinter struct {
Out io.Writer
}

type namespaceDescribeView struct {
Name string `json:",omitempty"`
Labels map[string]string `json:",omitempty"`
Annotations map[string]string `json:",omitempty"`
Status string `json:",omitempty"`
DirectlyAttachedPolicies []policymanager.ObjRef `json:",omitempty"`
}

func (nsp *NamespacesPrinter) PrintDescribeView(resourceModel *resourcediscovery.ResourceModel) {
index := 0
for _, namespaceNode := range resourceModel.Namespaces {
index++

views := []namespaceDescribeView{
{
Name: namespaceNode.Namespace.Name,
},
{
Annotations: namespaceNode.Namespace.Annotations,
Labels: namespaceNode.Namespace.Labels,
},
{
Status: string(namespaceNode.Namespace.Status.Phase),
},
}

if policyRefs := resourcediscovery.ConvertPoliciesMapToPolicyRefs(namespaceNode.Policies); len(policyRefs) != 0 {
views = append(views, namespaceDescribeView{
DirectlyAttachedPolicies: policyRefs,
})
}

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)
}
fmt.Fprint(nsp.Out, string(b))
}

if index+1 <= len(resourceModel.Namespaces) {
fmt.Fprintf(nsp.Out, "\n\n")
}
}
}
187 changes: 187 additions & 0 deletions gwctl/pkg/printer/namespace_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
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"
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"
"k8s.io/apimachinery/pkg/runtime"
gatewayv1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
"sigs.k8s.io/gateway-api/gwctl/pkg/utils"
"sigs.k8s.io/gateway-api/gwctl/pkg/common"
"sigs.k8s.io/gateway-api/gwctl/pkg/resourcediscovery"
)

func TestNamespacePrinter_PrintDescribeView(t *testing.T) {
objects := []runtime.Object{
// Defining a Namespace called development
&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "development",
Labels: map[string]string{
"type": "test-namespace",
},
Annotations: map[string]string{
"test-annotation": "development-annotation",
},
},
Status: corev1.NamespaceStatus{
Phase: corev1.NamespaceActive,
},
},

// CRD and definition for HealthCheckPolicy attached to development namespace
&apiextensionsv1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: "healthcheckpolicies.foo.com",
Labels: map[string]string{
gatewayv1alpha2.PolicyLabelKey: "inherited",
},
},
Spec: apiextensionsv1.CustomResourceDefinitionSpec{
Scope: apiextensionsv1.ClusterScoped,
Group: "foo.com",
Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{Name: "v1"}},
Names: apiextensionsv1.CustomResourceDefinitionNames{
Plural: "healthcheckpolicies",
Kind: "HealthCheckPolicy",
},
},
},
&unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "foo.com/v1",
"kind": "HealthCheckPolicy",
"metadata": map[string]interface{}{
"name": "health-check-gatewayclass",
},
"spec": map[string]interface{}{
"override": map[string]interface{}{
"key1": "value-parent-1",
"key3": "value-parent-3",
"key5": "value-parent-5",
},
"default": map[string]interface{}{
"key2": "value-parent-2",
"key4": "value-parent-4",
},
"targetRef": map[string]interface{}{
"kind": "Namespace",
"name": "development",
},
},
},
},

// Defining a Namespace called production
&corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
Name: "production",
Labels: map[string]string{
"type": "production-namespace",
},
},
Status: corev1.NamespaceStatus{
Phase: corev1.NamespaceActive,
},
},
// CRD and definition for TimeoutPolicy attached to default namespace
&apiextensionsv1.CustomResourceDefinition{
ObjectMeta: metav1.ObjectMeta{
Name: "timeoutpolicies.bar.com",
Labels: map[string]string{
gatewayv1alpha2.PolicyLabelKey: "direct",
},
},
Spec: apiextensionsv1.CustomResourceDefinitionSpec{
Scope: apiextensionsv1.ClusterScoped,
Group: "bar.com",
Versions: []apiextensionsv1.CustomResourceDefinitionVersion{{Name: "v1"}},
Names: apiextensionsv1.CustomResourceDefinitionNames{
Plural: "timeoutpolicies",
Kind: "TimeoutPolicy",
},
},
},
&unstructured.Unstructured{
Object: map[string]interface{}{
"apiVersion": "bar.com/v1",
"kind": "TimeoutPolicy",
"metadata": map[string]interface{}{
"name": "timeout-policy-namespace",
},
"spec": map[string]interface{}{
"condition": "path=/abc",
"seconds": int64(30),
"targetRef": map[string]interface{}{
"kind": "Namespace",
"name": "production",
},
},
},
},
}

params := utils.MustParamsForTest(t, common.MustClientsForTest(t, objects...))
discoverer := resourcediscovery.Discoverer{
K8sClients: params.K8sClients,
PolicyManager: params.PolicyManager,
}
resourceModel, err := discoverer.DiscoverResourcesForNamespace(resourcediscovery.Filter{})
if err != nil {
t.Fatalf("Failed to construct resourceModel: %v", resourceModel)
}

nsp := &NamespacesPrinter{
Out: params.Out,
}
nsp.PrintDescribeView(resourceModel)

got := params.Out.(*bytes.Buffer).String()
want := `
Name: development
Annotations:
test-annotation: development-annotation
Labels:
type: test-namespace
Status: Active
DirectlyAttachedPolicies:
- Group: foo.com
Kind: HealthCheckPolicy
Name: health-check-gatewayclass
Name: production
Labels:
type: production-namespace
Status: Active
DirectlyAttachedPolicies:
- Group: bar.com
Kind: TimeoutPolicy
Name: timeout-policy-namespace
`
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)
}

}
Loading

0 comments on commit 34e51fc

Please sign in to comment.