utils.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package secret
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/api/types/filters"
  7. "github.com/docker/docker/api/types/swarm"
  8. "github.com/docker/docker/client"
  9. "golang.org/x/net/context"
  10. )
  11. func getSecretsByNameOrIDPrefixes(ctx context.Context, client client.APIClient, terms []string) ([]swarm.Secret, error) {
  12. args := filters.NewArgs()
  13. for _, n := range terms {
  14. args.Add("names", n)
  15. args.Add("id", n)
  16. }
  17. return client.SecretList(ctx, types.SecretListOptions{
  18. Filters: args,
  19. })
  20. }
  21. func getCliRequestedSecretIDs(ctx context.Context, client client.APIClient, terms []string) ([]string, error) {
  22. secrets, err := getSecretsByNameOrIDPrefixes(ctx, client, terms)
  23. if err != nil {
  24. return nil, err
  25. }
  26. if len(secrets) > 0 {
  27. found := make(map[string]struct{})
  28. next:
  29. for _, term := range terms {
  30. // attempt to lookup secret by full ID
  31. for _, s := range secrets {
  32. if s.ID == term {
  33. found[s.ID] = struct{}{}
  34. continue next
  35. }
  36. }
  37. // attempt to lookup secret by full name
  38. for _, s := range secrets {
  39. if s.Spec.Annotations.Name == term {
  40. found[s.ID] = struct{}{}
  41. continue next
  42. }
  43. }
  44. // attempt to lookup secret by partial ID (prefix)
  45. // return error if more than one matches found (ambiguous)
  46. n := 0
  47. for _, s := range secrets {
  48. if strings.HasPrefix(s.ID, term) {
  49. found[s.ID] = struct{}{}
  50. n++
  51. }
  52. }
  53. if n > 1 {
  54. return nil, fmt.Errorf("secret %s is ambiguous (%d matches found)", term, n)
  55. }
  56. }
  57. // We already collected all the IDs found.
  58. // Now we will remove duplicates by converting the map to slice
  59. ids := []string{}
  60. for id := range found {
  61. ids = append(ids, id)
  62. }
  63. return ids, nil
  64. }
  65. return terms, nil
  66. }