forked from krystal/guvnor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cleanup.go
86 lines (77 loc) · 1.73 KB
/
cleanup.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
package guvnor
import (
"context"
"fmt"
"strconv"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"go.uber.org/zap"
)
type CleanupArgs struct {
ServiceName string
}
func (e *Engine) Cleanup(ctx context.Context, args CleanupArgs) error {
svc, err := e.loadServiceConfig(args.ServiceName)
if err != nil {
return err
}
svcState, err := e.state.LoadServiceState(svc.Name)
if err != nil {
return err
}
e.log.Debug(
"finding process containers for service",
zap.String("service", svc.Name),
)
serviceFilter := fmt.Sprintf("%s=%s", serviceLabel, svc.Name)
serviceProcessContainers, err := e.docker.ContainerList(
ctx,
types.ContainerListOptions{
All: true,
Filters: filters.NewArgs(
filters.Arg("label", managedLabel),
filters.Arg("label", serviceFilter),
// Ensure they are affiliated with a process
filters.Arg("label", processLabel),
),
},
)
if err != nil {
return err
}
e.log.Debug(
"found process containers for service",
zap.String("service", svc.Name),
zap.Int("count", len(serviceProcessContainers)),
)
deleteCount := 0
for _, container := range serviceProcessContainers {
deploy, ok := container.Labels[deploymentLabel]
if !ok {
continue
}
if deploy != strconv.Itoa(svcState.DeploymentID) {
e.log.Debug(
"zombie container found; removing",
zap.String("service", svc.Name),
zap.String("container", container.ID),
)
err = e.docker.ContainerRemove(
ctx,
container.ID,
types.ContainerRemoveOptions{
Force: true,
},
)
if err != nil {
return err
}
deleteCount++
}
}
e.log.Debug("deleted zombie containers",
zap.String("service", svc.Name),
zap.Int("count", deleteCount),
)
return nil
}