// SecretSpecToGRPC converts Secret to a grpc Secret.
15258
func SecretSpecToGRPC(s swarmtypes.SecretSpec) swarmapi.SecretSpec {
	spec := swarmapi.SecretSpec{
		Annotations: swarmapi.Annotations{
			Name:   s.Name,
			Labels: s.Labels,
		},
		Data:   s.Data,
		Driver: driverToGRPC(s.Driver),
	}

	if s.Templating != nil {
		spec.Templating = &swarmapi.Driver{
			Name:    s.Templating.Name,
			Options: s.Templating.Options,
		}
	}

	return spec
}
1181552
func getSecretString(secret *v1.Secret, key string) string {
	data, ok := secret.Data[key]
	if !ok {
		return ""
	}

	return string(data)
}
743186
func NewCryptoClientRPC(config Config, kbCtx Context) *CryptoClientRPC {
	log := config.MakeLogger("")
	deferLog := log.CloneWithAddedDepth(1)
	c := &CryptoClientRPC{
		CryptoClient: CryptoClient{
			CryptoCommon: MakeCryptoCommon(config.Codec(), config),
			log:          log,
			deferLog:     deferLog,
		},
		config: config,
	}
	conn := NewSharedKeybaseConnection(kbCtx, config, c)
	c.CryptoClient.client = keybase1.CryptoClient{Cli: conn.GetClient()}
	c.CryptoClient.teamsClient = keybase1.TeamsClient{Cli: conn.GetClient()}
	c.CryptoClient.shutdownFn = conn.Shutdown
	return c
}
890676
func ServiceSpecToGRPC(s types.ServiceSpec) (swarmapi.ServiceSpec, error) {
	name := s.Name
	if name == "" {
		name = namesgenerator.GetRandomName(0)
	}

	serviceNetworks := make([]*swarmapi.NetworkAttachmentConfig, 0, len(s.Networks))
	for _, n := range s.Networks {
		netConfig := &swarmapi.NetworkAttachmentConfig{Target: n.Target, Aliases: n.Aliases, DriverAttachmentOpts: n.DriverOpts}
		serviceNetworks = append(serviceNetworks, netConfig)
	}

	taskNetworks := make([]*swarmapi.NetworkAttachmentConfig, 0, len(s.TaskTemplate.Networks))
	for _, n := range s.TaskTemplate.Networks {
		netConfig := &swarmapi.NetworkAttachmentConfig{Target: n.Target, Aliases: n.Aliases, DriverAttachmentOpts: n.DriverOpts}
		taskNetworks = append(taskNetworks, netConfig)

	}

	spec := swarmapi.ServiceSpec{
		Annotations: swarmapi.Annotations{
			Name:   name,
			Labels: s.Labels,
		},
		Task: swarmapi.TaskSpec{
			Resources:   resourcesToGRPC(s.TaskTemplate.Resources),
			LogDriver:   driverToGRPC(s.TaskTemplate.LogDriver),
			Networks:    taskNetworks,
			ForceUpdate: s.TaskTemplate.ForceUpdate,
		},
		Networks: serviceNetworks,
	}

	switch s.TaskTemplate.Runtime {
	case types.RuntimeContainer, "": // if empty runtime default to container
		if s.TaskTemplate.ContainerSpec != nil {
			containerSpec, err := containerToGRPC(s.TaskTemplate.ContainerSpec)
			if err != nil {
				return swarmapi.ServiceSpec{}, err
			}
			spec.Task.Runtime = &swarmapi.TaskSpec_Container{Container: containerSpec}
		} else {
			// If the ContainerSpec is nil, we can't set the task runtime
			return swarmapi.ServiceSpec{}, ErrMismatchedRuntime
		}
	case types.RuntimePlugin:
		if s.TaskTemplate.PluginSpec != nil {
			if s.Mode.Replicated != nil {
				return swarmapi.ServiceSpec{}, errors.New("plugins must not use replicated mode")
			}

			s.Mode.Global = &types.GlobalService{} // must always be global

			pluginSpec, err := proto.Marshal(s.TaskTemplate.PluginSpec)
			if err != nil {
				return swarmapi.ServiceSpec{}, err
			}
			spec.Task.Runtime = &swarmapi.TaskSpec_Generic{
				Generic: &swarmapi.GenericRuntimeSpec{
					Kind: string(types.RuntimePlugin),
					Payload: &gogotypes.Any{
						TypeUrl: string(types.RuntimeURLPlugin),
						Value:   pluginSpec,
					},
				},
			}
		} else {
			return swarmapi.ServiceSpec{}, ErrMismatchedRuntime
		}
	case types.RuntimeNetworkAttachment:
		// NOTE(dperny) I'm leaving this case here for completeness. The actual
		// code is left out deliberately, as we should refuse to parse a
		// Network Attachment runtime; it will cause weird behavior all over
		// the system if we do. Instead, fallthrough and return
		// ErrUnsupportedRuntime if we get one.
		fallthrough
	default:
		return swarmapi.ServiceSpec{}, ErrUnsupportedRuntime
	}

	restartPolicy, err := restartPolicyToGRPC(s.TaskTemplate.RestartPolicy)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}
	spec.Task.Restart = restartPolicy

	if s.TaskTemplate.Placement != nil {
		var preferences []*swarmapi.PlacementPreference
		for _, pref := range s.TaskTemplate.Placement.Preferences {
			if pref.Spread != nil {
				preferences = append(preferences, &swarmapi.PlacementPreference{
					Preference: &swarmapi.PlacementPreference_Spread{
						Spread: &swarmapi.SpreadOver{
							SpreadDescriptor: pref.Spread.SpreadDescriptor,
						},
					},
				})
			}
		}
		var platforms []*swarmapi.Platform
		for _, plat := range s.TaskTemplate.Placement.Platforms {
			platforms = append(platforms, &swarmapi.Platform{
				Architecture: plat.Architecture,
				OS:           plat.OS,
			})
		}
		spec.Task.Placement = &swarmapi.Placement{
			Constraints: s.TaskTemplate.Placement.Constraints,
			Preferences: preferences,
			MaxReplicas: s.TaskTemplate.Placement.MaxReplicas,
			Platforms:   platforms,
		}
	}

	spec.Update, err = updateConfigToGRPC(s.UpdateConfig)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}
	spec.Rollback, err = updateConfigToGRPC(s.RollbackConfig)
	if err != nil {
		return swarmapi.ServiceSpec{}, err
	}

	if s.EndpointSpec != nil {
		if s.EndpointSpec.Mode != "" &&
			s.EndpointSpec.Mode != types.ResolutionModeVIP &&
			s.EndpointSpec.Mode != types.ResolutionModeDNSRR {
			return swarmapi.ServiceSpec{}, fmt.Errorf("invalid resolution mode: %q", s.EndpointSpec.Mode)
		}

		spec.Endpoint = &swarmapi.EndpointSpec{}

		spec.Endpoint.Mode = swarmapi.EndpointSpec_ResolutionMode(swarmapi.EndpointSpec_ResolutionMode_value[strings.ToUpper(string(s.EndpointSpec.Mode))])

		for _, portConfig := range s.EndpointSpec.Ports {
			spec.Endpoint.Ports = append(spec.Endpoint.Ports, &swarmapi.PortConfig{
				Name:          portConfig.Name,
				Protocol:      swarmapi.PortConfig_Protocol(swarmapi.PortConfig_Protocol_value[strings.ToUpper(string(portConfig.Protocol))]),
				PublishMode:   swarmapi.PortConfig_PublishMode(swarmapi.PortConfig_PublishMode_value[strings.ToUpper(string(portConfig.PublishMode))]),
				TargetPort:    portConfig.TargetPort,
				PublishedPort: portConfig.PublishedPort,
			})
		}
	}

	// Mode
	if s.Mode.Global != nil && s.Mode.Replicated != nil {
		return swarmapi.ServiceSpec{}, fmt.Errorf("cannot specify both replicated mode and global mode")
	}

	if s.Mode.Global != nil {
		spec.Mode = &swarmapi.ServiceSpec_Global{
			Global: &swarmapi.GlobalService{},
		}
	} else if s.Mode.Replicated != nil && s.Mode.Replicated.Replicas != nil {
		spec.Mode = &swarmapi.ServiceSpec_Replicated{
			Replicated: &swarmapi.ReplicatedService{Replicas: *s.Mode.Replicated.Replicas},
		}
	} else {
		spec.Mode = &swarmapi.ServiceSpec_Replicated{
			Replicated: &swarmapi.ReplicatedService{Replicas: 1},
		}
	}

	return spec, nil
}
977620
func (b *Backend) Secret(k string) *Secret {
	for _, s := range b.Secrets {
		if s.Type == k {
			return s
		}
	}

	return nil
}
1182302
func OptionSecret(s secrets.Secrets) Option {
	return func(cfg *config) {
		cfg.secret = s
	}
}
1284100
func (g *Guard) Secret(v []byte) (*Secret, error) {
	g.lock.Lock()
	defer g.lock.Unlock()

	b, err := memguard.NewMutableFromBytes(v)
	if err != nil {
		return nil, err
	}

	s := Secret{
		buffer: b,
		guard:  g,
	}

	g.secrets = append(g.secrets, &s)
	return &s, nil
}
1372274
func (p *Pod) GetSecretSource(name string) (string, error) {
	if val, ok := p.Secrets[name]; ok {
		return val.Source, nil
	}
	return "", fmt.Errorf("secret does not exist")
}
1312096
func (s *Server) globalRPC(method string, args interface{},
	reply structs.CompoundResponse) error {

	// Make a new request into each datacenter
	dcs := s.router.GetDatacenters()

	replies, total := 0, len(dcs)
	errorCh := make(chan error, total)
	respCh := make(chan interface{}, total)

	for _, dc := range dcs {
		go func(dc string) {
			rr := reply.New()
			if err := s.forwardDC(method, dc, args, &rr); err != nil {
				errorCh <- err
				return
			}
			respCh <- rr
		}(dc)
	}

	for replies < total {
		select {
		case err := <-errorCh:
			return err
		case rr := <-respCh:
			reply.Add(rr)
			replies++
		}
	}
	return nil
}
525197
func (c *RegionCache) GetRPCContext(bo *Backoffer, id RegionVerID) (*RPCContext, error) {
	c.mu.RLock()
	region := c.getCachedRegion(id)
	if region == nil {
		c.mu.RUnlock()
		return nil, nil
	}
	// Note: it is safe to use region.meta and region.peer without clone after
	// unlock, because region cache will never update the content of region's meta
	// or peer. On the contrary, if we want to use `region` after unlock, then we
	// need to clone it to avoid data race.
	meta, peer := region.meta, region.peer
	c.mu.RUnlock()

	addr, err := c.GetStoreAddr(bo, peer.GetStoreId())
	if err != nil {
		return nil, errors.Trace(err)
	}
	if addr == "" {
		// Store not found, region must be out of date.
		c.DropRegion(id)
		return nil, nil
	}
	return &RPCContext{
		Region: id,
		Meta:   meta,
		Peer:   peer,
		Addr:   addr,
	}, nil
}
72512
func (s *SecretService) PutSecret(ctx context.Context, orgID influxdb.ID, key string, val string) error {
	if err := authorizeWriteSecret(ctx, orgID); err != nil {
		return err
	}

	err := s.s.PutSecret(ctx, orgID, key, val)
	if err != nil {
		return err
	}

	return nil
}
565914
func (s *SecretService) PutSecret(ctx context.Context, orgID platform.ID, k string, v string) error {
	data, ver, err := s.loadSecrets(ctx, orgID)
	if err != nil {
		return err
	}

	data[k] = v

	return s.putSecrets(ctx, orgID, data, ver)
}
1288248
func (e *DockercfgTokenDeletedController) findDockercfgSecrets(tokenSecret *v1.Secret) ([]*v1.Secret, error) {
	dockercfgSecrets := []*v1.Secret{}

	options := metav1.ListOptions{FieldSelector: fields.OneTermEqualSelector(api.SecretTypeField, string(v1.SecretTypeDockercfg)).String()}
	potentialSecrets, err := e.client.CoreV1().Secrets(tokenSecret.Namespace).List(options)
	if err != nil {
		return nil, err
	}

	for i, currSecret := range potentialSecrets.Items {
		if currSecret.Annotations[ServiceAccountTokenSecretNameKey] == tokenSecret.Name {
			dockercfgSecrets = append(dockercfgSecrets, &potentialSecrets.Items[i])
		}
	}

	return dockercfgSecrets, nil
}
31067
func secretFromSecretSpec(spec *api.SecretSpec) *api.Secret {
	return &api.Secret{
		ID:   identity.NewID(),
		Spec: *spec,
	}
}
475628
func parseSecret(namespace, secretName string, kubeClient clientset.Interface) (string, error) {
	secretMap, err := volutil.GetSecretForPV(namespace, secretName, glusterfsPluginName, kubeClient)
	if err != nil {
		klog.Errorf("failed to get secret: %s/%s: %v", namespace, secretName, err)
		return "", fmt.Errorf("failed to get secret %s/%s: %v", namespace, secretName, err)
	}
	if len(secretMap) == 0 {
		return "", fmt.Errorf("empty secret map")
	}
	secret := ""
	for k, v := range secretMap {
		if k == secretKeyName {
			return v, nil
		}
		secret = v
	}

	// If not found, the last secret in the map wins as done before
	return secret, nil
}
76623
func scanSecrets(r io.Reader) ([]secretPair, error) {
	var pairs []secretPair

	lexer := shlex.NewLexer(r)

	for {
		word, err := lexer.Next()
		if err != nil {
			if err == io.EOF {
				return pairs, nil
			}
			return nil, fmt.Errorf("Error reading input file. %s", err)
		}

		tokens := strings.SplitN(word, "=", 2)
		if len(tokens) < 2 {
			return nil, fmt.Errorf("Error parsing secret %q", word)
		}

		key := tokens[0]
		value := tokens[1]

		if key == "" || value == "" {
			return nil, fmt.Errorf("Error parsing secret %q", word)
		}

		pairs = append(pairs, secretPair{key: key, value: value})
	}
}
1210050
func (c *Cluster) UpdateSecret(input string, version uint64, spec types.SecretSpec) error {
	return c.lockedManagerAction(func(ctx context.Context, state nodeState) error {
		secret, err := getSecret(ctx, state.controlClient, input)
		if err != nil {
			return err
		}

		secretSpec := convert.SecretSpecToGRPC(spec)

		_, err = state.controlClient.UpdateSecret(ctx,
			&swarmapi.UpdateSecretRequest{
				SecretID: secret.ID,
				SecretVersion: &swarmapi.Version{
					Index: version,
				},
				Spec: &secretSpec,
			})
		return err
	})
}