Пример #1
0
func (k8scc *K8sClientConfig) UnversionedClient() *unversioned.Client {
	config := clientcmdapi.NewConfig()
	config.Clusters[k8scc.ClusterID] = &clientcmdapi.Cluster{
		InsecureSkipTLSVerify:    k8scc.InsecureSkipTLSVerify,
		Server:                   k8scc.Server,
		CertificateAuthority:     k8scc.CertificateAuthority,
		CertificateAuthorityData: k8scc.CertificateAuthorityData,
	}
	config.AuthInfos[k8scc.ClusterID] = &clientcmdapi.AuthInfo{
		ClientCertificate:     k8scc.ClientCertificate,
		ClientKey:             k8scc.ClientKey,
		ClientCertificateData: k8scc.ClientCertificateData,
		ClientKeyData:         k8scc.ClientKeyData,
	}
	config.Contexts[k8scc.ClusterID] = &clientcmdapi.Context{
		Cluster:  k8scc.ClusterID,
		AuthInfo: k8scc.ClusterID,
	}
	config.CurrentContext = k8scc.ClusterID

	clientBuilder := clientcmd.NewNonInteractiveClientConfig(*config, k8scc.ClusterID, &clientcmd.ConfigOverrides{})

	clientConfig, err := clientBuilder.ClientConfig()
	if err != nil {
		log.Fatalf("Unexpected error: %v", err)
	}
	client, err := unversioned.New(clientConfig)
	if err != nil {
		log.Fatalf("Unexpected error: %v", err)
	}

	return client
}
Пример #2
0
func TestKubectlValidation(t *testing.T) {
	testCases := []struct {
		data string
		err  bool
	}{
		{`{"apiVersion": "v1", "kind": "thisObjectShouldNotExistInAnyGroup"}`, true},
		{`{"apiVersion": "invalidVersion", "kind": "Pod"}`, true},
		{`{"apiVersion": "v1", "kind": "Pod"}`, false},

		// The following test the experimental api.
		// TODO: Replace with something more robust. These may move.
		{`{"apiVersion": "extensions/v1beta1", "kind": "Ingress"}`, false},
		{`{"apiVersion": "extensions/v1beta1", "kind": "Job"}`, false},
		{`{"apiVersion": "vNotAVersion", "kind": "Job"}`, true},
	}
	components := framework.NewMasterComponents(&framework.Config{})
	defer components.Stop(true, true)
	ctx := clientcmdapi.NewContext()
	cfg := clientcmdapi.NewConfig()
	// Enable swagger api on master.
	components.KubeMaster.InstallSwaggerAPI()
	cluster := clientcmdapi.NewCluster()

	cluster.Server = components.ApiServer.URL
	cluster.InsecureSkipTLSVerify = true
	cfg.Contexts = map[string]*clientcmdapi.Context{"test": ctx}
	cfg.CurrentContext = "test"
	overrides := clientcmd.ConfigOverrides{
		ClusterInfo: *cluster,
	}
	cmdConfig := clientcmd.NewNonInteractiveClientConfig(*cfg, "test", &overrides, nil)
	factory := util.NewFactory(cmdConfig)
	schema, err := factory.Validator(true, "")
	if err != nil {
		t.Errorf("failed to get validator: %v", err)
		return
	}
	for i, test := range testCases {
		err := schema.ValidateBytes([]byte(test.data))
		if err == nil {
			if test.err {
				t.Errorf("case %d: expected error", i)
			}
		} else {
			if !test.err {
				t.Errorf("case %d: unexpected error: %v", i, err)
			}
		}
	}
}
Пример #3
0
func loadRESTClientConfig(kubeconfig string) (*restclient.Config, error) {
	// Load structured kubeconfig data from the given path.
	loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
	loadedConfig, err := loader.Load()
	if err != nil {
		return nil, err
	}
	// Flatten the loaded data to a particular restclient.Config based on the current context.
	return clientcmd.NewNonInteractiveClientConfig(
		*loadedConfig,
		loadedConfig.CurrentContext,
		&clientcmd.ConfigOverrides{},
		loader,
	).ClientConfig()
}
Пример #4
0
func createClientsetForCluster(c federationapi.Cluster, i int, userAgentName string) *kubeclientset.Clientset {
	kubecfg, err := clientcmd.LoadFromFile(framework.TestContext.KubeConfig)
	framework.ExpectNoError(err, "error loading KubeConfig: %v", err)

	cfgOverride := &clientcmd.ConfigOverrides{
		ClusterInfo: clientcmdapi.Cluster{
			Server: c.Spec.ServerAddressByClientCIDRs[0].ServerAddress,
		},
	}
	ccfg := clientcmd.NewNonInteractiveClientConfig(*kubecfg, c.Name, cfgOverride, clientcmd.NewDefaultClientConfigLoadingRules())
	cfg, err := ccfg.ClientConfig()
	framework.ExpectNoError(err, "Error creating client config in cluster #%d (%q)", i, c.Name)

	cfg.QPS = KubeAPIQPS
	cfg.Burst = KubeAPIBurst
	return kubeclientset.NewForConfigOrDie(restclient.AddUserAgent(cfg, userAgentName))
}
Пример #5
0
// k8s.io/kubernetes/pkg/client/unversioned/clientcmd/loader.go
func directKClientConfig(kubeconfigPath string, context, server string) clientcmd.ClientConfig {
	conf, err := clientcmd.LoadFromFile(kubeconfigPath)
	//conf, err := clientcmd.NewDefaultPathOptions().GetStartingConfig()
	if err != nil {
		glog.Errorf("client not configured: %v\n", err)
		return nil
	}
	glog.Infof("kube client configured: %+v\n", conf)

	var clientConfig clientcmd.ClientConfig
	overrides := &clientcmd.ConfigOverrides{}
	if server != "" {
		overrides.ClusterInfo = kclientcmdapi.Cluster{Server: server}
	}
	if context != "" {
		overrides.CurrentContext = context
	}
	clientConfig = clientcmd.NewNonInteractiveClientConfig(*conf,
		context, overrides)
	return clientConfig
}
Пример #6
0
// NewKubeClusterFromContext creates a KubeCluster using a Kubernetes client with the configuration of the given context.
// If the context name is empty, the default context will be used.
func NewKubeClusterFromContext(name string) (*KubeCluster, error) {
	rulesConfig, err := defaultLoadingRules().Load()
	if err != nil {
		return nil, fmt.Errorf("could not load rules: %v", err)
	}

	clientConfig := clientcmd.NewNonInteractiveClientConfig(*rulesConfig, name, &clientcmd.ConfigOverrides{})

	rawConfig, err := clientConfig.RawConfig()
	if err != nil || rawConfig.Contexts == nil {
		return nil, fmt.Errorf("could not access kubectl config: %v", err)
	}

	if name == DefaultContext {
		name = rawConfig.CurrentContext
	}

	if rawConfig.Contexts[name] == nil {
		return nil, fmt.Errorf("context '%s' does not exist", name)
	}

	restClientConfig, err := clientConfig.ClientConfig()
	if err != nil {
		return nil, fmt.Errorf("could not get ClientConfig: %v", err)
	}

	client, err := kubecli.New(restClientConfig)
	if err != nil {
		return nil, fmt.Errorf("could not create Kubernetes client: %v", err)
	}

	return &KubeCluster{
		Client:    client,
		context:   name,
		localkube: name == "localkube",
	}, nil
}
Пример #7
0
			clusters = map[string]*cluster{}
			primaryClusterName = clusterList.Items[0].Name
			By(fmt.Sprintf("Labeling %q as the first cluster", primaryClusterName))
			for i, c := range clusterList.Items {
				framework.Logf("Creating a clientset for the cluster %s", c.Name)

				Expect(framework.TestContext.KubeConfig).ToNot(Equal(""), "KubeConfig must be specified to load clusters' client config")
				kubecfg, err := clientcmd.LoadFromFile(framework.TestContext.KubeConfig)
				framework.ExpectNoError(err, "error loading KubeConfig: %v", err)

				cfgOverride := &clientcmd.ConfigOverrides{
					ClusterInfo: clientcmdapi.Cluster{
						Server: c.Spec.ServerAddressByClientCIDRs[0].ServerAddress,
					},
				}
				ccfg := clientcmd.NewNonInteractiveClientConfig(*kubecfg, c.Name, cfgOverride, clientcmd.NewDefaultClientConfigLoadingRules())
				cfg, err := ccfg.ClientConfig()
				framework.ExpectNoError(err, "Error creating client config in cluster #%d (%q)", i, c.Name)

				cfg.QPS = KubeAPIQPS
				cfg.Burst = KubeAPIBurst
				clset := release_1_3.NewForConfigOrDie(restclient.AddUserAgent(cfg, UserAgentName))
				clusters[c.Name] = &cluster{c.Name, clset, false, nil}
			}

			for name, c := range clusters {
				// The e2e Framework created the required namespace in one of the clusters, but we need to create it in all the others, if it doesn't yet exist.
				if _, err := c.Clientset.Core().Namespaces().Get(f.Namespace.Name); errors.IsNotFound(err) {
					ns := &v1.Namespace{
						ObjectMeta: v1.ObjectMeta{
							Name: f.Namespace.Name,
Пример #8
0
func GetKubeClientConfig(uri *url.URL) (*kube_client.Config, error) {
	var (
		kubeConfig *kube_client.Config
		err        error
	)

	opts := uri.Query()
	configOverrides, err := getConfigOverrides(uri)
	if err != nil {
		return nil, err
	}

	inClusterConfig := defaultInClusterConfig
	if len(opts["inClusterConfig"]) > 0 {
		inClusterConfig, err = strconv.ParseBool(opts["inClusterConfig"][0])
		if err != nil {
			return nil, err
		}
	}

	if inClusterConfig {
		kubeConfig, err = kube_client.InClusterConfig()
		if err != nil {
			return nil, err
		}

		if configOverrides.ClusterInfo.Server != "" {
			kubeConfig.Host = configOverrides.ClusterInfo.Server
		}
		kubeConfig.GroupVersion = &unversioned.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
		kubeConfig.Insecure = configOverrides.ClusterInfo.InsecureSkipTLSVerify
		if configOverrides.ClusterInfo.InsecureSkipTLSVerify {
			kubeConfig.TLSClientConfig.CAFile = ""
		}
	} else {
		authFile := ""
		if len(opts["auth"]) > 0 {
			authFile = opts["auth"][0]
		}

		if authFile != "" {
			// Load structured kubeconfig data from the given path.
			loader := &kubeClientCmd.ClientConfigLoadingRules{ExplicitPath: authFile}
			loadedConfig, err := loader.Load()
			if err != nil {
				return nil, err
			}

			// Flatten the loaded data to a particular restclient.Config based on the current context.
			if kubeConfig, err = kubeClientCmd.NewNonInteractiveClientConfig(
				*loadedConfig,
				loadedConfig.CurrentContext,
				&kubeClientCmd.ConfigOverrides{},
				loader).ClientConfig(); err != nil {
				return nil, err
			}
		} else {
			kubeConfig = &kube_client.Config{
				Host:     configOverrides.ClusterInfo.Server,
				Insecure: configOverrides.ClusterInfo.InsecureSkipTLSVerify,
			}
			kubeConfig.GroupVersion = &unversioned.GroupVersion{Version: configOverrides.ClusterInfo.APIVersion}
		}
	}
	if len(kubeConfig.Host) == 0 {
		return nil, fmt.Errorf("invalid kubernetes master url specified")
	}

	useServiceAccount := defaultUseServiceAccount
	if len(opts["useServiceAccount"]) >= 1 {
		useServiceAccount, err = strconv.ParseBool(opts["useServiceAccount"][0])
		if err != nil {
			return nil, err
		}
	}

	if useServiceAccount {
		// If a readable service account token exists, then use it
		if contents, err := ioutil.ReadFile(defaultServiceAccountFile); err == nil {
			kubeConfig.BearerToken = string(contents)
		}
	}

	kubeConfig.ContentType = "application/vnd.kubernetes.protobuf"

	return kubeConfig, nil
}