-
Notifications
You must be signed in to change notification settings - Fork 0
/
container.go
213 lines (167 loc) · 5.69 KB
/
container.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package ec2metaproxy
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
log "github.com/flyinprogrammer/ec2metaproxy/Godeps/_workspace/src/github.com/cihub/seelog"
"github.com/flyinprogrammer/ec2metaproxy/Godeps/_workspace/src/github.com/fsouza/go-dockerclient"
"github.com/flyinprogrammer/ec2metaproxy/Godeps/_workspace/src/github.com/goamz/goamz/aws"
)
const (
maxSessionNameLen int = 32
credentialsRefreshPeriod time.Duration = 30 * time.Second
)
var (
// matches char that is not valid in a STS role session name
invalidSessionNameRegexp = regexp.MustCompile(`[^\w+=,.@-]`)
)
type ContainerInfo struct {
ContainerID string
ShortContainerID string
SessionName string
LastUpdated time.Time
Error error
RoleArn RoleArn
Credentials *RoleCredentials
}
func (t *ContainerInfo) RequiresRefresh() bool {
if t.RoleArn.Empty() {
return false
}
if t.Credentials != nil {
return t.Credentials.ExpiredNow()
}
return time.Since(t.LastUpdated) > credentialsRefreshPeriod
}
type ContainerRole struct {
LastUpdated time.Time
Arn RoleArn
Credentials *RoleCredentials
}
type ContainerService struct {
containerIPMap map[string]*ContainerInfo
containerIDMap map[string]string // container id => container IP
docker *docker.Client
defaultRoleArn RoleArn
auth aws.Auth
lock sync.Mutex
}
func NewContainerService(docker *docker.Client, defaultRoleArn RoleArn, auth aws.Auth) *ContainerService {
return &ContainerService{
containerIPMap: make(map[string]*ContainerInfo),
containerIDMap: make(map[string]string),
docker: docker,
defaultRoleArn: defaultRoleArn,
auth: auth,
}
}
func (t *ContainerService) RoleForIP(containerIP string) (*ContainerRole, error) {
t.lock.Lock()
defer t.lock.Unlock()
info, err := t.containerForIP(containerIP)
if err != nil {
return nil, err
}
if info.RequiresRefresh() {
log.Infof("Refreshing role for container %s: role=%s session=%s", info.ShortContainerID, info.RoleArn, info.SessionName)
creds, err := AssumeRole(t.auth, info.RoleArn.String(), info.SessionName)
info.LastUpdated = time.Now()
info.Error = err
info.Credentials = creds
}
if info.Error != nil {
return nil, info.Error
}
return &ContainerRole{info.LastUpdated, info.RoleArn, info.Credentials}, nil
}
func (t *ContainerService) containerForIP(containerIP string) (*ContainerInfo, error) {
info, found := t.containerIPMap[containerIP]
if !found {
t.syncContainers()
info, found = t.containerIPMap[containerIP]
if !found {
return nil, fmt.Errorf("No container found for IP %s", containerIP)
}
}
return info, nil
}
func (t *ContainerService) syncContainers() {
log.Info("Synchronizing state with running docker containers")
apiContainers, err := t.docker.ListContainers(docker.ListContainersOptions{
All: false, // only running containers
Size: false, // do not need size information
Limit: 0, // all running containers
Since: "", // not applicable
Before: "", // not applicable
})
if err != nil {
log.Error("Error listing running containers: ", err)
return
}
containerIPMap := make(map[string]*ContainerInfo)
containerIDMap := make(map[string]string)
for _, apiContainer := range apiContainers {
container, err := t.docker.InspectContainer(apiContainer.ID)
if err != nil {
log.Error("Error inspecting container: ", apiContainer.ID, ": ", err)
continue
}
shortContainerID := apiContainer.ID[:6]
containerIP := container.NetworkSettings.IPAddress
roleArn, roleErr := getRoleArnFromEnv(container.Config.Env, t.defaultRoleArn)
if roleArn.Empty() && roleErr == nil {
roleErr = fmt.Errorf("No role defined for container %s: image=%s", shortContainerID, container.Config.Image)
}
log.Infof("Container: id=%s image=%s role=%s", shortContainerID, container.Config.Image, roleArn)
containerIPMap[containerIP] = &ContainerInfo{
ContainerID: apiContainer.ID,
ShortContainerID: shortContainerID,
SessionName: generateSessionName(container),
LastUpdated: time.Time{},
Error: roleErr,
RoleArn: roleArn,
}
containerIDMap[apiContainer.ID] = containerIP
}
t.containerIPMap = containerIPMap
t.containerIDMap = containerIDMap
}
func getRoleArnFromEnv(env []string, defaultArn RoleArn) (RoleArn, error) {
for _, e := range env {
v := strings.SplitN(e, "=", 2)
if len(v) > 1 && v[0] == "IAM_ROLE" && len(v[1]) > 0 {
return NewRoleArn(v[1])
}
}
return defaultArn, nil
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
func generateSessionName(container *docker.Container) string {
containerID := container.ID[:6]
remaining := maxSessionNameLen - (len(containerID) + 2) // 2 chars for separators
containerName := container.Name[1:] // Strip '/' prefix
imageName := container.Config.Image
// Split the remaining number of characters between container and image name.
// If one or the other is shcontainerIDMapcontainerIDMaporter than half the remaining, give the available
// chars to the other string.
// Trim container name
containerNameLen := remaining / 2
containerNameLen = (containerNameLen + maxInt(0, containerNameLen-len(imageName)))
if containerNameLen < len(containerName) {
containerName = containerName[len(containerName)-containerNameLen:]
}
// Trim image name
imageNameLen := (remaining + 1) / 2 // If odd, image name gets the extra char
imageNameLen = (imageNameLen + maxInt(0, imageNameLen-len(containerName)))
if imageNameLen < len(imageName) {
imageName = imageName[len(imageName)-imageNameLen:]
}
return invalidSessionNameRegexp.ReplaceAllString(fmt.Sprintf("%s-%s-%s", imageName, containerName, containerID), "_")
}