query namespace exists with GET Namespace (#236)

More efficient ns switches with kubens by querying only the namespace (instead
of listing all namespaces).

Signed-off-by: Ahmet Alp Balkan <ahmetb@google.com>
This commit is contained in:
Ahmet Alp Balkan 2020-05-31 15:32:44 -07:00 committed by GitHub
parent 0141ee19d2
commit 170233bffd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 29 additions and 16 deletions

View File

@ -54,15 +54,7 @@ func queryNamespaces(kc *kubeconfig.Kubeconfig) ([]string, error) {
return []string{"ns1", "ns2"}, nil return []string{"ns1", "ns2"}, nil
} }
b, err := kc.Bytes() clientset, err := newKubernetesClientSet(kc)
if err != nil {
return nil, errors.Wrap(err, "failed to convert in-memory kubeconfig to yaml")
}
cfg, err := clientcmd.RESTConfigFromKubeConfig(b)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize config")
}
clientset, err := kubernetes.NewForConfig(cfg)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "failed to initialize k8s REST client") return nil, errors.Wrap(err, "failed to initialize k8s REST client")
} }
@ -87,3 +79,15 @@ func queryNamespaces(kc *kubeconfig.Kubeconfig) ([]string, error) {
} }
return out, nil return out, nil
} }
func newKubernetesClientSet(kc *kubeconfig.Kubeconfig) (*kubernetes.Clientset, error) {
b, err := kc.Bytes()
if err != nil {
return nil, errors.Wrap(err, "failed to convert in-memory kubeconfig to yaml")
}
cfg, err := clientcmd.RESTConfigFromKubeConfig(b)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize config")
}
return kubernetes.NewForConfig(cfg)
}

View File

@ -2,8 +2,11 @@ package main
import ( import (
"io" "io"
"os"
"github.com/pkg/errors" "github.com/pkg/errors"
errors2 "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/ahmetb/kubectx/internal/cmdutil" "github.com/ahmetb/kubectx/internal/cmdutil"
"github.com/ahmetb/kubectx/internal/kubeconfig" "github.com/ahmetb/kubectx/internal/kubeconfig"
@ -75,14 +78,20 @@ func switchNamespace(kc *kubeconfig.Kubeconfig, ns string) (string, error) {
} }
func namespaceExists(kc *kubeconfig.Kubeconfig, ns string) (bool, error) { func namespaceExists(kc *kubeconfig.Kubeconfig, ns string) (bool, error) {
nses, err := queryNamespaces(kc) // for tests
if os.Getenv("_MOCK_NAMESPACES") != "" {
return ns == "ns1" || ns == "ns2", nil
}
clientset, err := newKubernetesClientSet(kc)
if err != nil { if err != nil {
return false, err return false, errors.Wrap(err, "failed to initialize k8s REST client")
} }
for _, v := range nses {
if v == ns { namespace, err := clientset.CoreV1().Namespaces().Get(ns, metav1.GetOptions{})
return true, nil if errors2.IsNotFound(err) {
} return false, nil
} }
return false, nil return namespace != nil, errors.Wrapf(err, "failed to query "+
"namespace %q from k8s API", ns)
} }