Skip to content

kubeletctl panics when no arguments are provided to some commands #5

@jimen0

Description

@jimen0

kubeletctl commands that require arguments cause a panicif no arguments are provided. I confirmed this behaviour with this release.

$ ./kubeletctl --http --server REDACTED --port 10255 debug
panic: runtime error: index out of range [0] with length 0

goroutine 1 [running]:
kubeletctl/cmd/proxy/debug.glob..func1(0x15708a0, 0xc00034e320, 0x0, 0x5)
	/home/ubuntu/test/kubeletctl/cmd/proxy/debug/debug.go:89 +0x1e1
github.com/spf13/cobra.(*Command).execute(0x15708a0, 0xc00034e2d0, 0x5, 0x5, 0x15708a0, 0xc00034e2d0)
	/home/ubuntu/test/kubeletctl/vendor/github.com/spf13/cobra/command.go:842 +0x29d
github.com/spf13/cobra.(*Command).ExecuteC(0x156dea0, 0x443cba, 0x151f1a0, 0xc000000180)
	/home/ubuntu/test/kubeletctl/vendor/github.com/spf13/cobra/command.go:943 +0x317
github.com/spf13/cobra.(*Command).Execute(...)
	/home/ubuntu/test/kubeletctl/vendor/github.com/spf13/cobra/command.go:883
kubeletctl/cmd.Execute()
	/home/ubuntu/test/kubeletctl/cmd/root.go:66 +0x31
main.main()
	/home/ubuntu/test/kubeletctl/main.go:20 +0x20

Panic comes from the following snippet:

var inputArgs string
if args == nil {
    fmt.Println("[*] No debug profile was specified")
    os.Exit(1)
} else {
    inputArgs = args[0]
}

The error comes from checking if the arguments slice is nil instead of checking the number of arguments (length of a nil slice is 0 too, see the playground). If no arguments are provided, cobra passes an empty slice as argument, not nil.

I confirmed this behaviour in the debug and exec commands, but it might be present in more of them.

I built this small repro so you can check cobra's behaviour when no arguments are provided:

package main

import (
	"fmt"

	"github.com/spf13/cobra"
)

func main() {
	cmdPrint := &cobra.Command{
		Use: "print [str]",
		Run: func(_ *cobra.Command, args []string) {
			fmt.Printf("args: %#+v\n", args)
		},
	}

	rootCmd := &cobra.Command{Use: "app"}
	rootCmd.AddCommand(cmdPrint)
	rootCmd.Execute()
}
:/tmp/example$ go run main.go print
args: []string{}
:/tmp/example$ go run main.go print foo
args: []string{"foo"}

Regards,
Miguel

Metadata

Metadata

Assignees

No one assigned

    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