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

[kn-admin] Avoid to print runtime error if kubectl context is not set  #70

Open
@chaozbj

Description

@chaozbj

If the kubectl context is not set or run kubectl config unset current-context to unset it, we will get runtime error when run kn admin, for example:

☕10:37 ➜ ~/ [chao ✘] k config current-context
error: current-context is not set
☕10:36 ➜ ~/ [chao ✘] ./cmd autoscaling update --scale-to-zero
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb0 pc=0x1da8c10]

goroutine 1 [running]:
knative.dev/client-contrib/plugins/admin/pkg/command/autoscaling.NewAutoscalingUpdateCommand.func2(0xc0002e4f00, 0xc0002c7ff0, 0x0, 0x1, 0x0, 0x0)
	/Users/chao/Workspace/Code/github.com/client-contrib/plugins/admin/pkg/command/autoscaling/update.go:66 +0xa0
github.com/spf13/cobra.(*Command).execute(0xc0002e4f00, 0xc0002c7fe0, 0x1, 0x1, 0xc0002e4f00, 0xc0002c7fe0)
	/Users/chao/Workspace/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:826 +0x460
github.com/spf13/cobra.(*Command).ExecuteC(0xc000197400, 0x0, 0x0, 0xc000197400)
	/Users/chao/Workspace/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:914 +0x2fb
github.com/spf13/cobra.(*Command).Execute(...)
	/Users/chao/Workspace/Code/go/pkg/mod/github.com/spf13/[email protected]/command.go:864
main.main()
	/Users/chao/Workspace/Code/github.com/client-contrib/plugins/admin/cmd/kn-admin.go:24 +0x40

I checked the codes in AdminParams:

// Initialize generate the clientset for params
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
}

// rootCmd represents the base command when called without any subcommands
func NewAdminCommand(params ...pkg.AdminParams) *cobra.Command {
	p := &pkg.AdminParams{}
	p.Initialize()

	rootCmd := &cobra.Command{
		Use:   "kn\u00A0admin",
		Short: "A plugin of kn client to manage Knative",
		Long:  `kn admin: a plugin of kn client to manage Knative for administrators`,

...

I think we can do some improvements for the above functions so that we can avoid outputting runtime error if kubectl context is not set:

  1. In Initialize(), we'd better return error when fail to create ClientSet
  2. In NewAdminCommand(), we should check the error from p.Initialize(), if error is returned, we can print the error message and exit to run command.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions