-
Notifications
You must be signed in to change notification settings - Fork 18.6k
/
idresolver.go
90 lines (81 loc) · 2.1 KB
/
idresolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package idresolver
import (
"fmt"
"golang.org/x/net/context"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/stringid"
)
// IDResolver provides ID to Name resolution.
type IDResolver struct {
client client.APIClient
noResolve bool
cache map[string]string
}
// New creates a new IDResolver.
func New(client client.APIClient, noResolve bool) *IDResolver {
return &IDResolver{
client: client,
noResolve: noResolve,
cache: make(map[string]string),
}
}
func (r *IDResolver) get(ctx context.Context, t interface{}, id string) (string, error) {
switch t := t.(type) {
case swarm.Node:
node, _, err := r.client.NodeInspectWithRaw(ctx, id)
if err != nil {
return id, nil
}
if node.Spec.Annotations.Name != "" {
return node.Spec.Annotations.Name, nil
}
if node.Description.Hostname != "" {
return node.Description.Hostname, nil
}
return id, nil
case swarm.Service:
service, _, err := r.client.ServiceInspectWithRaw(ctx, id)
if err != nil {
return id, nil
}
return service.Spec.Annotations.Name, nil
case swarm.Task:
// If the caller passes the full task there's no need to do a lookup.
if t.ID == "" {
var err error
t, _, err = r.client.TaskInspectWithRaw(ctx, id)
if err != nil {
return id, nil
}
}
taskID := stringid.TruncateID(t.ID)
if t.ServiceID == "" {
return taskID, nil
}
service, err := r.Resolve(ctx, swarm.Service{}, t.ServiceID)
if err != nil {
return "", err
}
return fmt.Sprintf("%s.%d.%s", service, t.Slot, taskID), nil
default:
return "", fmt.Errorf("unsupported type")
}
}
// Resolve will attempt to resolve an ID to a Name by querying the manager.
// Results are stored into a cache.
// If the `-n` flag is used in the command-line, resolution is disabled.
func (r *IDResolver) Resolve(ctx context.Context, t interface{}, id string) (string, error) {
if r.noResolve {
return id, nil
}
if name, ok := r.cache[id]; ok {
return name, nil
}
name, err := r.get(ctx, t, id)
if err != nil {
return "", err
}
r.cache[id] = name
return name, nil
}