// FromKubeConfig creates a Kubernetes endpoint from a Kubeconfig file
765239
func FromKubeConfig(kubeconfig, kubeContext, namespaceOverride string) (Endpoint, error) {
	cfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
		&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig},
		&clientcmd.ConfigOverrides{CurrentContext: kubeContext, Context: clientcmdapi.Context{Namespace: namespaceOverride}})
	ns, _, err := cfg.Namespace()
	if err != nil {
		return Endpoint{}, err
	}
	clientcfg, err := cfg.ClientConfig()
	if err != nil {
		return Endpoint{}, err
	}
	var ca, key, cert []byte
	if ca, err = readFileOrDefault(clientcfg.CAFile, clientcfg.CAData); err != nil {
		return Endpoint{}, err
	}
	if key, err = readFileOrDefault(clientcfg.KeyFile, clientcfg.KeyData); err != nil {
		return Endpoint{}, err
	}
	if cert, err = readFileOrDefault(clientcfg.CertFile, clientcfg.CertData); err != nil {
		return Endpoint{}, err
	}
	var tlsData *context.TLSData
	if ca != nil || cert != nil || key != nil {
		tlsData = &context.TLSData{
			CA:   ca,
			Cert: cert,
			Key:  key,
		}
	}
	return Endpoint{
		EndpointMeta: EndpointMeta{
			EndpointMetaBase: context.EndpointMetaBase{
				Host:          clientcfg.Host,
				SkipTLSVerify: clientcfg.Insecure,
			},
			DefaultNamespace: ns,
			AuthProvider:     clientcfg.AuthProvider,
			Exec:             clientcfg.ExecProvider,
		},
		TLSData: tlsData,
	}, nil
}
612031
func WriteKubeConfig(restConfig *rest.Config, namespace, filename string) error {
	kubeConfig := NewKubeConfig(restConfig, namespace)
	return clientcmd.WriteToFile(*kubeConfig, filename)
}
1043041
func (c *NodeupModelContext) KubeletBootstrapKubeconfig() string {
	path := c.Cluster.Spec.Kubelet.BootstrapKubeconfig

	if c.IsMaster {
		if c.Cluster.Spec.MasterKubelet != nil && c.Cluster.Spec.MasterKubelet.BootstrapKubeconfig != "" {
			path = c.Cluster.Spec.MasterKubelet.BootstrapKubeconfig
		}
	}

	if path != "" {
		return path
	}

	return "/var/lib/kubelet/bootstrap-kubeconfig"
}
1256516
func FromConfig(c context.Context, cfg []*config.Settings_SourceAcls) (*ACLs, error) {
	ctx := validation.Context{Context: c}
	ACLs := &ACLs{}
	ACLs.load(&ctx, cfg)
	if err := ctx.Finalize(); err != nil {
		return nil, err
	}
	return ACLs, nil
}
1040767
func makeKubeconfig(ctx context.Context, config *Config, token string) ([]byte, error) {
	// @step: load the certificate authority
	content, err := ioutil.ReadFile(config.TLSClientCAPath)
	if err != nil {
		return []byte{}, err
	}

	// @step: we need to write out the kubeconfig
	name := "bootstrap-context"
	clusterName := "cluster"

	cfg := &v1.Config{
		APIVersion: "v1",
		Kind:       "Config",
		AuthInfos: []v1.NamedAuthInfo{
			{
				Name: name,
				AuthInfo: v1.AuthInfo{
					Token: token,
				},
			},
		},
		Clusters: []v1.NamedCluster{
			{
				Name: clusterName,
				Cluster: v1.Cluster{
					Server:                   config.KubeAPI,
					CertificateAuthorityData: content,
				},
			},
		},
		Contexts: []v1.NamedContext{
			{
				Name: name,
				Context: v1.Context{
					Cluster:  clusterName,
					AuthInfo: name,
				},
			},
		},
		CurrentContext: name,
	}

	return json.MarshalIndent(cfg, "", "  ")
}
493779
func Convert_v1alpha1_KubeProxyConfig_To_kops_KubeProxyConfig(in *KubeProxyConfig, out *kops.KubeProxyConfig, s conversion.Scope) error {
	return autoConvert_v1alpha1_KubeProxyConfig_To_kops_KubeProxyConfig(in, out, s)
}
7607
func FromEnv() (*Me, error) {
	host := os.Getenv("KUBERNETES_SERVICE_HOST")
	port := os.Getenv("KUBERNETES_SERVICE_PORT")
	name := NameFromEnv()

	// FIXME: Better way? Probably scanning secrets for
	// an SSL cert would help?
	proto := "https"

	url := proto + "://" + host + ":" + port

	me := &Me{
		ApiServer: url,
		Name:      name,
		Namespace: NamespaceFromEnv(),
	}

	config, err := rest.InClusterConfig()
	if err != nil {
		return me, err
	}
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		return me, err
	}
	me.c = clientset

	if err := me.init(); err != nil {
		return me, err
	}

	return me, nil
}
1347807
func validateKubeConfig(config *clientcmdapi.Config) error {
	if len(config.Clusters) < 1 {
		return errors.New("the provided cluster-info kubeconfig file must have at least one Cluster defined")
	}
	defaultCluster := kubeconfigutil.GetClusterFromKubeConfig(config)
	if defaultCluster == nil {
		return errors.New("the provided cluster-info kubeconfig file must have an unnamed Cluster or a CurrentContext that specifies a non-nil Cluster")
	}
	return clientcmd.Validate(*config)
}
616060
func (d *initData) KubeConfigPath() string {
	if d.dryRun {
		d.kubeconfigPath = filepath.Join(d.dryRunDir, kubeadmconstants.AdminKubeConfigFileName)
	}
	return d.kubeconfigPath
}
265724
func NewKubeClient(kubeconfig string) (*kubernetes.Clientset, error) {
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		return nil, fmt.Errorf("Error Building config from Kubeconfig: %v", err)
	}

	return kubernetes.NewForConfig(config)
}
424261
func kubeconfigFromEnv() string {
	kubeconfig := os.Getenv(teleport.EnvKubeConfig)

	// The KUBECONFIG environment variable is a list. On Windows it's
	// semicolon-delimited. On Linux and macOS it's colon-delimited.
	var parts []string
	switch runtime.GOOS {
	case teleport.WindowsOS:
		parts = strings.Split(kubeconfig, ";")
	default:
		parts = strings.Split(kubeconfig, ":")
	}

	// Default behavior of kubectl is to return the first file from list.
	var configpath string
	if len(parts) > 0 {
		configpath = parts[0]
	}
	log.Debugf("Found kubeconfig in environment at '%v'.", configpath)

	return configpath
}
972608
func (b *KubeconfigBuilder) WriteKubecfg() error {
	config, err := b.configAccess.GetStartingConfig()
	if err != nil {
		return fmt.Errorf("error reading kubeconfig: %v", err)
	}

	if config == nil {
		config = &clientcmdapi.Config{}
	}

	{
		cluster := config.Clusters[b.Context]
		if cluster == nil {
			cluster = clientcmdapi.NewCluster()
		}
		cluster.Server = b.Server

		if b.CACert == nil {
			// For now, we assume that the cluster has a "real" cert issued by a CA
			cluster.InsecureSkipTLSVerify = false
			cluster.CertificateAuthority = ""
			cluster.CertificateAuthorityData = nil
		} else {
			cluster.InsecureSkipTLSVerify = false
			cluster.CertificateAuthority = ""
			cluster.CertificateAuthorityData = b.CACert
		}

		if config.Clusters == nil {
			config.Clusters = make(map[string]*clientcmdapi.Cluster)
		}
		config.Clusters[b.Context] = cluster
	}

	{
		authInfo := config.AuthInfos[b.Context]
		if authInfo == nil {
			authInfo = clientcmdapi.NewAuthInfo()
		}

		if b.KubeBearerToken != "" {
			authInfo.Token = b.KubeBearerToken
		} else if b.KubeUser != "" && b.KubePassword != "" {
			authInfo.Username = b.KubeUser
			authInfo.Password = b.KubePassword
		}

		if b.ClientCert != nil && b.ClientKey != nil {
			authInfo.ClientCertificate = ""
			authInfo.ClientCertificateData = b.ClientCert
			authInfo.ClientKey = ""
			authInfo.ClientKeyData = b.ClientKey
		}

		if config.AuthInfos == nil {
			config.AuthInfos = make(map[string]*clientcmdapi.AuthInfo)
		}
		config.AuthInfos[b.Context] = authInfo
	}

	// If we have a bearer token, also create a credential entry with basic auth
	// so that it is easy to discover the basic auth password for your cluster
	// to use in a web browser.
	if b.KubeUser != "" && b.KubePassword != "" {
		name := b.Context + "-basic-auth"
		authInfo := config.AuthInfos[name]
		if authInfo == nil {
			authInfo = clientcmdapi.NewAuthInfo()
		}

		authInfo.Username = b.KubeUser
		authInfo.Password = b.KubePassword

		if config.AuthInfos == nil {
			config.AuthInfos = make(map[string]*clientcmdapi.AuthInfo)
		}
		config.AuthInfos[name] = authInfo
	}

	{
		context := config.Contexts[b.Context]
		if context == nil {
			context = clientcmdapi.NewContext()
		}

		context.Cluster = b.Context
		context.AuthInfo = b.Context

		if b.Namespace != "" {
			context.Namespace = b.Namespace
		}

		if config.Contexts == nil {
			config.Contexts = make(map[string]*clientcmdapi.Context)
		}
		config.Contexts[b.Context] = context
	}

	config.CurrentContext = b.Context

	if err := clientcmd.ModifyConfig(b.configAccess, *config, true); err != nil {
		return err
	}

	fmt.Printf("kops has set your kubectl context to %s\n", b.Context)
	return nil
}
939745
func NewClusterConfig() *cobra.Command {
	var (
		clientConfig clientcmd.ClientConfig
	)
	var command = &cobra.Command{
		Use:   "kubeconfig CLUSTER_URL OUTPUT_PATH",
		Short: "Generates kubeconfig for the specified cluster",
		Run: func(c *cobra.Command, args []string) {
			if len(args) != 2 {
				c.HelpFunc()(c, args)
				os.Exit(1)
			}
			serverUrl := args[0]
			output := args[1]
			conf, err := clientConfig.ClientConfig()
			errors.CheckError(err)
			namespace, _, err := clientConfig.Namespace()
			errors.CheckError(err)
			kubeclientset, err := kubernetes.NewForConfig(conf)
			errors.CheckError(err)

			cluster, err := db.NewDB(namespace, settings.NewSettingsManager(context.Background(), kubeclientset, namespace), kubeclientset).GetCluster(context.Background(), serverUrl)
			errors.CheckError(err)
			err = kube.WriteKubeConfig(cluster.RESTConfig(), namespace, output)
			errors.CheckError(err)
		},
	}
	clientConfig = cli.AddKubectlFlagsToCmd(command)
	return command
}
1217545
func FromJSONConfig(config jsonconfig.Obj, prefix, serverBaseURL string) (HandlerConfig, error) {
	hc := HandlerConfig{
		Program:       config.RequiredString("program"),
		Prefix:        config.OptionalString("prefix", prefix),
		BackendURL:    config.OptionalString("backendURL", ""),
		Listen:        config.OptionalString("listen", ""),
		APIHost:       config.OptionalString("apiHost", ""),
		ServerListen:  config.OptionalString("serverListen", ""),
		ServerBaseURL: config.OptionalString("serverBaseURL", serverBaseURL),
		AppConfig:     config.OptionalObject("appConfig"),
	}
	if err := config.Validate(); err != nil {
		return HandlerConfig{}, err
	}
	return hc, nil
}
1350622
func DefaultKubeletConfiguration(internalcfg *kubeadmapi.ClusterConfiguration) {
	externalkubeletcfg := &kubeletconfigv1beta1.KubeletConfiguration{}

	// Do a roundtrip to the external version for defaulting
	if internalcfg.ComponentConfigs.Kubelet != nil {
		Scheme.Convert(internalcfg.ComponentConfigs.Kubelet, externalkubeletcfg, nil)
	}

	if externalkubeletcfg.StaticPodPath == "" {
		externalkubeletcfg.StaticPodPath = kubeadmapiv1beta2.DefaultManifestsDir
	}
	if externalkubeletcfg.ClusterDNS == nil {
		dnsIP, err := constants.GetDNSIP(internalcfg.Networking.ServiceSubnet)
		if err != nil {
			externalkubeletcfg.ClusterDNS = []string{kubeadmapiv1beta2.DefaultClusterDNSIP}
		} else {
			externalkubeletcfg.ClusterDNS = []string{dnsIP.String()}
		}
	}
	if externalkubeletcfg.ClusterDomain == "" {
		externalkubeletcfg.ClusterDomain = internalcfg.Networking.DNSDomain
	}

	// Enforce security-related kubelet options

	// Require all clients to the kubelet API to have client certs signed by the cluster CA
	externalkubeletcfg.Authentication.X509.ClientCAFile = filepath.Join(internalcfg.CertificatesDir, constants.CACertName)
	externalkubeletcfg.Authentication.Anonymous.Enabled = utilpointer.BoolPtr(false)

	// On every client request to the kubelet API, execute a webhook (SubjectAccessReview request) to the API server
	// and ask it whether the client is authorized to access the kubelet API
	externalkubeletcfg.Authorization.Mode = kubeletconfigv1beta1.KubeletAuthorizationModeWebhook

	// Let clients using other authentication methods like ServiceAccount tokens also access the kubelet API
	externalkubeletcfg.Authentication.Webhook.Enabled = utilpointer.BoolPtr(true)

	// Disable the readonly port of the kubelet, in order to not expose unnecessary information
	externalkubeletcfg.ReadOnlyPort = 0

	// Enables client certificate rotation for the kubelet
	externalkubeletcfg.RotateCertificates = true

	// Serve a /healthz webserver on localhost:10248 that kubeadm can talk to
	externalkubeletcfg.HealthzBindAddress = "127.0.0.1"
	externalkubeletcfg.HealthzPort = utilpointer.Int32Ptr(constants.KubeletHealthzPort)

	Scheme.Default(externalkubeletcfg)

	if internalcfg.ComponentConfigs.Kubelet == nil {
		internalcfg.ComponentConfigs.Kubelet = &kubeletconfig.KubeletConfiguration{}
	}

	// TODO: Figure out how to handle errors in defaulting code
	// Go back to the internal version
	Scheme.Convert(externalkubeletcfg, internalcfg.ComponentConfigs.Kubelet, nil)
}
109879
func NewKubeClient(config *KubeClientConfig) (KubeClientInterface, error) {
	// Use default implementation if no KubernetesGetter is specified
	if config.KubeRESTAPIGetter == nil {
		config.KubeRESTAPIGetter = &defaultGetter{}
	}
	// Use default implementation if no OpenShiftGetter is specified
	if config.OpenShiftRESTAPIGetter == nil {
		config.OpenShiftRESTAPIGetter = &defaultGetter{}
	}
	kubeAPI, err := config.GetKubeRESTAPI(config)
	if err != nil {
		return nil, err
	}
	osAPI, err := config.GetOpenShiftRESTAPI(config)
	if err != nil {
		return nil, err
	}
	// Use default implementation if no MetricsGetter is specified
	if config.MetricsGetter == nil {
		config.MetricsGetter = &defaultGetter{}
	}

	envMap := config.GetEnvironmentMapping()
	kubeClient := &kubeClient{
		config:           config,
		envMap:           envMap,
		BaseURLProvider:  config,
		KubeRESTAPI:      kubeAPI,
		OpenShiftRESTAPI: osAPI,
		metricsMap:       make(map[string]Metrics),
		rulesMap:         make(map[string]*accessRules),
		MetricsGetter:    config.MetricsGetter,
	}

	return kubeClient, nil
}
47045
func (container *Container) FromDisk() error {
	pth, err := container.ConfigPath()
	if err != nil {
		return err
	}

	jsonSource, err := os.Open(pth)
	if err != nil {
		return err
	}
	defer jsonSource.Close()

	dec := json.NewDecoder(jsonSource)

	// Load container settings
	if err := dec.Decode(container); err != nil {
		return err
	}

	// Ensure the operating system is set if blank. Assume it is the OS of the
	// host OS if not, to ensure containers created before multiple-OS
	// support are migrated
	if container.OS == "" {
		container.OS = runtime.GOOS
	}

	return container.readHostConfig()
}