// toRawKubePersistentConfigLoader binds config flag values to config overrides
// Returns a persistent clientConfig for propagation.
764693
func (f *ConfigFlags) toRawKubePersistentConfigLoader() clientcmd.ClientConfig {
	f.lock.Lock()
	defer f.lock.Unlock()

	if f.clientConfig == nil {
		f.clientConfig = f.toRawKubeConfigLoader()
	}

	return f.clientConfig
}
1141260
func LoadKubeConfig() (*clientcmdapi.Config, error) {
	filename, err := utils.EnsureLocalPath(
		kubeconfigFromEnv(),
		teleport.KubeConfigDir,
		teleport.KubeConfigFile)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	config, err := clientcmd.LoadFromFile(filename)
	if err != nil && !os.IsNotExist(err) {
		return nil, trace.ConvertSystemError(err)
	}
	if config == nil {
		config = clientcmdapi.NewConfig()
	}

	return config, nil
}
629022
func (st *State) ResourcesPersistence() (ResourcesPersistence, error) {
	base := st.newPersistence()
	persist := NewResourcePersistence(base)
	return persist, nil
}
837128
func (dialer *PredicateDialer) ClientConfig() (comm.ClientConfig, error) {
	val := dialer.Config.Load()
	if val == nil {
		return comm.ClientConfig{}, errors.New("client config not initialized")
	}
	cc, isClientConfig := val.(comm.ClientConfig)
	if !isClientConfig {
		err := errors.Errorf("value stored is %v, not comm.ClientConfig",
			reflect.TypeOf(val))
		return comm.ClientConfig{}, err
	}
	if cc.SecOpts == nil {
		return comm.ClientConfig{}, errors.New("SecOpts is nil")
	}
	// Copy by value the secure options
	secOpts := *cc.SecOpts
	return comm.ClientConfig{
		AsyncConnect: cc.AsyncConnect,
		Timeout:      cc.Timeout,
		SecOpts:      &secOpts,
		KaOpts:       cc.KaOpts,
	}, nil
}
837100
func (s *StoreToPVFetcher) GetPersistentVolumeInfo(id string) (*api.PersistentVolume, error) {
	o, exists, err := s.Get(&api.PersistentVolume{ObjectMeta: api.ObjectMeta{Name: id}})

	if err != nil {
		return nil, fmt.Errorf("error retrieving PersistentVolume '%v' from cache: %v", id, err)
	}

	if !exists {
		return nil, fmt.Errorf("PersistentVolume '%v' is not in cache", id)
	}

	return o.(*api.PersistentVolume), nil
}
9369
func (b *KubectlBuilder) findKubeconfigUser() (*fi.User, *fi.Group, error) {
	var users []string
	switch b.Distribution {
	case distros.DistributionJessie, distros.DistributionDebian9:
		users = []string{"admin", "root"}
	case distros.DistributionCentos7:
		users = []string{"centos"}
	default:
		glog.Warningf("Unknown distro; won't write kubeconfig to homedir %s", b.Distribution)
		return nil, nil, nil
	}

	for _, s := range users {
		user, err := fi.LookupUser(s)
		if err != nil {
			glog.Warningf("error looking up user %q: %v", s, err)
			continue
		}
		if user == nil {
			continue
		}
		group, err := fi.LookupGroupById(user.Gid)
		if err != nil {
			glog.Warningf("unable to find group %d for user %q", user.Gid, s)
			continue
		}
		if group == nil {
			continue
		}
		return user, group, nil
	}

	return nil, nil, nil
}
686764
func (pm *VolumePluginMgr) FindPersistentPluginBySpec(spec *Spec) (PersistentVolumePlugin, error) {
	volumePlugin, err := pm.FindPluginBySpec(spec)
	if err != nil {
		return nil, fmt.Errorf("Could not find volume plugin for spec: %#v", spec)
	}
	if persistentVolumePlugin, ok := volumePlugin.(PersistentVolumePlugin); ok {
		return persistentVolumePlugin, nil
	}
	return nil, fmt.Errorf("no persistent volume plugin matched")
}
656448
func CreateKubeClientFromConfig(conf *KubeConfig) (*kubernetes.Clientset, error) {
	rcConf := new(rest.Config)
	if len(conf.Clusters) < 1 {
		return nil, errNoClustersInConfig
	}
	cluster := conf.Clusters[0].Cluster
	if len(conf.AuthInfos) < 1 {
		return nil, errNoAuthInfosInConfig
	}
	authInfo := conf.AuthInfos[0].AuthInfo

	rcConf.Host = cluster.Server
	rcConf.Username = authInfo.Username
	rcConf.Password = authInfo.Password
	rcConf.TLSClientConfig.CertData = []byte(authInfo.ClientCertificateData)
	rcConf.TLSClientConfig.KeyData = []byte(authInfo.ClientKeyData)
	rcConf.TLSClientConfig.CAData = []byte(cluster.CertificateAuthorityData)
	rcConf.BearerToken = authInfo.Token
	rcConf.UserAgent = "k8s-claimer"
	rcConf.Insecure = cluster.InsecureSkipTLSVerify

	return kubernetes.NewForConfig(rcConf)
}
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)
}
872251
func (c *simpleCollectionStore) RetrieveCollectionPersistenceConfigs(cc common.CollectionCriteria) (CollectionPersistenceConfigs, error) {
	staticCollectionConfig, err := c.retrieveCollectionConfig(cc, nil)
	if err != nil {
		return nil, err
	}
	return &SimpleCollectionPersistenceConfigs{staticCollectionConfig.BlockToLive}, nil
}
1243454
func GetKubernetesClient() (kubernetes.Interface, error) {
	config, err := rest.InClusterConfig()
	if err != nil {
		return nil, err
	}

	return kubernetes.NewForConfig(config)
}
116900
func GetFromKubeProxyConfigMap(client clientset.Interface, version *version.Version) (runtime.Object, error) {

	// Read the ConfigMap from the cluster
	kubeproxyCfg, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(kubeadmconstants.KubeProxyConfigMap, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}

	kubeproxyConfigData, ok := kubeproxyCfg.Data[kubeadmconstants.KubeProxyConfigMapKey]
	if !ok {
		return nil, errors.Errorf("unexpected error when reading %s ConfigMap: %s key value pair missing",
			kubeadmconstants.KubeProxyConfigMap, kubeadmconstants.KubeProxyConfigMapKey)
	}

	// Decodes the Config map dat into the internal component config
	obj := &kubeproxyconfig.KubeProxyConfiguration{}
	err = unmarshalObject(obj, []byte(kubeproxyConfigData))
	if err != nil {
		return nil, err
	}

	return obj, nil
}
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)
}
560877
func (c CreateLeaseResp) KubeConfig() (*k8s.KubeConfig, error) {
	configBytes, err := c.KubeConfigBytes()
	if err != nil {
		return nil, err
	}
	kubeConfig := &k8s.KubeConfig{}
	if err := json.Unmarshal(configBytes, kubeConfig); err != nil {
		return nil, err
	}
	return kubeConfig, nil
}
191606
func (a *Armor) GetConfigForClient(clientHelloInfo *tls.ClientHelloInfo) (*tls.Config, error) {
	// Get the host from the hello info
	host := a.Hosts[clientHelloInfo.ServerName]
	// If the host or the clientCAs are not configured the function
	// returns the default TLS configuration
	if host == nil || len(host.ClientCAs) == 0 {
		return nil, nil
	}

	// Use existing host config if exist
	if host.TLSConfig != nil {
		return host.TLSConfig, nil
	}

	// Build and save the host config
	host.TLSConfig = a.buildTLSConfig(clientHelloInfo, host)

	return host.TLSConfig, nil
}
1230716
func getNodeNameFromKubeletConfig(kubeconfigDir string) (string, error) {
	// loads the kubelet.conf file
	fileName := filepath.Join(kubeconfigDir, constants.KubeletKubeConfigFileName)
	config, err := clientcmd.LoadFromFile(fileName)
	if err != nil {
		return "", err
	}

	// gets the info about the current user
	authInfo := config.AuthInfos[config.Contexts[config.CurrentContext].AuthInfo]

	// gets the X509 certificate with current user credentials
	var certs []*x509.Certificate
	if len(authInfo.ClientCertificateData) > 0 {
		// if the config file uses an embedded x509 certificate (e.g. kubelet.conf created by kubeadm), parse it
		if certs, err = certutil.ParseCertsPEM(authInfo.ClientCertificateData); err != nil {
			return "", err
		}
	} else if len(authInfo.ClientCertificate) > 0 {
		// if the config file links an external x509 certificate (e.g. kubelet.conf created by TLS bootstrap), load it
		if certs, err = certutil.CertsFromFile(authInfo.ClientCertificate); err != nil {
			return "", err
		}
	} else {
		return "", errors.New("invalid kubelet.conf. X509 certificate expected")
	}

	// We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
	// TODO: Support multiple certs here in order to be able to rotate certs
	cert := certs[0]

	// gets the node name from the certificate common name
	return strings.TrimPrefix(cert.Subject.CommonName, constants.NodesUserPrefix), nil
}
285259
func GetFromKubeletConfigMap(client clientset.Interface, version *version.Version) (runtime.Object, error) {

	// Read the ConfigMap from the cluster based on what version the kubelet is
	configMapName := kubeadmconstants.GetKubeletConfigMapName(version)
	kubeletCfg, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(configMapName, metav1.GetOptions{})
	if err != nil {
		return nil, err
	}

	kubeletConfigData, ok := kubeletCfg.Data[kubeadmconstants.KubeletBaseConfigurationConfigMapKey]
	if !ok {
		return nil, errors.Errorf("unexpected error when reading %s ConfigMap: %s key value pair missing",
			configMapName, kubeadmconstants.KubeletBaseConfigurationConfigMapKey)
	}

	// Decodes the kubeletConfigData into the internal component config
	obj := &kubeletconfig.KubeletConfiguration{}
	err = unmarshalObject(obj, []byte(kubeletConfigData))
	if err != nil {
		return nil, err
	}

	return obj, nil
}