utils.go 1.8 KB

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