// handleConfigMapFromEnvFileSource adds the specified env file source information
// into the provided configMap
506075
func handleConfigMapFromEnvFileSource(configMap *v1.ConfigMap, envFileSource string) error {
	info, err := os.Stat(envFileSource)
	if err != nil {
		switch err := err.(type) {
		case *os.PathError:
			return fmt.Errorf("error reading %s: %v", envFileSource, err.Err)
		default:
			return fmt.Errorf("error reading %s: %v", envFileSource, err)
		}
	}
	if info.IsDir() {
		return fmt.Errorf("env config file cannot be a directory")
	}

	return addFromEnvFile(envFileSource, func(key, value string) error {
		return addKeyFromLiteralToConfigMap(configMap, key, value)
	})
}
1321534
func (p environStatePolicy) ProviderConfigSchemaSource(cloudName string) (config.ConfigSchemaSource, error) {
	cloud, err := p.st.Cloud(cloudName)
	if err != nil {
		return nil, errors.Trace(err)
	}
	provider, err := environProvider(cloud.Type)
	if err != nil {
		return nil, errors.Trace(err)
	}
	if cs, ok := provider.(config.ConfigSchemaSource); ok {
		return cs, nil
	}
	return nil, errors.NotImplementedf("config.ConfigSource")
}
173974
func configMapToConfig(configMap map[string]comparable, rootGroupKey string) (*cb.ConfigGroup, error) {
	rootPath := pathSeparator + rootGroupKey
	return recurseConfigMap(rootPath, configMap)
}
1283462
func addKvToConfigMap(configMap *v1.ConfigMap, keyName, data string) error {
	// Note, the rules for ConfigMap keys are the exact same as the ones for SecretKeys.
	if errs := validation.IsConfigMapKey(keyName); len(errs) != 0 {
		return fmt.Errorf("%q is not a valid key name for a ConfigMap: %s", keyName, strings.Join(errs, ";"))
	}

	keyExistsErrorMsg := "cannot add key %s, another key by that name already exists: %v"

	// If the configmap data contains byte sequences that are all in the UTF-8
	// range, we will write it to .Data
	if utf8.Valid([]byte(data)) {
		if _, entryExists := configMap.Data[keyName]; entryExists {
			return fmt.Errorf(keyExistsErrorMsg, keyName, configMap.Data)
		}
		configMap.Data[keyName] = data
		return nil
	}

	// otherwise, it's BinaryData
	if configMap.BinaryData == nil {
		configMap.BinaryData = map[string][]byte{}
	}
	if _, entryExists := configMap.BinaryData[keyName]; entryExists {
		return fmt.Errorf(keyExistsErrorMsg, keyName, configMap.BinaryData)
	}
	configMap.BinaryData[keyName] = []byte(data)
	return nil
}
475441
func Convert_v1alpha1_SchedulerPolicyConfigMapSource_To_config_SchedulerPolicyConfigMapSource(in *v1alpha1.SchedulerPolicyConfigMapSource, out *config.SchedulerPolicyConfigMapSource, s conversion.Scope) error {
	return autoConvert_v1alpha1_SchedulerPolicyConfigMapSource_To_config_SchedulerPolicyConfigMapSource(in, out, s)
}
1059489
func fileAsConfigMap(file string) ([]byte, map[string]interface{}, error) {
	raw, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, nil, errors.Annotatef(err, "reading config from %q", file)
	}
	if len(raw) == 0 {
		return nil, nil, nil
	}

	cfg, err := bytesAsConfigMap(raw)
	if err != nil {
		return raw, cfg, errors.NotValidf("converting %q contents to map: %s", file, err.Error())
	}
	return raw, cfg, nil
}
334092
func DefaultAPIResourceConfigSource() *serverstorage.ResourceConfig {
	ret := serverstorage.NewResourceConfig()
	// NOTE: GroupVersions listed here will be enabled by default. Don't put alpha versions in the list.
	ret.EnableVersions(
		v1.SchemeGroupVersion,
		v1beta1.SchemeGroupVersion,
	)

	return ret
}
801945
func validateConfigMapNodeConfigSourceSpec(source *core.ConfigMapNodeConfigSource, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	// uid and resourceVersion must not be set in spec
	if string(source.UID) != "" {
		allErrs = append(allErrs, field.Forbidden(fldPath.Child("uid"), "uid must not be set in spec"))
	}
	if source.ResourceVersion != "" {
		allErrs = append(allErrs, field.Forbidden(fldPath.Child("resourceVersion"), "resourceVersion must not be set in spec"))
	}
	return append(allErrs, validateConfigMapNodeConfigSource(source, fldPath)...)
}
450740
func (p *ProvisionerAPI) imageMetadataFromDataSources(env environs.Environ, constraint *imagemetadata.ImageConstraint) ([]params.CloudImageMetadata, error) {
	sources, err := environs.ImageMetadataSources(env)
	if err != nil {
		return nil, errors.Trace(err)
	}

	cfg := env.Config()
	toModel := func(m *imagemetadata.ImageMetadata, mSeries string, source string, priority int) cloudimagemetadata.Metadata {
		result := cloudimagemetadata.Metadata{
			MetadataAttributes: cloudimagemetadata.MetadataAttributes{
				Region:          m.RegionName,
				Arch:            m.Arch,
				VirtType:        m.VirtType,
				RootStorageType: m.Storage,
				Source:          source,
				Series:          mSeries,
				Stream:          m.Stream,
				Version:         m.Version,
			},
			Priority: priority,
			ImageId:  m.Id,
		}
		// TODO (anastasiamac 2016-08-24) This is a band-aid solution.
		// Once correct value is read from simplestreams, this needs to go.
		// Bug# 1616295
		if result.Stream == "" {
			result.Stream = constraint.Stream
		}
		if result.Stream == "" {
			result.Stream = cfg.ImageStream()
		}
		return result
	}

	var metadataState []cloudimagemetadata.Metadata
	for _, source := range sources {
		logger.Debugf("looking in data source %v", source.Description())
		found, info, err := imagemetadata.Fetch([]simplestreams.DataSource{source}, constraint)
		if err != nil {
			// Do not stop looking in other data sources if there is an issue here.
			logger.Warningf("encountered %v while getting published images metadata from %v", err, source.Description())
			continue
		}
		for _, m := range found {
			mSeries, err := series.VersionSeries(m.Version)
			if err != nil {
				logger.Warningf("could not determine series for image id %s: %v", m.Id, err)
				continue
			}
			metadataState = append(metadataState, toModel(m, mSeries, info.Source, source.Priority()))
		}
	}
	if len(metadataState) > 0 {
		if err := p.st.CloudImageMetadataStorage.SaveMetadata(metadataState); err != nil {
			// No need to react here, just take note
			logger.Warningf("failed to save published image metadata: %v", err)
		}
	}

	// Since we've fallen through to data sources search and have saved all needed images into controller,
	// let's try to get them from controller to avoid duplication of conversion logic here.
	all, err := p.imageMetadataFromState(constraint)
	if err != nil {
		return nil, errors.Annotate(err, "could not read metadata from controller after saving it there from data sources")
	}

	if len(all) == 0 {
		return nil, errors.NotFoundf("image metadata for series %v, arch %v", constraint.Series, constraint.Arches)
	}

	return all, nil
}
974076
func (s *configMapLister) ConfigMaps(namespace string) ConfigMapNamespaceLister {
	return configMapNamespaceLister{indexer: s.indexer, namespace: namespace}
}
396211
func NewFileSource() FileSource {
	if fileConfigSource == nil {
		fileConfigSource = new(fileSource)
		fileConfigSource.priority = fileSourcePriority
		fileConfigSource.files = make([]file, 0)
		fileConfigSource.fileHandlers = make(map[string]FileHandler)
	}

	return fileConfigSource
}
1083633
func createConfigMap(client *k8s.Client, name string, values map[string]string) error {
	cm := &v1.ConfigMap{
		Metadata: &metav1.ObjectMeta{
			Name:      &name,
			Namespace: &client.Namespace,
		},
		Data: values,
	}

	err := client.Create(context.Background(), cm)

	// If an HTTP error was returned by the API server, it will be of type
	// *k8s.APIError. This can be used to inspect the status code.
	if apiErr, ok := err.(*k8s.APIError); ok {
		// Resource already exists. Carry on.
		if apiErr.Code == http.StatusConflict {
			return nil
		}
	}
	return fmt.Errorf("create configmap: %v", err)
}
447665
func addKeyFromFileToConfigMap(configMap *v1.ConfigMap, keyName, filePath string) error {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	if utf8.Valid(data) {
		return addKeyFromLiteralToConfigMap(configMap, keyName, string(data))
	}

	err = validateNewConfigMap(configMap, keyName)
	if err != nil {
		return err
	}
	configMap.BinaryData[keyName] = data
	return nil
}
1360690
func (s *Stack) createFileBasedConfigMaps(configMaps corev1.ConfigMapInterface) ([]childResource, error) {
	var resources []childResource
	for name, config := range s.Spec.Configs {
		if config.File == "" {
			continue
		}

		fileName := filepath.Base(config.File)
		content, err := ioutil.ReadFile(config.File)
		if err != nil {
			return resources, err
		}

		configMap, err := configMaps.Create(toConfigMap(s.Name, name, fileName, content))
		if err != nil {
			return resources, err
		}
		resources = append(resources, &configMapChildResource{client: configMaps, configMap: configMap})
	}
	return resources, nil
}
480866
func NewEnvSource(prefix string, env ...string) Source {
	vars := makeEnvVars(env)
	base := make([]string, 0, 10)

	if prefix != "" {
		base = append(base, prefix)
	}

	return SourceFunc(func(dst Map) (err error) {
		dst.Scan(func(path []string, item MapItem) {
			path = append(base, path...)
			path = append(path, item.Name)

			k := snakecaseUpper(strings.Join(path, "_"))

			if v, ok := vars[k]; ok {
				if e := item.Value.Set(v); e != nil {
					err = e
				}
			}
		})
		return
	})
}
1217879
func Convert_core_EnvFromSource_To_v1_EnvFromSource(in *core.EnvFromSource, out *v1.EnvFromSource, s conversion.Scope) error {
	return autoConvert_core_EnvFromSource_To_v1_EnvFromSource(in, out, s)
}
919419
func handleFromFileSources(secret *api.Secret, fileSources []string) error {
	for _, fileSource := range fileSources {
		keyName, filePath, err := parseFileSource(fileSource)
		if err != nil {
			return err
		}
		info, err := os.Stat(filePath)
		if err != nil {
			switch err := err.(type) {
			case *os.PathError:
				return fmt.Errorf("error reading %s: %v", filePath, err.Err)
			default:
				return fmt.Errorf("error reading %s: %v", filePath, err)
			}
		}
		if info.IsDir() {
			if strings.Contains(fileSource, "=") {
				return fmt.Errorf("cannot give a key name for a directory path.")
			}
			fileList, err := ioutil.ReadDir(filePath)
			if err != nil {
				return fmt.Errorf("error listing files in %s: %v", filePath, err)
			}
			for _, item := range fileList {
				itemPath := path.Join(filePath, item.Name())
				if item.Mode().IsRegular() {
					keyName = item.Name()
					err = addKeyFromFileToSecret(secret, keyName, itemPath)
					if err != nil {
						return err
					}
				}
			}
		} else {
			err = addKeyFromFileToSecret(secret, keyName, filePath)
			if err != nil {
				return err
			}
		}
	}

	return nil
}