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

5. kubectl-kcp: get rid of workspace duality and implement logical cluster path semantics #778

Merged
merged 6 commits into from
Mar 31, 2022
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
50 changes: 50 additions & 0 deletions cmd/kubectl-workspaces/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2022 The KCP 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 main

import (
goflags "flag"
"fmt"
"os"

"github.com/spf13/pflag"

"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/klog/v2"

"github.com/kcp-dev/kcp/pkg/cliplugins/workspace/cmd"
)

func main() {
flags := pflag.NewFlagSet("kubectl-kcp", pflag.ExitOnError)
pflag.CommandLine = flags

workspaceCmd, err := cmd.NewCmdWorkspace(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}

// setup klog
fs := goflags.NewFlagSet("klog", goflags.PanicOnError)
klog.InitFlags(fs)
workspaceCmd.PersistentFlags().AddGoFlagSet(fs)

if err := workspaceCmd.Execute(); err != nil {
os.Exit(1)
}
}
50 changes: 50 additions & 0 deletions cmd/kubectl-ws/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright 2022 The KCP 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 main

import (
goflags "flag"
"fmt"
"os"

"github.com/spf13/pflag"

"k8s.io/cli-runtime/pkg/genericclioptions"
"k8s.io/klog/v2"

"github.com/kcp-dev/kcp/pkg/cliplugins/workspace/cmd"
)

func main() {
flags := pflag.NewFlagSet("kubectl-kcp", pflag.ExitOnError)
pflag.CommandLine = flags

workspaceCmd, err := cmd.NewCmdWorkspace(genericclioptions.IOStreams{In: os.Stdin, Out: os.Stdout, ErrOut: os.Stderr})
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}

// setup klog
fs := goflags.NewFlagSet("klog", goflags.PanicOnError)
klog.InitFlags(fs)
workspaceCmd.PersistentFlags().AddGoFlagSet(fs)

if err := workspaceCmd.Execute(); err != nil {
os.Exit(1)
}
}
4 changes: 4 additions & 0 deletions config/crds/tenancy.kcp.dev_clusterworkspaces.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ spec:
jsonPath: .status.phase
name: Phase
type: string
- description: URL to access the workspace
jsonPath: .status.baseURL
name: URL
type: string
name: v1alpha1
schema:
openAPIV3Schema:
Expand Down
4 changes: 4 additions & 0 deletions config/crds/tenancy.kcp.dev_workspaces.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ spec:
jsonPath: .status.phase
name: Phase
type: string
- description: URL to access the workspace
jsonPath: .status.baseURL
name: URL
type: string
name: v1beta1
schema:
openAPIV3Schema:
Expand Down
1 change: 1 addition & 0 deletions config/system-crds/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ func Bootstrap(ctx context.Context, crdClient apiextensionsclient.Interface, dis
{Group: tenancy.GroupName, Resource: "clusterworkspaces"},
{Group: tenancy.GroupName, Resource: "clusterworkspacetypes"},
{Group: tenancy.GroupName, Resource: "workspaceshards"},
{Group: tenancy.GroupName, Resource: "workspaces"},
{Group: apiresource.GroupName, Resource: "apiresourceimports"},
{Group: apiresource.GroupName, Resource: "negotiatedapiresources"},
{Group: workload.GroupName, Resource: "workloadclusters"},
Expand Down
1 change: 1 addition & 0 deletions pkg/apis/tenancy/v1alpha1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ var RootCluster = logicalcluster.New("root")
// +kubebuilder:resource:scope=Cluster,categories=kcp
// +kubebuilder:printcolumn:name="Type",type=string,JSONPath=`.spec.type`,description="Type of the workspace"
// +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`,description="The current phase (e.g. Scheduling, Initializing, Ready)"
// +kubebuilder:printcolumn:name="URL",type=string,JSONPath=`.status.baseURL`,description="URL to access the workspace"
type ClusterWorkspace struct {
metav1.TypeMeta `json:",inline"`
// +optional
Expand Down
1 change: 1 addition & 0 deletions pkg/apis/tenancy/v1beta1/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import (
// +kubebuilder:resource:scope=Cluster,categories=kcp
// +kubebuilder:printcolumn:name="Type",type=string,JSONPath=`.spec.type`,description="Type of the workspace"
// +kubebuilder:printcolumn:name="Phase",type=string,JSONPath=`.status.phase`,description="The current phase (e.g. Scheduling, Initializing, Ready)"
// +kubebuilder:printcolumn:name="URL",type=string,JSONPath=`.status.baseURL`,description="URL to access the workspace"
type Workspace struct {
metav1.TypeMeta `json:",inline"`
// +optional
Expand Down
119 changes: 70 additions & 49 deletions pkg/cliplugins/workspace/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package cmd

import (
"fmt"
"time"

"github.com/spf13/cobra"

Expand All @@ -29,65 +30,83 @@ import (
var (
workspaceExample = `
# Shows the workspace you are currently using
%[1]s workspace current

# use a given workspace (this will change the current-context of your current KUBECONFIG)
%[1]s workspace use
%[1]s workspace

# enter a given workspace (this will change the current-context of your current KUBECONFIG)
%[1]s workspace use my-workspace

# list all your personal workspaces
%[1]s workspace list

# enter a given absolute workspace
%[1]s workspace root:default:my-workspace

# enter the parent workspace
%[1]s workspace ..

# enter the previous workspace
%[1]s workspace -

# create a workspace and immediately enter it
%[1]s workspace create my-workspace --use
`
)

// NewCmdWorkspace provides a cobra command wrapping WorkspaceOptions
func NewCmdWorkspace(streams genericclioptions.IOStreams) (*cobra.Command, error) {
opts := plugin.NewOptions(streams)

useRunE := func(cmd *cobra.Command, args []string) error {
if err := opts.Validate(); err != nil {
return err
}

kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
}
if len(args) > 1 {
return cmd.Help()
}

arg := ""
if len(args) == 1 {
arg = args[0]
}
return kubeconfig.UseWorkspace(cmd.Context(), arg)
}

cmd := &cobra.Command{
Aliases: []string{"ws", "workspaces"},
Use: "workspace [--scope=<personal|all>] <create|list|use|current|delete>",
Use: "workspace [list|create|<workspace>|..|-|<root:absolute:workspace>]",
Short: "Manages KCP workspaces",
Example: fmt.Sprintf(workspaceExample, "kubectl kcp"),
SilenceUsage: true,
TraverseChildren: true,
RunE: useRunE,
}

opts.BindFlags(cmd)

useCmd := &cobra.Command{
Use: "use < workspace name | - >",
Short: "Uses the given workspace as the current workspace. Using - means previous workspace",
Example: "kcp workspace use my-worspace",
Use: "use <workspace>|..|-|<root:absolute:workspace>",
Short: "Uses the given workspace as the current workspace. Using - means previous workspace, .. means parent workspace",
SilenceUsage: true,
RunE: func(c *cobra.Command, args []string) error {
kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
}
if len(args) != 1 {
return fmt.Errorf("the workspace name (or -) should be given")
if len(args) == 0 {
return c.Help()
}

if err := kubeconfig.UseWorkspace(c.Context(), opts, args[0]); err != nil {
return err
}
return nil
return useRunE(c, args)
},
}

currentCmd := &cobra.Command{
Use: "current",
Short: "Returns the name of the current workspace",
Short: "Replaced with \"kubectl kcp workspace\" or \"kubectl workspace\" or shorter \"kubectl ws\"",
Example: "kcp workspace current",
SilenceUsage: true,
RunE: func(c *cobra.Command, args []string) error {
kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
}
if err := kubeconfig.CurrentWorkspace(c.Context(), opts); err != nil {
return err
}
return nil
fmt.Println("The \"current\" command being replaced. Please do instead:\n\n kubectl kcp workspaces\n\nor shorter:\n\n kubectl ws")
return useRunE(c, nil)
},
}

Expand All @@ -97,6 +116,9 @@ func NewCmdWorkspace(streams genericclioptions.IOStreams) (*cobra.Command, error
Example: "kcp workspace list",
SilenceUsage: true,
RunE: func(c *cobra.Command, args []string) error {
if err := opts.Validate(); err != nil {
return err
}
kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
Expand All @@ -108,47 +130,46 @@ func NewCmdWorkspace(streams genericclioptions.IOStreams) (*cobra.Command, error
},
}

useFlag := "use"
var typeFlag string
var workspaceType string
var enterAfterCreation bool
var ignoreExisting bool
createCmd := &cobra.Command{
Use: "create",
Short: "Creates a new personal workspace",
Example: "kcp workspace create <workspace name>",
Example: "kcp workspace create <workspace name> [--type=<type>] [--enter [--ignore-not-ready]] --ignore-existing",
SilenceUsage: true,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
useAfterCreation, err := c.Flags().GetBool(useFlag)
if err != nil {
RunE: func(cmd *cobra.Command, args []string) error {
if err := opts.Validate(); err != nil {
return err
}

kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
}
if err := kubeconfig.CreateWorkspace(c.Context(), opts, args[0], useAfterCreation, typeFlag); err != nil {
if err := kubeconfig.CreateWorkspace(cmd.Context(), args[0], workspaceType, ignoreExisting, enterAfterCreation, time.Minute); err != nil {
return err
}
return nil
},
}
createCmd.Flags().Bool(useFlag, false, "Use the new workspace after a successful creation")
createCmd.Flags().StringVar(&typeFlag, "type", typeFlag, "The workspace type to create")
createCmd.Flags().StringVar(&workspaceType, "type", "", "A workspace type (default: Universal)")
ncdc marked this conversation as resolved.
Show resolved Hide resolved
createCmd.Flags().BoolVar(&enterAfterCreation, "enter", enterAfterCreation, "Immediately enter the created workspace")
createCmd.Flags().BoolVar(&ignoreExisting, "ignore-existing", ignoreExisting, "Ignore if the workspace already exists")
createCmd.Flags().BoolVar(&enterAfterCreation, "use", enterAfterCreation, "Use the new workspace after a successful creation")
if err := createCmd.Flags().MarkDeprecated("use", "Use --enter instead"); err != nil {
return nil, err
}

deleteCmd := &cobra.Command{
Use: "delete",
Short: "Deletes a personal workspace",
Example: "kcp workspace delete <workspace name>",
Short: "Replaced with \"kubectl delete workspace <workspace-name>\"",
Example: "kcp workspace delete <workspace-name>",
SilenceUsage: true,
Args: cobra.ExactArgs(1),
RunE: func(c *cobra.Command, args []string) error {
kubeconfig, err := plugin.NewKubeConfig(opts)
if err != nil {
return err
}
if err := kubeconfig.DeleteWorkspace(c.Context(), opts, args[0]); err != nil {
return err
}
return nil
Run: func(c *cobra.Command, args []string) {
fmt.Println("The \"delete\" command is gone. Please do instead:\n\n kubectl delete workspace <workspace-name>")
},
}

Expand Down
Loading