Skip to content
This repository has been archived by the owner on Mar 9, 2021. It is now read-only.

Commit

Permalink
[kn-admin]Refine k8s client and flag check (#25)
Browse files Browse the repository at this point in the history
- Refine k8s client init and align with kn client
- Add preRunE to check flag values
- Add default help
  • Loading branch information
Gong Zhang authored May 5, 2020
1 parent 266a40d commit f0ebfab
Show file tree
Hide file tree
Showing 6 changed files with 119 additions and 47 deletions.
23 changes: 4 additions & 19 deletions plugins/admin/core/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@ import (
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"knative.dev/client-contrib/plugins/admin/pkg"
"knative.dev/client-contrib/plugins/admin/pkg/command"
"knative.dev/client-contrib/plugins/admin/pkg/command/domain"
Expand All @@ -35,23 +33,7 @@ var cfgFile string

func NewAdminCommand(params ...pkg.AdminParams) *cobra.Command {
p := &pkg.AdminParams{}
kubeConfig := os.Getenv("KUBECONFIG")
if kubeConfig == "" {
fmt.Println("cannot get cluster kube config, please export environment variable KUBECONFIG")
os.Exit(1)
}

cfg, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
if err != nil {
fmt.Println("failed to build config:", err)
os.Exit(1)
}

p.ClientSet, err = kubernetes.NewForConfig(cfg)
if err != nil {
fmt.Println("failed to create client:", err)
os.Exit(1)
}
p.Initialize()

rootCmd := &cobra.Command{
Use: "kn\u00A0admin",
Expand All @@ -70,6 +52,9 @@ kn admin registry add - to add registry with credentials
rootCmd.AddCommand(domain.NewDomainCmd(p))
rootCmd.AddCommand(private_registry.NewPrivateRegistryCmd(p))
rootCmd.AddCommand(command.NewVersionCommand())

// Add default help page if there's unknown command
rootCmd.InitDefaultHelpCmd()
return rootCmd
}

Expand Down
8 changes: 2 additions & 6 deletions plugins/admin/pkg/command/domain/domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
package domain

import (
"fmt"

"github.com/spf13/cobra"
"knative.dev/client-contrib/plugins/admin/pkg"
)
Expand All @@ -26,13 +24,11 @@ func NewDomainCmd(p *pkg.AdminParams) *cobra.Command {
var domainCmd = &cobra.Command{
Use: "domain",
Short: "Manage route domain",
Long: `Set default route domain or route domain for Service with selectors. For example:
Long: `Set default route domain or custom route domain for Service with selectors. For example:
kn admin domain set - to set Knative route domain`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("domain called")
},
}
domainCmd.AddCommand(NewDomainSetCommand(p))
domainCmd.InitDefaultHelpCmd()
return domainCmd
}
11 changes: 11 additions & 0 deletions plugins/admin/pkg/command/domain/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package domain

import (
"errors"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -45,6 +46,12 @@ kn admin domain set --custom-domain mydomain.com
# To set a route domain for service having label app=v1
kn admin domain set --custom-domain mydomain.com --selector app=v1
`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if domain == "" {
return errors.New("'domain set' requires the route name to run provided with the --custom-domain option")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
currentCm := &corev1.ConfigMap{}
currentCm, err := p.ClientSet.CoreV1().ConfigMaps("knative-serving").Get("config-domain", metav1.GetOptions{})
Expand Down Expand Up @@ -94,7 +101,11 @@ kn admin domain set --custom-domain mydomain.com --selector app=v1
}

domainSetCommand.Flags().StringVarP(&domain, "custom-domain", "d", "", "Desired custom domain")
domainSetCommand.MarkFlagRequired("custom-domain")
domainSetCommand.Flags().StringSliceVar(&selector, "selector", nil, "Domain selector")

domainSetCommand.InitDefaultHelpFlag()

return domainSetCommand
}

Expand Down
58 changes: 36 additions & 22 deletions plugins/admin/pkg/command/registry/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
package registry

import (
"errors"
"fmt"
"os"

Expand All @@ -28,14 +29,14 @@ import (
)

type prcmdFlags struct {
DockerServer string
SecretName string
DockerEmail string
DockerUsername string
DockerPassword string
Server string
SecretName string
Email string
Username string
Password string
}

type DockerRegistry struct {
type Registry struct {
Auths Auths `json:"auths"`
}
type RegistryCred struct {
Expand All @@ -44,9 +45,6 @@ type RegistryCred struct {
Email string `json:"Email"`
}

//type Auths struct {
// RegistryCred RegistryCred `json:"us.icr.io"`
//}
type Auths map[string]RegistryCred

//
Expand All @@ -69,13 +67,25 @@ kn admin registry add \
--email=[REGISTRY_EMAIL] \
--username=[REGISTRY_USER] \
--password=[REGISTRY_PASSWORD]`,
PreRunE: func(cmd *cobra.Command, args []string) error {
if prflags.Username == "" {
return errors.New("'registry add' requires the registry user name to run provided with the --username option")
}
if prflags.Password == "" {
return errors.New("'registry add' requires the registry password to run provided with the --password option")
}
if prflags.Server == "" {
return errors.New("'registry add' requires the registry server to run provided with the --server option")
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
dockerCfg := DockerRegistry{
dockerCfg := Registry{
Auths: Auths{
prflags.DockerServer: RegistryCred{
Username: prflags.DockerUsername,
Password: prflags.DockerPassword,
Email: prflags.DockerEmail,
prflags.Server: RegistryCred{
Username: prflags.Username,
Password: prflags.Password,
Email: prflags.Email,
},
},
}
Expand All @@ -96,8 +106,8 @@ kn admin registry add \
},
Type: corev1.SecretTypeDockerConfigJson,
ObjectMeta: metav1.ObjectMeta{
Name: prflags.SecretName,
Namespace: "default",
GenerateName: fmt.Sprintf("%s-", prflags.SecretName),
Namespace: "default",
},
Data: secretData,
}
Expand All @@ -120,15 +130,19 @@ kn admin registry add \
os.Exit(1)
}

fmt.Printf("Private registry %s added for default Service Account\n", prflags.DockerServer)
fmt.Printf("Private registry %s added for default Service Account\n", prflags.Server)
},
}

prAddCmd.Flags().StringVar(&prflags.SecretName, "secret-name", "", "Registry Secret Name")
prAddCmd.Flags().StringVar(&prflags.DockerServer, "server", "", "Registry Address")
prAddCmd.Flags().StringVar(&prflags.DockerEmail, "email", "", "Registry Email")
prAddCmd.Flags().StringVar(&prflags.DockerUsername, "username", "", "Registry Username")
prAddCmd.Flags().StringVar(&prflags.DockerPassword, "password", "", "Registry Email")
prAddCmd.Flags().StringVar(&prflags.SecretName, "secret-name", "secret-registry", "Registry Secret Name")
prAddCmd.Flags().StringVar(&prflags.Server, "server", "", "Registry Address")
prAddCmd.MarkFlagRequired("server")
prAddCmd.Flags().StringVar(&prflags.Email, "email", "[email protected]", "Registry Email")
prAddCmd.Flags().StringVar(&prflags.Username, "username", "", "Registry Username")
prAddCmd.MarkFlagRequired("username")
prAddCmd.Flags().StringVar(&prflags.Password, "password", "", "Registry Password")
prAddCmd.MarkFlagRequired("password")

prAddCmd.InitDefaultHelpFlag()
return prAddCmd
}
1 change: 1 addition & 0 deletions plugins/admin/pkg/command/registry/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,6 @@ kn admin registry add \
--password=[REGISTRY_PASSWORD]`,
}
privateRegistryCmd.AddCommand(NewPrAddCommand(p))
privateRegistryCmd.InitDefaultHelpCmd()
return privateRegistryCmd
}
65 changes: 65 additions & 0 deletions plugins/admin/pkg/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,12 @@
package pkg

import (
"fmt"
"os"
"path/filepath"

"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
)

Expand All @@ -24,3 +29,63 @@ type AdminParams struct {
ClientConfig clientcmd.ClientConfig
ClientSet *kubernetes.Clientset
}

func (params *AdminParams) Initialize() error {
if params.ClientSet == nil {
restConfig, err := params.RestConfig()
if err != nil {
return err
}

params.ClientSet, err = kubernetes.NewForConfig(restConfig)
if err != nil {
fmt.Println("failed to create client:", err)
os.Exit(1)
}
}
return nil
}

// RestConfig returns REST config, which can be to use to create specific clientset
func (params *AdminParams) RestConfig() (*rest.Config, error) {
var err error

if params.ClientConfig == nil {
params.ClientConfig, err = params.GetClientConfig()
if err != nil {
return nil, err
}
}

config, err := params.ClientConfig.ClientConfig()
if err != nil {
return nil, err
}

return config, nil
}

// GetClientConfig gets ClientConfig from KubeCfgPath
func (params *AdminParams) GetClientConfig() (clientcmd.ClientConfig, error) {
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules()
if len(params.KubeCfgPath) == 0 {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}), nil
}

_, err := os.Stat(params.KubeCfgPath)
if err == nil {
loadingRules.ExplicitPath = params.KubeCfgPath
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, &clientcmd.ConfigOverrides{}), nil
}

if !os.IsNotExist(err) {
return nil, err
}

paths := filepath.SplitList(params.KubeCfgPath)
if len(paths) > 1 {
return nil, fmt.Errorf("Can not find config file. '%s' looks like a path. "+
"Please use the env var KUBECONFIG if you want to check for multiple configuration files", params.KubeCfgPath)
}
return nil, fmt.Errorf("Config file '%s' can not be found", params.KubeCfgPath)
}

0 comments on commit f0ebfab

Please sign in to comment.