parse.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package service
  2. import (
  3. "fmt"
  4. "github.com/docker/docker/api/types"
  5. "github.com/docker/docker/api/types/filters"
  6. swarmtypes "github.com/docker/docker/api/types/swarm"
  7. "github.com/docker/docker/client"
  8. "golang.org/x/net/context"
  9. )
  10. // ParseSecrets retrieves the secrets with the requested names and fills
  11. // secret IDs into the secret references.
  12. func ParseSecrets(client client.SecretAPIClient, requestedSecrets []*swarmtypes.SecretReference) ([]*swarmtypes.SecretReference, error) {
  13. secretRefs := make(map[string]*swarmtypes.SecretReference)
  14. ctx := context.Background()
  15. for _, secret := range requestedSecrets {
  16. if _, exists := secretRefs[secret.File.Name]; exists {
  17. return nil, fmt.Errorf("duplicate secret target for %s not allowed", secret.SecretName)
  18. }
  19. secretRef := new(swarmtypes.SecretReference)
  20. *secretRef = *secret
  21. secretRefs[secret.File.Name] = secretRef
  22. }
  23. args := filters.NewArgs()
  24. for _, s := range secretRefs {
  25. args.Add("names", s.SecretName)
  26. }
  27. secrets, err := client.SecretList(ctx, types.SecretListOptions{
  28. Filters: args,
  29. })
  30. if err != nil {
  31. return nil, err
  32. }
  33. foundSecrets := make(map[string]string)
  34. for _, secret := range secrets {
  35. foundSecrets[secret.Spec.Annotations.Name] = secret.ID
  36. }
  37. addedSecrets := []*swarmtypes.SecretReference{}
  38. for _, ref := range secretRefs {
  39. id, ok := foundSecrets[ref.SecretName]
  40. if !ok {
  41. return nil, fmt.Errorf("secret not found: %s", ref.SecretName)
  42. }
  43. // set the id for the ref to properly assign in swarm
  44. // since swarm needs the ID instead of the name
  45. ref.SecretID = id
  46. addedSecrets = append(addedSecrets, ref)
  47. }
  48. return addedSecrets, nil
  49. }