// EnableDynamicConfigForNode updates the Node's ConfigSource to enable Dynamic Kubelet Configuration, depending on what version the kubelet is
// Used at "kubeadm init", "kubeadm join" and "kubeadm upgrade" time
165170
func EnableDynamicConfigForNode(client clientset.Interface, nodeName string, kubeletVersion *version.Version) error {

	configMapName := kubeadmconstants.GetKubeletConfigMapName(kubeletVersion)
	fmt.Printf("[kubelet] Enabling Dynamic Kubelet Config for Node %q; config sourced from ConfigMap %q in namespace %s\n",
		nodeName, configMapName, metav1.NamespaceSystem)
	fmt.Println("[kubelet] WARNING: The Dynamic Kubelet Config feature is beta, but off by default. It hasn't been well-tested yet at this stage, use with caution.")

	_, err := client.CoreV1().ConfigMaps(metav1.NamespaceSystem).Get(configMapName, metav1.GetOptions{})
	if err != nil {
		return errors.Wrap(err, "couldn't get the kubelet configuration ConfigMap")
	}

	// Loop on every falsy return. Return with an error if raised. Exit successfully if true is returned.
	return apiclient.PatchNode(client, nodeName, func(n *v1.Node) {
		patchNodeForDynamicConfig(n, configMapName)
	})
}
323026
func GetDynamicPluginProber(config persistentvolumeconfig.VolumeConfiguration) volume.DynamicPluginProber {
	return flexvolume.GetDynamicPluginProber(config.FlexVolumePluginDir, exec.New() /*exec.Interface*/)
}
921046
func SetNodeRegistrationDynamicDefaults(cfg *kubeadmapi.NodeRegistrationOptions, ControlPlaneTaint bool) error {
	var err error
	cfg.Name, err = nodeutil.GetHostname(cfg.Name)
	if err != nil {
		return err
	}

	// Only if the slice is nil, we should append the control-plane taint. This allows the user to specify an empty slice for no default control-plane taint
	if ControlPlaneTaint && cfg.Taints == nil {
		cfg.Taints = []v1.Taint{kubeadmconstants.ControlPlaneTaint}
	}

	if cfg.CRISocket == "" {
		cfg.CRISocket, err = kubeadmruntime.DetectCRISocket()
		if err != nil {
			return err
		}
		klog.V(1).Infof("detected and using CRI socket: %s", cfg.CRISocket)
	}

	return nil
}
577636
func (cc *Controller) loadConfig(source checkpoint.RemoteConfigSource) (*kubeletconfig.KubeletConfiguration, string, error) {
	// load KubeletConfiguration from checkpoint
	kc, err := cc.checkpointStore.Load(source)
	if err != nil {
		return nil, status.LoadError, err
	}
	// apply any required transformations to the KubeletConfiguration
	if cc.transform != nil {
		if err := cc.transform(kc); err != nil {
			return nil, status.InternalError, err
		}
	}
	// validate the result
	if err := validation.ValidateKubeletConfiguration(kc); err != nil {
		return nil, status.ValidateError, err
	}
	return kc, "", nil
}
564582
func NodeEnabled(s *Selector) {
	WaitFunc(s.waitReady(func(ctx context.Context, n *cdp.Node) error {
		n.RLock()
		defer n.RUnlock()

		for i := 0; i < len(n.Attributes); i += 2 {
			if n.Attributes[i] == "disabled" {
				return ErrDisabled
			}
		}

		return nil
	}))(s)
}
737568
func (s *LoadBalancerService) GetLoadBalancerByName(name string, opts ...OptionFunc) (*LoadBalancer, int, error) {
	id, count, err := s.GetLoadBalancerID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetLoadBalancerByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
577751
func newDynamicTimeout(timeout, minimum time.Duration) *dynamicTimeout {
	return &dynamicTimeout{timeout: int64(timeout), minimum: int64(minimum)}
}
1290783
func (c *ConfigLocal) EnableDiskLimiter(configRoot string) error {
	if c.diskLimiter != nil {
		return errors.New("c.diskLimiter is already non-nil")
	}

	params := makeDefaultBackpressureDiskLimiterParams(
		configRoot, c.getQuotaUsage, c.diskBlockCacheFraction, c.syncBlockCacheFraction)
	log := c.MakeLogger("")
	log.Debug("Setting disk storage byte limit to %d and file limit to %d",
		params.byteLimit, params.fileLimit)
	os.MkdirAll(configRoot, 0700)

	diskLimiter, err := newBackpressureDiskLimiter(log, params)
	if err != nil {
		return err
	}
	c.diskLimiter = diskLimiter
	return nil
}
1341091
func (r *FSRepo) setConfigUnsynced(updated *config.Config) error {
	configFilename, err := config.Filename(r.path)
	if err != nil {
		return err
	}
	// to avoid clobbering user-provided keys, must read the config from disk
	// as a map, write the updated struct values to the map and write the map
	// to disk.
	var mapconf map[string]interface{}
	if err := serialize.ReadConfigFile(configFilename, &mapconf); err != nil {
		return err
	}
	m, err := config.ToMap(updated)
	if err != nil {
		return err
	}
	for k, v := range m {
		mapconf[k] = v
	}
	if err := serialize.WriteConfigFile(configFilename, mapconf); err != nil {
		return err
	}
	// Do not use `*r.config = ...`. This will modify the *shared* config
	// returned by `r.Config`.
	r.config = updated
	return nil
}
699098
func (o *ResourceConfig) EnableAll() {
	for k := range o.GroupVersionConfigs {
		o.GroupVersionConfigs[k] = true
	}
}
1084072
func newCmdKubeletConfigEnableDynamic() *cobra.Command {
	var nodeName, kubeletVersionStr string
	var kubeConfigFile string

	cmd := &cobra.Command{
		Use:     "enable-dynamic",
		Short:   "EXPERIMENTAL: Enable or update dynamic kubelet configuration for a Node",
		Long:    kubeletConfigEnableDynamicLongDesc,
		Example: kubeletConfigEnableDynamicExample,
		Run: func(cmd *cobra.Command, args []string) {
			if len(nodeName) == 0 {
				kubeadmutil.CheckErr(errors.New("The --node-name argument is required"))
			}
			if len(kubeletVersionStr) == 0 {
				kubeadmutil.CheckErr(errors.New("The --kubelet-version argument is required"))
			}

			kubeletVersion, err := version.ParseSemantic(kubeletVersionStr)
			kubeadmutil.CheckErr(err)

			kubeConfigFile = cmdutil.GetKubeConfigPath(kubeConfigFile)
			client, err := kubeconfigutil.ClientSetFromFile(kubeConfigFile)
			kubeadmutil.CheckErr(err)

			err = kubeletphase.EnableDynamicConfigForNode(client, nodeName, kubeletVersion)
			kubeadmutil.CheckErr(err)
		},
	}

	options.AddKubeConfigFlag(cmd.Flags(), &kubeConfigFile)
	cmd.Flags().StringVar(&nodeName, options.NodeName, nodeName, "Name of the node that should enable the dynamic kubelet configuration")
	cmd.Flags().StringVar(&kubeletVersionStr, "kubelet-version", kubeletVersionStr, "The desired version for the kubelet")
	return cmd
}
647129
func LoadInitConfigurationFromFile(cfgPath string) (*kubeadmapi.InitConfiguration, error) {
	klog.V(1).Infof("loading configuration from %q", cfgPath)

	b, err := ioutil.ReadFile(cfgPath)
	if err != nil {
		return nil, errors.Wrapf(err, "unable to read config from %q ", cfgPath)
	}

	return BytesToInitConfiguration(b)
}
529511
func SetClusterDynamicDefaults(cfg *kubeadmapi.ClusterConfiguration, advertiseAddress string, bindPort int32) error {
	// Default all the embedded ComponentConfig structs
	componentconfigs.Known.Default(cfg)

	ip := net.ParseIP(advertiseAddress)
	if ip.To4() != nil {
		cfg.ComponentConfigs.KubeProxy.BindAddress = kubeadmapiv1beta2.DefaultProxyBindAddressv4
	} else {
		cfg.ComponentConfigs.KubeProxy.BindAddress = kubeadmapiv1beta2.DefaultProxyBindAddressv6
	}

	// Resolve possible version labels and validate version string
	if err := NormalizeKubernetesVersion(cfg); err != nil {
		return err
	}

	// If ControlPlaneEndpoint is specified without a port number defaults it to
	// the bindPort number of the APIEndpoint.
	// This will allow join of additional control plane instances with different bindPort number
	if cfg.ControlPlaneEndpoint != "" {
		host, port, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint)
		if err != nil {
			return err
		}
		if port == "" {
			cfg.ControlPlaneEndpoint = net.JoinHostPort(host, strconv.FormatInt(int64(bindPort), 10))
		}
	}

	// Downcase SANs. Some domain names (like ELBs) have capitals in them.
	LowercaseSANs(cfg.APIServer.CertSANs)
	return nil
}
840708
func ConfigMapDataToVolumeConfig(data map[string]string, provisionerConfig *ProvisionerConfiguration) error {
	rawYaml := ""
	for key, val := range data {
		rawYaml += key
		rawYaml += ": \n"
		rawYaml += insertSpaces(string(val))
	}

	if err := yaml.Unmarshal([]byte(rawYaml), provisionerConfig); err != nil {
		return fmt.Errorf("fail to Unmarshal yaml due to: %#v", err)
	}
	for class, config := range provisionerConfig.StorageClassConfig {
		if config.BlockCleanerCommand == nil {
			// Supply a default block cleaner command.
			config.BlockCleanerCommand = []string{DefaultBlockCleanerCommand}
		} else {
			// Validate that array is non empty.
			if len(config.BlockCleanerCommand) < 1 {
				return fmt.Errorf("Invalid empty block cleaner command for class %v", class)
			}
		}
		if config.MountDir == "" || config.HostDir == "" {
			return fmt.Errorf("Storage Class %v is misconfigured, missing HostDir or MountDir parameter", class)
		}

		if config.VolumeMode == "" {
			config.VolumeMode = DefaultVolumeMode
		}
		volumeMode := v1.PersistentVolumeMode(config.VolumeMode)
		if volumeMode != v1.PersistentVolumeBlock && volumeMode != v1.PersistentVolumeFilesystem {
			return fmt.Errorf("unsupported volume mode %s", config.VolumeMode)
		}

		provisionerConfig.StorageClassConfig[class] = config
		glog.Infof("StorageClass %q configured with MountDir %q, HostDir %q, VolumeMode %q, FsType %q, BlockCleanerCommand %q",
			class,
			config.MountDir,
			config.HostDir,
			config.VolumeMode,
			config.FsType,
			config.BlockCleanerCommand)
	}
	return nil
}
908667
func (e *DeviceWrap) SwitchConfigAndActiveDevice(m libkb.MetaContext) (err error) {
	defer m.Trace("DeviceWrap#SetActiveDevice", func() error { return err })()

	if err = e.refreshMe(m); err != nil {
		return err
	}

	salt, err := e.args.Me.GetSalt()
	if err != nil {
		return err
	}
	me := e.args.Me
	// Atomically swap to the new config and active device
	if err := m.SwitchUserNewConfigActiveDevice(me.ToUserVersion(), me.GetNormalizedName(), salt,
		e.deviceID, e.signingKey, e.encryptionKey, e.args.DeviceName); err != nil {
		return err
	}

	// Sync down secrets for future offline login attempts to work.
	// This will largely just download what we just uploaded, but it's
	// easy to do this way.
	_, w := m.ActiveDevice().SyncSecrets(m)
	if w != nil {
		m.Warning("Error sync secrets: %s", w.Error())
	}
	return nil
}
1136934
func NewFilteredDynamicInformer(client dynamic.Interface, gvr schema.GroupVersionResource, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions TweakListOptionsFunc) informers.GenericInformer {
	return &dynamicInformer{
		gvr: gvr,
		informer: cache.NewSharedIndexInformer(
			&cache.ListWatch{
				ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
					if tweakListOptions != nil {
						tweakListOptions(&options)
					}
					return client.Resource(gvr).Namespace(namespace).List(options)
				},
				WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
					if tweakListOptions != nil {
						tweakListOptions(&options)
					}
					return client.Resource(gvr).Namespace(namespace).Watch(options)
				},
			},
			&unstructured.Unstructured{},
			resyncPeriod,
			indexers,
		),
	}
}
1203776
func BootstrapKubeletConfigController(dynamicConfigDir string, transform dynamickubeletconfig.TransformFunc) (*kubeletconfiginternal.KubeletConfiguration, *dynamickubeletconfig.Controller, error) {
	if !utilfeature.DefaultFeatureGate.Enabled(features.DynamicKubeletConfig) {
		return nil, nil, fmt.Errorf("failed to bootstrap Kubelet config controller, you must enable the DynamicKubeletConfig feature gate")
	}
	if len(dynamicConfigDir) == 0 {
		return nil, nil, fmt.Errorf("cannot bootstrap Kubelet config controller, --dynamic-config-dir was not provided")
	}

	// compute absolute path and bootstrap controller
	dir, err := filepath.Abs(dynamicConfigDir)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to get absolute path for --dynamic-config-dir=%s", dynamicConfigDir)
	}
	// get the latest KubeletConfiguration checkpoint from disk, or return the default config if no valid checkpoints exist
	c := dynamickubeletconfig.NewController(dir, transform)
	kc, err := c.Bootstrap()
	if err != nil {
		return nil, nil, fmt.Errorf("failed to determine a valid configuration, error: %v", err)
	}
	return kc, c, nil
}