forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker.go
347 lines (314 loc) · 9.57 KB
/
docker.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package rkeworker
import (
"context"
"fmt"
"io"
"reflect"
"runtime"
"strings"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/rancher/rke/hosts"
"github.com/rancher/rke/services"
"github.com/rancher/types/apis/management.cattle.io/v3"
"github.com/sirupsen/logrus"
)
const (
RKEContainerNameLabel = "io.rancher.rke.container.name"
CattleProcessNameLabel = "io.cattle.process.name"
)
type NodeConfig struct {
ClusterName string `json:"clusterName"`
Certs string `json:"certs"`
Processes map[string]v3.Process `json:"processes"`
Files []v3.File `json:"files"`
}
func runProcess(ctx context.Context, name string, p v3.Process, start bool) error {
c, err := client.NewEnvClient()
if err != nil {
return err
}
defer c.Close()
args := filters.NewArgs()
args.Add("label", RKEContainerNameLabel+"="+name)
// to handle upgrades of old container
oldArgs := filters.NewArgs()
oldArgs.Add("label", CattleProcessNameLabel+"="+name)
containers, err := c.ContainerList(ctx, types.ContainerListOptions{
All: true,
Filters: args,
})
if err != nil {
return err
}
oldContainers, err := c.ContainerList(ctx, types.ContainerListOptions{
All: true,
Filters: oldArgs,
})
if err != nil {
return err
}
containers = append(containers, oldContainers...)
var matchedContainers []types.Container
for _, container := range containers {
changed, err := changed(ctx, c, p, container)
if err != nil {
return err
}
if changed {
err := remove(ctx, c, container.ID)
if err != nil {
return err
}
} else {
matchedContainers = append(matchedContainers, container)
}
}
for i := 1; i < len(matchedContainers); i++ {
if err := remove(ctx, c, matchedContainers[i].ID); err != nil {
return err
}
}
if len(matchedContainers) > 0 {
if strings.Contains(name, "share-mnt") {
inspect, err := c.ContainerInspect(ctx, matchedContainers[0].ID)
if err != nil {
return err
}
if inspect.State != nil && inspect.State.Status == "exited" && inspect.State.ExitCode == 0 {
return nil
}
}
c.ContainerStart(ctx, matchedContainers[0].ID, types.ContainerStartOptions{})
if !strings.Contains(name, "share-mnt") {
runLogLinker(ctx, c, name, p)
}
return nil
}
config, hostConfig, _ := services.GetProcessConfig(p)
if config.Labels == nil {
config.Labels = map[string]string{}
}
config.Labels[RKEContainerNameLabel] = name
newContainer, err := c.ContainerCreate(ctx, config, hostConfig, nil, name)
if client.IsErrNotFound(err) {
var output io.ReadCloser
imagePullOptions := types.ImagePullOptions{}
if p.ImageRegistryAuthConfig != "" {
imagePullOptions.RegistryAuth = p.ImageRegistryAuthConfig
imagePullOptions.PrivilegeFunc = func() (string, error) { return p.ImageRegistryAuthConfig, nil }
}
output, err = c.ImagePull(ctx, config.Image, imagePullOptions)
if err != nil {
return err
}
defer output.Close()
io.Copy(logrus.StandardLogger().Writer(), output)
newContainer, err = c.ContainerCreate(ctx, config, hostConfig, nil, name)
}
if err == nil && start {
if err := c.ContainerStart(ctx, newContainer.ID, types.ContainerStartOptions{}); err != nil {
return err
}
if !strings.Contains(name, "share-mnt") {
return runLogLinker(ctx, c, name, p)
}
return nil
}
return err
}
func remove(ctx context.Context, c *client.Client, id string) error {
return c.ContainerRemove(ctx, id, types.ContainerRemoveOptions{
Force: true,
RemoveVolumes: true,
})
}
func changed(ctx context.Context, c *client.Client, expectedProcess v3.Process, container types.Container) (bool, error) {
actualDockerInspect, err := c.ContainerInspect(ctx, container.ID)
if err != nil {
return false, err
}
defaultDockerInspect, _, err := c.ImageInspectWithRaw(ctx, actualDockerInspect.Image)
if err != nil {
return false, err
}
actualProcess := v3.Process{
Command: actualDockerInspect.Config.Entrypoint,
Args: actualDockerInspect.Config.Cmd,
Env: actualDockerInspect.Config.Env,
Image: actualDockerInspect.Config.Image,
Binds: actualDockerInspect.HostConfig.Binds,
NetworkMode: string(actualDockerInspect.HostConfig.NetworkMode),
PidMode: string(actualDockerInspect.HostConfig.PidMode),
Privileged: actualDockerInspect.HostConfig.Privileged,
VolumesFrom: actualDockerInspect.HostConfig.VolumesFrom,
Labels: actualDockerInspect.Config.Labels,
}
if len(expectedProcess.Command) == 0 {
expectedProcess.Command = actualProcess.Command
}
if len(expectedProcess.Args) == 0 {
expectedProcess.Args = actualProcess.Args
}
if len(expectedProcess.Env) == 0 {
expectedProcess.Env = actualProcess.Env
}
if expectedProcess.NetworkMode == "" {
expectedProcess.NetworkMode = actualProcess.NetworkMode
}
if expectedProcess.PidMode == "" {
expectedProcess.PidMode = actualProcess.PidMode
}
if len(expectedProcess.Labels) == 0 {
expectedProcess.Labels = actualProcess.Labels
}
// Don't detect changes on these fields
actualProcess.Name = expectedProcess.Name
actualProcess.HealthCheck.URL = expectedProcess.HealthCheck.URL
actualProcess.RestartPolicy = expectedProcess.RestartPolicy
actualProcess.ImageRegistryAuthConfig = expectedProcess.ImageRegistryAuthConfig
changed := false
t := reflect.TypeOf(actualProcess)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
if f.Name == "Command" {
leftMap := sliceToMap(expectedProcess.Command)
rightMap := sliceToMap(actualProcess.Command)
if reflect.DeepEqual(leftMap, rightMap) {
continue
}
} else if f.Name == "Env" {
expectedEnvs := make(map[string]string, 8)
for _, env := range defaultDockerInspect.Config.Env {
es := strings.SplitN(env, "=", 2)
if len(es) == 2 {
expectedEnvs[es[0]] = es[1]
}
}
for _, env := range expectedProcess.Env {
es := strings.SplitN(env, "=", 2)
if len(es) == 2 {
expectedEnvs[es[0]] = es[1]
} else {
expectedEnvs[es[0]] = "_host_related_env_"
}
}
actualEnvs := make(map[string]string, 8)
for _, env := range actualProcess.Env {
es := strings.SplitN(env, "=", 2)
if len(es) == 2 {
actualEnvs[es[0]] = es[1]
}
}
isNothingChange := true
for expectedEnvName, expectedEnvVal := range expectedEnvs {
if expectedEnvVal == "_host_related_env_" {
continue
}
if expectedEnvVal != actualEnvs[expectedEnvName] {
isNothingChange = false
break
}
}
if isNothingChange {
continue
}
} else if f.Name == "Labels" {
processLabels := make(map[string]string)
for k, v := range defaultDockerInspect.Config.Labels {
processLabels[k] = v
}
for k, v := range expectedProcess.Labels {
processLabels[k] = v
}
if reflect.DeepEqual(processLabels, actualProcess.Labels) {
continue
}
} else if f.Name == "Publish" {
expectedExposedPortSet, expectedBindings, err := nat.ParsePortSpecs(reflect.ValueOf(expectedProcess).Field(i).Interface().([]string))
if err != nil {
return false, err
}
expectedExposedPorts := natPortSetToSlice(expectedExposedPortSet)
nat.SortPortMap(expectedExposedPorts, expectedBindings)
actualExposedPortSet := make(map[nat.Port]struct{}, 0)
actualBindings := actualDockerInspect.HostConfig.PortBindings
for port := range actualBindings {
if _, exists := actualExposedPortSet[port]; !exists {
actualExposedPortSet[port] = struct{}{}
}
}
actualExposedPorts := natPortSetToSlice(actualExposedPortSet)
nat.SortPortMap(actualExposedPorts, actualBindings)
if reflect.DeepEqual(actualBindings, nat.PortMap(expectedBindings)) {
continue
}
}
left := reflect.ValueOf(actualProcess).Field(i).Interface()
right := reflect.ValueOf(expectedProcess).Field(i).Interface()
if !reflect.DeepEqual(left, right) {
logrus.Infof("For process %s, %s has changed from %v to %v", expectedProcess.Name, f.Name, right, left)
changed = true
}
}
return changed, nil
}
func sliceToMap(args []string) map[string]bool {
result := map[string]bool{}
for _, arg := range args {
result[arg] = true
}
return result
}
func natPortSetToSlice(args map[nat.Port]struct{}) []nat.Port {
result := make([]nat.Port, 0, len(args))
for arg := range args {
result = append(result, arg)
}
return result
}
func runLogLinker(ctx context.Context, c *client.Client, containerName string, p v3.Process) error {
if ignoreWindows() {
return nil
}
inspect, err := c.ContainerInspect(ctx, containerName)
if err != nil {
return err
}
containerID := inspect.ID
containerLogPath := inspect.LogPath
containerLogLink := fmt.Sprintf("%s/%s_%s.log", hosts.RKELogsPath, containerName, containerID)
logLinkerName := fmt.Sprintf("%s-%s", services.LogLinkContainerName, containerName)
config := &container.Config{
Image: p.Image,
Tty: true,
Entrypoint: []string{
"sh",
"-c",
fmt.Sprintf("mkdir -p %s ; ln -s %s %s", hosts.RKELogsPath, containerLogPath, containerLogLink),
},
}
hostConfig := &container.HostConfig{
Binds: []string{
"/var/lib:/var/lib",
},
Privileged: true,
}
// remove log linker if its already exists
remove(ctx, c, logLinkerName)
newContainer, err := c.ContainerCreate(ctx, config, hostConfig, nil, logLinkerName)
if err != nil {
return err
}
if err := c.ContainerStart(ctx, newContainer.ID, types.ContainerStartOptions{}); err != nil {
return err
}
// remove log linker after start
return remove(ctx, c, logLinkerName)
}
func ignoreWindows() bool {
return runtime.GOOS == "windows"
}