-
Notifications
You must be signed in to change notification settings - Fork 7
/
gc.go
283 lines (253 loc) · 7.95 KB
/
gc.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
/**
* Copyright 2015 Nicolas De Loof
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"context"
"flag"
"github.com/boltdb/bolt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
log "github.com/sirupsen/logrus"
"os"
"path"
"strings"
"time"
)
var (
cli *client.Client
db *bolt.DB
dbPath = flag.String("db", "/var/db/docker-gc/state.db", "Location of the database file")
debug = flag.Bool("debug", false, "Enable debug output")
maxAge = flag.Duration("maxAge", 72*time.Hour, "max duration for an unused image")
lastUse = map[string]time.Time{}
purgeFrequency = flag.Duration("purgeFrequency", 57*time.Second, "How often the image purge will be run")
)
const (
BUCKET_IMAGE = "images"
)
func init() {
c, err := client.NewEnvClient()
if err != nil {
log.Fatal("Failed to setup docker client " + err.Error())
}
cli = c
}
func removeImage(id string) {
log.WithField("id", id).Info("Removing image")
_, err := cli.ImageRemove(context.Background(), id, types.ImageRemoveOptions{})
if err != nil {
log.WithError(err).WithField("id", id).Error("Cannot remove image")
return
}
if db != nil {
db.Update(func(tx *bolt.Tx) error {
log.WithField("id", id).Debug("Removing image from database")
b := tx.Bucket([]byte(BUCKET_IMAGE))
err := b.Delete([]byte(id))
if err != nil {
log.WithError(err).WithField("id", id).Warn("Error while removing from database")
return err
}
return nil
})
}
delete(lastUse, id)
}
func updateImageLastUsage(id string, usage time.Time) {
if db != nil {
db.Update(func(tx *bolt.Tx) error {
log.WithFields(log.Fields{"id": id, "usage": usage}).
Debug("Updating database")
b := tx.Bucket([]byte(BUCKET_IMAGE))
encoded, err := usage.GobEncode()
if err != nil {
log.WithError(err).WithFields(log.Fields{"id": id, "usage": usage}).
Error("Cannot update image data")
return err
}
err = b.Put([]byte(id), encoded)
if err != nil {
log.WithError(err).WithFields(log.Fields{"id": id, "usage": usage}).
Error("Cannot update image data")
return err
}
return nil
})
// TODO what to do if db cannot be updated?
}
lastUse[id] = usage
}
func loadImageDataFromDocker() {
now := time.Now()
log.Info("Setting last use from containers")
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
if err != nil {
log.WithError(err).Warn("Cannot get list of containers, image last usage may be less accurate")
} else {
for _, container := range containers {
log.WithField("Container", container.ID).Debug("Reading container")
img, _, err := cli.ImageInspectWithRaw(context.Background(), container.Image)
if err != nil {
log.WithError(err).WithField("Container", container.ID).
Warn("Cannot inspect image for container")
continue
}
var usage time.Time
if strings.HasPrefix(container.Status, "Exit") {
log.WithField("Container", container.ID).Debug("Container exited, adjusting image last usage")
details, err := cli.ContainerInspect(context.Background(), container.ID)
if err != nil {
log.WithField("Container", container.ID).
WithError(err).Warn("Cannot inspect container, skipping image update")
continue
}
usage, err = time.Parse(time.RFC3339, details.State.FinishedAt)
if err != nil {
log.WithError(err).WithField("Container", container.ID).
Warn("Cannot parse FinishedAt for container")
continue
}
} else {
usage = now
}
if old, ok := lastUse[img.ID]; !ok || old.Before(usage) {
updateImageLastUsage(img.ID, usage)
}
}
}
log.Info("Reading image data from Docker")
images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
if err != nil {
log.WithError(err).Warn("Cannot list images from Docker")
return
}
for _, image := range images {
log.WithField("ID", image.ID).Debug("Reading image")
if old, exists := lastUse[image.ID]; exists {
log.WithField("ID", image.ID).WithField("Usage", old).Debug("Not updating image")
} else {
log.WithField("ID", image.ID).WithField("Usage", now).Debug("Updating image")
updateImageLastUsage(image.ID, now)
}
}
}
func initDatabase() error {
dirname := path.Dir(*dbPath)
err := os.MkdirAll(dirname, 0700)
if err != nil {
log.WithError(err).WithField("Dir", dirname).Error("Cannot create db directory")
return err
}
db, err = bolt.Open(*dbPath, 0600, &bolt.Options{Timeout: 1 * time.Second})
if err != nil {
log.WithError(err).WithField("Path", *dbPath).Error("Cannot open database")
return err
}
db.Update(func(tx *bolt.Tx) error {
log.WithField("Bucket", BUCKET_IMAGE).Debug("Using bucket")
b, err := tx.CreateBucketIfNotExists([]byte(BUCKET_IMAGE))
if err != nil {
log.WithError(err).Error("Cannot get or create bucket", BUCKET_IMAGE, err.Error())
return err
}
c := b.Cursor()
for id, usage := c.First(); id != nil; id, usage = c.Next() {
// TODO do not restore data for image not longer existing & remove them from DB
var decoded time.Time
err := decoded.GobDecode(usage)
if err != nil {
log.WithError(err).WithField("Image", id).Warn("Cannot decode last usage")
}
log.WithFields(log.Fields{
"Image": string(id),
"Last use": decoded,
}).Debug("Retrieved image data")
lastUse[string(id)] = decoded
}
return nil
})
return nil
}
func prepare() {
err := initDatabase()
if err != nil {
log.WithError(err).Warn("Cannot init database, persistence disabled")
if db != nil {
db.Close()
db = nil
}
}
loadImageDataFromDocker()
log.Infof("Loaded %d images from Docker", len(lastUse))
}
func main() {
flag.Parse()
if *debug {
log.SetLevel(log.DebugLevel)
}
prepare()
log.WithField("MaxAge", maxAge).Info("Will purge all images unused")
ticker := time.NewTicker(*purgeFrequency)
for {
select {
case <-ticker.C:
collect()
}
}
}
func collect() {
filters := filters.NewArgs()
filters.Add("dangling", "true")
dangling, err := cli.ImageList(context.Background(), types.ImageListOptions{Filters: filters})
if err != nil {
// TODO isn't Fatal a be too much
log.WithError(err).Fatal("Cannot get list of dangling images")
}
for _, image := range dangling {
log.WithField("id", image.ID).Info("Remove dangling image")
removeImage(image.ID)
}
inUse := map[string]bool{}
containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{All: true})
if err != nil {
// TODO isn't Fatal a be too much
log.WithError(err).Fatal("Cannot get list of containers")
}
for _, container := range containers {
img, _, err := cli.ImageInspectWithRaw(context.Background(), container.Image)
if err != nil {
log.WithError(err).WithField("Container", container.ID).
Warn("Cannot inspect image for container")
continue
}
log.WithFields(log.Fields{"image": img.ID, "container": container.ID}).Debug("Image is used by container")
inUse[img.ID] = true
}
max := time.Now().Add(time.Duration(-1 * maxAge.Nanoseconds()))
log.WithField("Since", max.Truncate(time.Second)).Debug("Purging all unused image")
images, err := cli.ImageList(context.Background(), types.ImageListOptions{})
if err != nil {
log.Fatal(err)
}
for _, image := range images {
id := image.ID
if use, ok := lastUse[id]; ok && use.Before(max) && !inUse[id] {
log.WithFields(log.Fields{"id": id, "use": use}).Info("Purging unused image")
removeImage(image.ID)
}
}
}