diff --git a/cmd/plugin/cli/root.go b/cmd/plugin/cli/root.go index 5dc147d..cb152de 100644 --- a/cmd/plugin/cli/root.go +++ b/cmd/plugin/cli/root.go @@ -18,6 +18,7 @@ import ( var ( KubernetesConfigFlags *genericclioptions.ConfigFlags + allNamespacesFlag bool ) func RootCmd() *cobra.Command { @@ -43,7 +44,7 @@ $ kubectl pod-lens prometheus-prometheus-operator-prometheus-0 argsChannel := make(chan string, 1) argsChannel <- podName - if err := plugin.RunPlugin(KubernetesConfigFlags, argsChannel); err != nil { + if err := plugin.RunPlugin(KubernetesConfigFlags, argsChannel, allNamespacesFlag); err != nil { return errors.Cause(err) } @@ -55,6 +56,7 @@ $ kubectl pod-lens prometheus-prometheus-operator-prometheus-0 KubernetesConfigFlags = genericclioptions.NewConfigFlags(false) KubernetesConfigFlags.AddFlags(cmd.Flags()) + cmd.Flags().BoolVarP(&allNamespacesFlag, "all-namespaces", "A", false, "query all objects in all API groups, both namespaced and non-namespaced") klog.InitFlags(nil) _ = cmd.Flags().MarkHidden("as-group") diff --git a/pkg/plugin/plugin.go b/pkg/plugin/plugin.go index 0f4ea10..096944c 100644 --- a/pkg/plugin/plugin.go +++ b/pkg/plugin/plugin.go @@ -68,7 +68,7 @@ func NewSnifferPlugin(configFlags *genericclioptions.ConfigFlags) (*SnifferPlugi }, nil } -func (sf *SnifferPlugin) findPodByName(name string, namespace string) error { +func (sf *SnifferPlugin) findPodByName(name, namespace string) error { pods, err := sf.Clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{}) if err != nil || len(pods.Items) == 0 { return errors.New("Failed to get pod: [" + @@ -556,15 +556,19 @@ func (sf *SnifferPlugin) printResource() error { return nil } -func RunPlugin(configFlags *genericclioptions.ConfigFlags, outputCh chan string) error { +func RunPlugin(configFlags *genericclioptions.ConfigFlags, outputCh chan string, allNamespacesFlag bool) error { sf, err := NewSnifferPlugin(configFlags) if err != nil { return err } podName := <-outputCh + var namespace string + if !allNamespacesFlag { + namespace = getNamespace(configFlags) + } - if err := sf.findPodByName(podName, *configFlags.Namespace); err != nil { + if err := sf.findPodByName(podName, namespace); err != nil { return err } @@ -626,3 +630,15 @@ func RunPlugin(configFlags *genericclioptions.ConfigFlags, outputCh chan string) return nil } + +func getNamespace(configFlags *genericclioptions.ConfigFlags) string { + if v := *configFlags.Namespace; v != "" { + return v + } + clientConfig := configFlags.ToRawKubeConfigLoader() + defaultNamespace, _, err := clientConfig.Namespace() + if err != nil { + defaultNamespace = "default" + } + return defaultNamespace +}