/
main.go
233 lines (196 loc) · 4.98 KB
/
main.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
package main
import (
"fmt"
"log"
"os"
"time"
docker "github.com/fsouza/go-dockerclient"
kingpin "gopkg.in/alecthomas/kingpin.v1"
)
var (
client *docker.Client
dockerVersion *docker.Env
debug bool
forceRemoveImages bool
containers = ContainerList{make(map[string]*docker.APIContainers), make(map[string]*docker.APIContainers)}
images = ImageList{make(map[string]*docker.APIImages), make(map[string]*docker.APIImages)}
)
type ImageList struct {
byID map[string]*docker.APIImages
byRepoTag map[string]*docker.APIImages
}
func (l ImageList) Add(image *docker.APIImages) {
l.byID[shortID(image.ID)] = image
for _, repoTag := range image.RepoTags {
if !repoTagIsNone(repoTag) {
l.byRepoTag[repoTag] = image
}
}
}
func (l ImageList) FindByID(id string) (img *docker.APIImages, ok bool) {
img, ok = l.byID[id]
return
}
func (l ImageList) FindByRepoTag(repoTag string) (img *docker.APIImages, ok bool) {
img, ok = l.byRepoTag[repoTag]
return
}
func (l ImageList) Iterator() chan *docker.APIImages {
out := make(chan *docker.APIImages)
go func() {
for _, img := range l.byID {
out <- img
}
close(out)
}()
return out
}
func (l ImageList) Print() {
for k, v := range l.byID {
fmt.Printf("%s =>\n %s\n", k, v)
}
}
type ContainerList struct {
byID map[string]*docker.APIContainers
byName map[string]*docker.APIContainers
}
func (l ContainerList) FindByID(id string) (c *docker.APIContainers, ok bool) {
c, ok = l.byID[id]
return
}
func (l ContainerList) FindByName(name string) (c *docker.APIContainers, ok bool) {
c, ok = l.byName[name]
return
}
func (l ContainerList) Add(container *docker.APIContainers) {
l.byID[shortID(container.ID)] = container
for _, name := range container.Names {
l.byName[name] = container
}
}
func (l ContainerList) Iterator() chan *docker.APIContainers {
out := make(chan *docker.APIContainers)
go func() {
for _, img := range l.byID {
out <- img
}
close(out)
}()
return out
}
func (l ContainerList) Print() {
for k, v := range l.byID {
fmt.Printf("%s =>\n %s\n", k, v)
}
}
func getContainers(cntList *ContainerList) {
options := docker.ListContainersOptions{All: true}
cnts, err := client.ListContainers(options)
if err != nil {
log.Fatal("client.ListContainers(", options, "): ", err)
}
for i := range cnts {
cntList.Add(&cnts[i])
}
if debug {
cntList.Print()
}
}
func getImages(imgList *ImageList) {
imgs, err := client.ListImages(false)
if err != nil {
log.Fatal("client.ListImages(false): ", err)
}
for i := range imgs {
imgList.Add(&imgs[i])
}
if debug {
imgList.Print()
}
}
func createClient() {
var (
dockerEndpoint string
err error
)
if dockerEndpoint = os.Getenv("DOCKER_HOST"); len(dockerEndpoint) == 0 {
dockerEndpoint = "unix:///var/run/docker.sock"
}
if debug {
log.Println("Connecting to Docker daemon via:", dockerEndpoint)
}
client, err = docker.NewClient(dockerEndpoint)
if err != nil {
log.Fatal(err)
}
dockerVersion, err = client.Version()
if err != nil {
log.Fatal("Could not connect to Docker daemon: ", err)
}
if debug {
showDockerVersion()
}
}
func showDockerVersion() {
fmt.Println("Docker daemon info:")
for key, value := range dockerVersion.Map() {
fmt.Printf(" %-15s : %s\n", key, value)
}
}
func cleanupImages() {
getImages(&images)
for img := range images.Iterator() {
if len(img.RepoTags) == 1 && repoTagIsNone(img.RepoTags[0]) {
log.Printf("removing image %s", shortID(img.ID))
if err := client.RemoveImage(img.ID); err != nil {
log.Println(err)
}
}
}
}
func cleanupContainers() {
getContainers(&containers)
getImages(&images)
var options = docker.RemoveContainerOptions{RemoveVolumes: true}
for c := range containers.Iterator() {
// if the Image doesn't refer to a repoTag, the container should be removed
if _, ok := images.FindByRepoTag(c.Image); !ok {
log.Printf("removing container %s based on image %s", shortID(c.ID), c.Image)
options.ID = c.ID
if err := client.RemoveContainer(options); err != nil {
log.Println(err)
}
}
}
}
func logDockerEvents(events <-chan *docker.APIEvents) {
for {
e := <-events
log.Printf("daemon: %s %s %s", e.From, e.Status, e.ID)
}
}
func repoTagIsNone(tagName string) bool {
return tagName == "<none>:<none>"
}
func shortID(id string) string {
return id[0:12]
}
func main() {
kingpin.Flag("debug", "Show extra info").BoolVar(&debug)
kingpin.Command("cleanup-images", "Cleanup any untagged images")
kingpin.Command("cleanup-containers", "Cleanup any containers based on untagged images")
command := kingpin.Parse() // get selected command or die here
createClient()
// Log events from the Daemon
var events = make(chan *docker.APIEvents)
client.AddEventListener(events)
go logDockerEvents(events)
switch command {
case "cleanup-images":
cleanupImages()
case "cleanup-containers":
cleanupContainers()
}
// FIXME: Wait a short moment for any last Daemon events to come back
time.Sleep(time.Second * 1)
}