// NewFromEnv reads a set of credentials in from environment variables in
// the format {PREFIX}{USERNAME|tolower}=password1,password2 and returns
// middleware that will validate incoming requests.
173192
func NewFromEnv(realm, prefix string) func(http.Handler) http.Handler {
	credentials := map[string][]string{}

	re := regexp.MustCompile(fmt.Sprintf("^%s(?P<username>.*)$", strings.ToUpper(prefix)))
	for _, envVar := range os.Environ() {
		name, value := split2(envVar, "=")

		if res := re.FindStringSubmatch(name); res != nil {
			username := strings.ToLower(res[1])
			credentials[username] = strings.Split(value, ",")
		}
	}

	return New(realm, credentials)
}
536253
func (o *EnvOptions) RunEnv() error {
	env, remove, err := utilenv.ParseEnv(append(o.EnvParams, o.EnvArgs...), o.In)
	if err != nil {
		return err
	}

	if len(o.From) != 0 {
		b := o.Builder().
			WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
			LocalParam(o.Local).
			ContinueOnError().
			NamespaceParam(o.Namespace).DefaultNamespace().
			FilenameParam(o.ExplicitNamespace, &o.FilenameOptions).
			Flatten()

		if !o.Local {
			b = b.
				LabelSelectorParam(o.Selector).
				ResourceTypeOrNameArgs(o.All, o.From).
				Latest()
		}

		singleItemImplied := false
		infos, err := b.Do().IntoSingleItemImplied(&singleItemImplied).Infos()
		if err != nil {
			return err
		}

		for _, info := range infos {
			switch from := info.Object.(type) {
			case *corev1.Secret:
				for key := range from.Data {
					envVar := corev1.EnvVar{
						Name: keyToEnvName(key),
						ValueFrom: &corev1.EnvVarSource{
							SecretKeyRef: &corev1.SecretKeySelector{
								LocalObjectReference: corev1.LocalObjectReference{
									Name: from.Name,
								},
								Key: key,
							},
						},
					}
					env = append(env, envVar)
				}
			case *corev1.ConfigMap:
				for key := range from.Data {
					envVar := corev1.EnvVar{
						Name: keyToEnvName(key),
						ValueFrom: &corev1.EnvVarSource{
							ConfigMapKeyRef: &corev1.ConfigMapKeySelector{
								LocalObjectReference: corev1.LocalObjectReference{
									Name: from.Name,
								},
								Key: key,
							},
						},
					}
					env = append(env, envVar)
				}
			default:
				return fmt.Errorf("unsupported resource specified in --from: %T", from)
			}
		}
	}

	if len(o.Prefix) != 0 {
		for i := range env {
			env[i].Name = fmt.Sprintf("%s%s", o.Prefix, env[i].Name)
		}
	}

	b := o.Builder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		LocalParam(o.Local).
		ContinueOnError().
		NamespaceParam(o.Namespace).DefaultNamespace().
		FilenameParam(o.ExplicitNamespace, &o.FilenameOptions).
		Flatten()

	if !o.Local {
		b = b.
			LabelSelectorParam(o.Selector).
			ResourceTypeOrNameArgs(o.All, o.Resources...).
			Latest()
	}

	singleItemImplied := false
	infos, err := b.Do().IntoSingleItemImplied(&singleItemImplied).Infos()
	if err != nil {
		return err
	}

	// only apply resource version locking on a single resource
	if !singleItemImplied && len(o.ResourceVersion) > 0 {
		return fmt.Errorf("--resource-version may only be used with a single resource")
	}
	// Keep a copy of the original objects prior to updating their environment.
	// Used in constructing the patch(es) that will be applied in the server.
	oldObjects := []runtime.Object{}
	oldData := make([][]byte, len(infos))
	for i := range infos {
		oldObjects = append(oldObjects, infos[i].Object.DeepCopyObject())
		old, err := json.Marshal(oldObjects[i])
		if err != nil {
			return err
		}
		oldData[i] = old
	}

	skipped := 0
	errored := []*resource.Info{}
	for _, info := range infos {
		name := getObjectName(info)
		ok, err := o.UpdatePodSpecForObject(info.Object, func(spec *corev1.PodSpec) error {
			resolutionErrorsEncountered := false
			containers, _ := selectContainers(spec.Containers, o.ContainerSelector)
			if len(containers) == 0 {
				fmt.Fprintf(o.ErrOut, "warning: %s does not have any containers matching %q\n", name, o.ContainerSelector)
				return nil
			}
			for _, c := range containers {
				if !o.Overwrite {
					if err := validateNoOverwrites(c.Env, env); err != nil {
						errored = append(errored, info)
						return err
					}
				}

				c.Env = updateEnv(c.Env, env, remove)

				if o.List {
					resolveErrors := map[string][]string{}
					store := envresolve.NewResourceStore()

					fmt.Fprintf(o.Out, "# %s, container %s\n", name, c.Name)
					for _, env := range c.Env {
						// Print the simple value
						if env.ValueFrom == nil {
							fmt.Fprintf(o.Out, "%s=%s\n", env.Name, env.Value)
							continue
						}

						// Print the reference version
						if !o.Resolve {
							fmt.Fprintf(o.Out, "# %s from %s\n", env.Name, envresolve.GetEnvVarRefString(env.ValueFrom))
							continue
						}

						value, err := envresolve.GetEnvVarRefValue(o.KubeClient, o.Namespace, store, env.ValueFrom, info.Object, c)
						// Print the resolved value
						if err == nil {
							fmt.Fprintf(o.Out, "%s=%s\n", env.Name, value)
							continue
						}

						// Print the reference version and save the resolve error
						fmt.Fprintf(o.Out, "# %s from %s\n", env.Name, envresolve.GetEnvVarRefString(env.ValueFrom))
						errString := err.Error()
						resolveErrors[errString] = append(resolveErrors[errString], env.Name)
						resolutionErrorsEncountered = true
					}

					// Print any resolution errors
					errs := []string{}
					for err, vars := range resolveErrors {
						sort.Strings(vars)
						errs = append(errs, fmt.Sprintf("error retrieving reference for %s: %v", strings.Join(vars, ", "), err))
					}
					sort.Strings(errs)
					for _, err := range errs {
						fmt.Fprintln(o.ErrOut, err)
					}
				}
			}
			if resolutionErrorsEncountered {
				errored = append(errored, info)
				return errors.New("failed to retrieve valueFrom references")
			}
			return nil
		})
		if !ok {
			// This is a fallback function for objects that don't have pod spec.
			ok, err = updateObjectEnvironment(info.Object, func(vars *[]corev1.EnvVar) error {
				if vars == nil {
					return fmt.Errorf("no environment variables provided")
				}
				if !o.Overwrite {
					if err := validateNoOverwrites(*vars, env); err != nil {
						errored = append(errored, info)
						return err
					}
				}
				*vars = updateEnv(*vars, env, remove)
				if o.List {
					fmt.Fprintf(o.Out, "# %s\n", name)
					for _, env := range *vars {
						fmt.Fprintf(o.Out, "%s=%s\n", env.Name, env.Value)
					}
				}
				return nil
			})
			if !ok {
				skipped++
				continue
			}
		}
		if err != nil {
			fmt.Fprintf(o.ErrOut, "error: %s %v\n", name, err)
			continue
		}
	}
	if singleItemImplied && skipped == len(infos) {
		name := getObjectName(infos[0])
		return fmt.Errorf("%s is not a pod or does not have a pod template", name)
	}
	if len(errored) == len(infos) {
		return kcmdutil.ErrExit
	}

	if o.List {
		return nil
	}

	allErrs := []error{}
updates:
	for i, info := range infos {
		for _, erroredInfo := range errored {
			if info == erroredInfo {
				continue updates
			}
		}

		if o.Local || o.DryRun {
			if err := o.Printer.PrintObj(info.Object, o.Out); err != nil {
				allErrs = append(allErrs, err)
			}
			continue
		}

		newData, err := json.Marshal(infos[i].Object)
		if err != nil {
			allErrs = append(allErrs, err)
			continue
		}
		patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData[i], newData, infos[i].Object)
		if err != nil {
			allErrs = append(allErrs, err)
			continue
		}

		actual, err := o.Client.Resource(info.Mapping.Resource).Namespace(info.Namespace).Patch(info.Name, types.StrategicMergePatchType, patchBytes, metav1.UpdateOptions{})
		if err != nil {
			allErrs = append(allErrs, fmt.Errorf("failed to set env: %v\n", err))
			continue
		}

		// make sure arguments to set or replace environment variables are set
		// before returning a successful message
		if len(env) == 0 && len(o.EnvArgs) == 0 && len(remove) == 0 {
			return fmt.Errorf("at least one environment variable must be provided")
		}

		if err := o.Printer.PrintObj(actual, o.Out); err != nil {
			allErrs = append(allErrs, err)
		}
	}
	return utilerrors.NewAggregate(allErrs)
}
1319712
func (e *Env) NewEnv() *Env {
	return &Env{
		env:    make(map[string]reflect.Value),
		typ:    make(map[string]reflect.Type),
		parent: e,
		name:   e.name,
	}
}
171863
func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials {
	return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...))
}
561079
func NewFileAWSCredentials(filename string, profile string) *Credentials {
	return New(&FileAWSCredentials{
		filename: filename,
		profile:  profile,
	})
}
89664
func NamespaceFromEnv(ctx context.Context) context.Context {
	namespace := os.Getenv(NamespaceEnvVar)
	if namespace == "" {
		namespace = Default
	}
	return WithNamespace(ctx, namespace)
}
706848
func NewOrdererClientFromEnv() (*OrdererClient, error) {
	address, override, clientConfig, err := configFromEnv("orderer")
	if err != nil {
		return nil, errors.WithMessage(err, "failed to load config for OrdererClient")
	}
	gClient, err := comm.NewGRPCClient(clientConfig)
	if err != nil {
		return nil, errors.WithMessage(err, "failed to create OrdererClient from config")
	}
	oClient := &OrdererClient{
		commonClient: commonClient{
			GRPCClient: gClient,
			address:    address,
			sn:         override}}
	return oClient, nil
}
1304672
func NewV4(endpoint string, accessKeyID, secretAccessKey string, secure bool) (*Client, error) {
	creds := credentials.NewStaticV4(accessKeyID, secretAccessKey, "")
	clnt, err := privateNew(endpoint, creds, secure, "", BucketLookupAuto)
	if err != nil {
		return nil, err
	}
	clnt.overrideSignerType = credentials.SignatureV4
	return clnt, nil
}
1342152
func loadFromEnv(conf *GatewayConfig) {
	// general configs
	conf.ServerName = getStringEnvVar("SFX_SERVER_NAME", conf.ServerName)
	conf.ClusterName = getStringEnvVar("SFX_GATEWAY_CLUSTER_NAME", conf.ClusterName)
	conf.ClusterOperation = getStringEnvVar("SFX_CLUSTER_OPERATION", conf.ClusterOperation)
	conf.ClusterDataDir = getStringEnvVar("SFX_CLUSTER_DATA_DIR", conf.ClusterDataDir)

	// file limits
	conf.EtcdSnapCount = getUint64EnvVar("SFX_ETCD_SNAP_COUNT", conf.EtcdSnapCount)
	conf.EtcdMaxSnapFiles = getUintEnvVar("SFX_ETCD_MAX_SNAP_FILES", conf.EtcdMaxSnapFiles)
	conf.EtcdMaxWalFiles = getUintEnvVar("SFX_ETD_MAX_WAL_FILES", conf.EtcdMaxWalFiles)

	// Target Cluster Addresses
	conf.TargetClusterAddresses = getCommaSeparatedStringEnvVar("SFX_TARGET_CLUSTER_ADDRESSES", conf.TargetClusterAddresses)

	// Peer Addresses
	conf.ListenOnPeerAddress = getStringEnvVar("SFX_LISTEN_ON_PEER_ADDRESS", conf.ListenOnPeerAddress)
	conf.ListenOnPeerAddresses = getCommaSeparatedStringEnvVar("SFX_LISTEN_ON_PEER_ADDRESSES", conf.ListenOnPeerAddresses)
	conf.AdvertisePeerAddress = getStringEnvVar("SFX_ADVERTISE_PEER_ADDRESS", conf.AdvertisePeerAddress)
	conf.AdvertisedPeerAddresses = getCommaSeparatedStringEnvVar("SFX_ADVERTISED_PEER_ADDRESSES", conf.AdvertisedPeerAddresses)

	// Client Addresses
	conf.ListenOnClientAddress = getStringEnvVar("SFX_LISTEN_ON_CLIENT_ADDRESS", conf.ListenOnClientAddress)
	conf.ListenOnClientAddresses = getCommaSeparatedStringEnvVar("SFX_LISTEN_ON_CLIENT_ADDRESSES", conf.ListenOnClientAddresses)
	conf.AdvertiseClientAddress = getStringEnvVar("SFX_ADVERTISE_CLIENT_ADDRESS", conf.AdvertiseClientAddress)
	conf.AdvertisedClientAddresses = getCommaSeparatedStringEnvVar("SFX_ADVERTISED_CLIENT_ADDRESSES", conf.AdvertisedClientAddresses)

	// Metric Addresses
	conf.ETCDMetricsAddress = getStringEnvVar("SFX_ETCD_METRICS_ADDRESS", conf.ETCDMetricsAddress)
	conf.EtcdListenOnMetricsAddresses = getCommaSeparatedStringEnvVar("SFX_ETCD_LISTEN_ON_METRICS_ADDRESSES", conf.EtcdListenOnMetricsAddresses)

	// Durations
	conf.UnhealthyMemberTTL = getDurationEnvVar("SFX_UNHEALTHY_MEMBER_TTL", conf.UnhealthyMemberTTL)
	conf.RemoveMemberTimeout = getDurationEnvVar("SFX_REMOVE_MEMBER_TIMEOUT", conf.RemoveMemberTimeout)
	conf.EtcdDialTimeout = getDurationEnvVar("SFX_ETCD_DIAL_TIMEOUT", conf.EtcdDialTimeout)
	conf.EtcdClusterCleanUpInterval = getDurationEnvVar("SFX_ETCD_CLUSTER_CLEANUP_INTERVAL", conf.EtcdClusterCleanUpInterval)
	conf.EtcdAutoSyncInterval = getDurationEnvVar("SFX_ETCD_AUTOSYNC_INTERVAL", conf.EtcdAutoSyncInterval)
	conf.EtcdStartupGracePeriod = getDurationEnvVar("SFX_ETCD_STARTUP_GRACE_PERIOD", conf.EtcdStartupGracePeriod)
	conf.EtcdHeartBeatInterval = getDurationEnvVar("SFX_ETCD_HEARTBEAT_INTERVAL", conf.EtcdHeartBeatInterval)
	conf.EtcdElectionTimeout = getDurationEnvVar("SFX_ETCD_ELECTION_TIMEOUT", conf.EtcdElectionTimeout)
}
967782
func NewV2(domain byte) UUID {
	u := UUID{}

	timeNow, clockSeq, hardwareAddr := getStorage()

	switch domain {
	case DomainPerson:
		binary.BigEndian.PutUint32(u[0:], posixUID)
	case DomainGroup:
		binary.BigEndian.PutUint32(u[0:], posixGID)
	}

	binary.BigEndian.PutUint16(u[4:], uint16(timeNow>>32))
	binary.BigEndian.PutUint16(u[6:], uint16(timeNow>>48))
	binary.BigEndian.PutUint16(u[8:], clockSeq)
	u[9] = domain

	copy(u[10:], hardwareAddr)

	u.SetVersion(2)
	u.SetVariant()

	return u
}
171148
func CompleteCredentialsFromEnv(keyName string) (cred *auth.Credentials, err error) {
	cred, err = credentialsFromEnv(keyName)
	if err != nil {
		return nil, err
	}
	v := reflect.ValueOf(cred).Elem()
	t := v.Type()
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i)
		if f.String() == "" {
			return nil, fmt.Errorf("Required environment variable not set for credentials attribute: %s", t.Field(i).Name)
		}
	}
	return cred, nil
}
187832
func NewRequest(username, password, method, uri, body string) DigestRequest {
	dr := DigestRequest{}
	dr.UpdateRequest(username, password, method, uri, body)
	dr.CertVal = true
	return dr
}
989145
func (cniApp *cniAppInfo) parseEnv() error {

	cniApp.logFields = make(logger.Fields)
	envVal := ""

	for _, envName := range cniEnvList {

		if envVal = os.Getenv(envName); envVal == "" {
			return fmt.Errorf("failed to get env variable %s", envName)
		}
		logger.Infof("parsed env variable %s = [%s]", envName, envVal)

		switch envName {

		case envVarCniCommand:
			cniApp.cniCmd = strings.ToUpper(envVal)
			cniApp.logFields["CMD"] = envVal
			if _, ok := map[string]int{cniapi.CniCmdAdd: 1,
				cniapi.CniCmdDel: 2}[cniApp.cniCmd]; ok == false {
				return fmt.Errorf("unknown CNI command %s", envName)
			}

		case envVarCniIfname:
			cniApp.cniMesosAttr.CniIfname = envVal

		case envVarCniNetns:
			cniApp.cniMesosAttr.CniNetns = envVal
			nsDir := filepath.Dir(envVal)
			cniApp.netcfgFile = strings.Join([]string{nsDir, "netcontiv", "network.conf"}, "/")
			logger.Infof("cni network config file location : %s", cniApp.netcfgFile)

		case envVarCniContainerID:
			cniApp.cniMesosAttr.CniContainerid = envVal
			cniApp.logFields["CID"] = strings.Split(envVal, "-")[0]
			logger.Debugf("added fields in logger CID: %s", cniApp.logFields["CID"])

		default:
			cniLog.Errorf("unknown CNI variable %s", envName)
		}
	}
	// update logger
	cniLog = logger.WithFields(cniApp.logFields)

	return nil
}
1199795
func NewCredentialValidatorAPIv1(ctx facade.Context) (*CredentialValidatorAPIV1, error) {
	v2, err := NewCredentialValidatorAPI(ctx)
	if err != nil {
		return nil, err
	}
	return &CredentialValidatorAPIV1{v2}, nil
}
995841
func NewRequest(username, password string) Request {
	invalidCh := make(chan InvalidPassword)
	createdCh := make(chan CreatedUser)
	authenticatedCh := make(chan AuthenticatedUser)

	return Request{
		Time:     filu.Now(),
		Username: username,
		Password: password,

		InvalidPassword:   invalidCh,
		CreatedUser:       createdCh,
		AuthenticatedUser: authenticatedCh,

		sendInvalidPassword:   invalidCh,
		sendCreatedUser:       createdCh,
		sendAuthenticatedUser: authenticatedCh,
	}
}
885729
func initEnv(prefix string) {
	copyEnvVars(prefix)

	// env variables with TM prefix (eg. TM_ROOT)
	viper.SetEnvPrefix(prefix)
	viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
	viper.AutomaticEnv()
}
155428
func NewV3(ns UUID, name string) UUID {
	return global.NewV3(ns, name)
}