This repository has been archived by the owner on Jul 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
container.go
93 lines (74 loc) · 2.53 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
package main
import (
"log"
"regexp"
"sort"
"strings"
docker "github.com/fsouza/go-dockerclient"
)
var IsID = regexp.MustCompile("^[0-9a-f]{12,}$")
// FilterContainer is a filter func returns true if the container should be added to list.
type FilterContainer func(apicontainer *docker.APIContainers) bool
func (deployer *Deployer) FindContainers(options docker.ListContainersOptions, filter FilterContainer) ([]docker.APIContainers, error) {
apicontainers, err := deployer.docker.ListContainers(options)
if err != nil {
return nil, err
}
ret := make([]docker.APIContainers, 0, len(apicontainers))
for i := range apicontainers {
apicontainer := &apicontainers[i]
if filter(apicontainer) {
ret = append(ret, *apicontainer)
}
}
return ret, nil
}
func (deployer *Deployer) InspectContainer(id string) (*docker.Container, error) {
return deployer.docker.InspectContainerWithOptions(docker.InspectContainerOptions{ID: id})
}
func (deployer *Deployer) StopContainers(containers []docker.APIContainers) {
names := []string{}
for i := range containers {
container := &containers[i]
log.Println("Stopping container", container.ID, container.Names)
names = append(names, container.Names...)
err := deployer.docker.StopContainer(container.ID, deployer.killTimeout)
if err != nil {
log.Println("Stop container", err)
}
}
if slack != nil && len(names) > 0 {
sort.Strings(names)
// Container Names are prefixed by "/".
text := "Deploying " + strings.ReplaceAll(strings.TrimPrefix(strings.Join(names, " "), "/"), " /", ", ")
if err := slack.Send(SlackPayload{Text: text}); err != nil {
log.Println("Slack error: ", err)
}
}
}
func (deployer *Deployer) FindStaleContainers() ([]docker.APIContainers, error) {
repotagMap, err := deployer.ListRepotags()
if err != nil {
return nil, err
}
filter := func(apicontainer *docker.APIContainers) bool {
// If image is an ID, it means the tag got reassigned.
if IsID.MatchString(apicontainer.Image) {
return true
}
// Otherwise, apicontainer.ID is a repotag. Make sure image container is running is still current.
if container, err := deployer.InspectContainer(apicontainer.ID); err == nil && repotagMap[apicontainer.Image] != container.Image {
return true
}
return false
}
return deployer.FindContainers(docker.ListContainersOptions{}, filter)
}
func (deployer *Deployer) StopStaleContainers() {
containers, err := deployer.FindStaleContainers()
if err != nil {
log.Println("FindStaleContainers", err)
return
}
deployer.StopContainers(containers)
}