idresolver.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package idresolver
  2. import (
  3. "fmt"
  4. "golang.org/x/net/context"
  5. "github.com/docker/engine-api/client"
  6. "github.com/docker/engine-api/types/swarm"
  7. )
  8. // IDResolver provides ID to Name resolution.
  9. type IDResolver struct {
  10. client client.APIClient
  11. noResolve bool
  12. cache map[string]string
  13. }
  14. // New creates a new IDResolver.
  15. func New(client client.APIClient, noResolve bool) *IDResolver {
  16. return &IDResolver{
  17. client: client,
  18. noResolve: noResolve,
  19. cache: make(map[string]string),
  20. }
  21. }
  22. func (r *IDResolver) get(ctx context.Context, t interface{}, id string) (string, error) {
  23. switch t.(type) {
  24. case swarm.Node:
  25. node, _, err := r.client.NodeInspectWithRaw(ctx, id)
  26. if err != nil {
  27. return id, nil
  28. }
  29. if node.Spec.Annotations.Name != "" {
  30. return node.Spec.Annotations.Name, nil
  31. }
  32. if node.Description.Hostname != "" {
  33. return node.Description.Hostname, nil
  34. }
  35. return id, nil
  36. case swarm.Service:
  37. service, _, err := r.client.ServiceInspectWithRaw(ctx, id)
  38. if err != nil {
  39. return id, nil
  40. }
  41. return service.Spec.Annotations.Name, nil
  42. default:
  43. return "", fmt.Errorf("unsupported type")
  44. }
  45. }
  46. // Resolve will attempt to resolve an ID to a Name by querying the manager.
  47. // Results are stored into a cache.
  48. // If the `-n` flag is used in the command-line, resolution is disabled.
  49. func (r *IDResolver) Resolve(ctx context.Context, t interface{}, id string) (string, error) {
  50. if r.noResolve {
  51. return id, nil
  52. }
  53. if name, ok := r.cache[id]; ok {
  54. return name, nil
  55. }
  56. name, err := r.get(ctx, t, id)
  57. if err != nil {
  58. return "", err
  59. }
  60. r.cache[id] = name
  61. return name, nil
  62. }