forked from containers/buildah
/
images.go
396 lines (357 loc) · 10.1 KB
/
images.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package main
import (
"fmt"
"os"
"strings"
"text/template"
"time"
"encoding/json"
is "github.com/containers/image/storage"
"github.com/containers/storage"
"github.com/pkg/errors"
"github.com/projectatomic/buildah/util"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
"golang.org/x/crypto/ssh/terminal"
)
type jsonImage struct {
ID string `json:"id"`
Names []string `json:"names"`
}
type imageOutputParams struct {
ID string
Name string
Digest string
CreatedAt string
Size string
}
type filterParams struct {
dangling string
label string
beforeImage string // Images are sorted by date, so we can just output until we see the image
sinceImage string // Images are sorted by date, so we can just output until we don't see the image
beforeDate time.Time
sinceDate time.Time
referencePattern string
}
var (
imagesFlags = []cli.Flag{
cli.BoolFlag{
Name: "digests",
Usage: "show digests",
},
cli.StringFlag{
Name: "filter, f",
Usage: "filter output based on conditions provided",
},
cli.StringFlag{
Name: "format",
Usage: "pretty-print images using a Go template",
},
cli.BoolFlag{
Name: "json",
Usage: "output in JSON format",
},
cli.BoolFlag{
Name: "noheading, n",
Usage: "do not print column headings",
},
cli.BoolFlag{
Name: "no-trunc, notruncate",
Usage: "do not truncate output",
},
cli.BoolFlag{
Name: "quiet, q",
Usage: "display only image IDs",
},
}
imagesDescription = "Lists locally stored images."
imagesCommand = cli.Command{
Name: "images",
Usage: "List images in local storage",
Description: imagesDescription,
Flags: imagesFlags,
Action: imagesCmd,
ArgsUsage: " ",
SkipArgReorder: true,
}
)
func imagesCmd(c *cli.Context) error {
if err := validateFlags(c, imagesFlags); err != nil {
return err
}
store, err := getStore(c)
if err != nil {
return err
}
images, err := store.Images()
if err != nil {
return errors.Wrapf(err, "error reading images")
}
if c.IsSet("quiet") && c.IsSet("format") {
return errors.Errorf("quiet and format are mutually exclusive")
}
quiet := c.Bool("quiet")
truncate := !c.Bool("no-trunc")
digests := c.Bool("digests")
hasTemplate := c.IsSet("format")
name := ""
if len(c.Args()) == 1 {
name = c.Args().Get(0)
} else if len(c.Args()) > 1 {
return errors.New("'buildah images' requires at most 1 argument")
}
if c.IsSet("json") {
JSONImages := []jsonImage{}
for _, image := range images {
JSONImages = append(JSONImages, jsonImage{ID: image.ID, Names: image.Names})
}
data, err2 := json.MarshalIndent(JSONImages, "", " ")
if err2 != nil {
return err2
}
fmt.Printf("%s\n", data)
return nil
}
var params *filterParams
if c.IsSet("filter") {
params, err = parseFilter(store, images, c.String("filter"))
if err != nil {
return errors.Wrapf(err, "error parsing filter")
}
}
if len(images) > 0 && !c.Bool("noheading") && !quiet && !hasTemplate {
outputHeader(truncate, digests)
}
return outputImages(images, c.String("format"), store, params, name, hasTemplate, truncate, digests, quiet)
}
func parseFilter(store storage.Store, images []storage.Image, filter string) (*filterParams, error) {
params := new(filterParams)
filterStrings := strings.Split(filter, ",")
for _, param := range filterStrings {
pair := strings.SplitN(param, "=", 2)
switch strings.TrimSpace(pair[0]) {
case "dangling":
if pair[1] == "true" || pair[1] == "false" {
params.dangling = pair[1]
} else {
return nil, fmt.Errorf("invalid filter: '%s=[%s]'", pair[0], pair[1])
}
case "label":
params.label = pair[1]
case "before":
beforeDate, err := setFilterDate(store, images, pair[1])
if err != nil {
return nil, fmt.Errorf("no such id: %s", pair[0])
}
params.beforeDate = beforeDate
params.beforeImage = pair[1]
case "since":
sinceDate, err := setFilterDate(store, images, pair[1])
if err != nil {
return nil, fmt.Errorf("no such id: %s", pair[0])
}
params.sinceDate = sinceDate
params.sinceImage = pair[1]
case "reference":
params.referencePattern = pair[1]
default:
return nil, fmt.Errorf("invalid filter: '%s'", pair[0])
}
}
return params, nil
}
func setFilterDate(store storage.Store, images []storage.Image, imgName string) (time.Time, error) {
for _, image := range images {
for _, name := range image.Names {
if matchesReference(name, imgName) {
// Set the date to this image
ref, err := is.Transport.ParseStoreReference(store, image.ID)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing reference to image %q: %v", image.ID, err)
}
img, err := ref.NewImage(nil)
if err != nil {
return time.Time{}, fmt.Errorf("error reading image %q: %v", image.ID, err)
}
defer img.Close()
inspect, err := img.Inspect()
if err != nil {
return time.Time{}, fmt.Errorf("error inspecting image %q: %v", image.ID, err)
}
date := *inspect.Created
return date, nil
}
}
}
return time.Time{}, fmt.Errorf("Could not locate image %q", imgName)
}
func outputHeader(truncate, digests bool) {
if truncate {
fmt.Printf("%-20s %-56s ", "IMAGE ID", "IMAGE NAME")
} else {
fmt.Printf("%-64s %-56s ", "IMAGE ID", "IMAGE NAME")
}
if digests {
fmt.Printf("%-71s ", "DIGEST")
}
fmt.Printf("%-22s %s\n", "CREATED AT", "SIZE")
}
func outputImages(images []storage.Image, format string, store storage.Store, filters *filterParams, argName string, hasTemplate, truncate, digests, quiet bool) error {
for _, image := range images {
createdTime := image.Created
inspectedTime, digest, size, _ := getDateAndDigestAndSize(image, store)
if !inspectedTime.IsZero() {
if createdTime != inspectedTime {
logrus.Debugf("image record and configuration disagree on the image's creation time for %q, using the one from the configuration", image)
createdTime = inspectedTime
}
}
createdTime = util.GetLocalTime(createdTime)
names := []string{}
if len(image.Names) > 0 {
names = image.Names
} else {
// images without names should be printed with "<none>" as the image name
names = append(names, "<none>")
}
for _, name := range names {
if !matchesFilter(image, store, name, filters) || !matchesReference(name, argName) {
continue
}
if quiet {
fmt.Printf("%-64s\n", image.ID)
// We only want to print each id once
break
}
params := imageOutputParams{
ID: image.ID,
Name: name,
Digest: digest,
CreatedAt: createdTime.Format("Jan 2, 2006 15:04"),
Size: formattedSize(size),
}
if hasTemplate {
if err := outputUsingTemplate(format, params); err != nil {
return err
}
continue
}
outputUsingFormatString(truncate, digests, params)
}
}
return nil
}
func matchesFilter(image storage.Image, store storage.Store, name string, params *filterParams) bool {
if params == nil {
return true
}
if params.dangling != "" && !matchesDangling(name, params.dangling) {
return false
} else if params.label != "" && !matchesLabel(image, store, params.label) {
return false
} else if params.beforeImage != "" && !matchesBeforeImage(image, name, params) {
return false
} else if params.sinceImage != "" && !matchesSinceImage(image, name, params) {
return false
} else if params.referencePattern != "" && !matchesReference(name, params.referencePattern) {
return false
}
return true
}
func matchesDangling(name string, dangling string) bool {
if dangling == "false" && name != "<none>" {
return true
} else if dangling == "true" && name == "<none>" {
return true
}
return false
}
func matchesLabel(image storage.Image, store storage.Store, label string) bool {
storeRef, err := is.Transport.ParseStoreReference(store, image.ID)
if err != nil {
return false
}
img, err := storeRef.NewImage(nil)
if err != nil {
return false
}
defer img.Close()
info, err := img.Inspect()
if err != nil {
return false
}
pair := strings.SplitN(label, "=", 2)
for key, value := range info.Labels {
if key == pair[0] {
if len(pair) == 2 {
if value == pair[1] {
return true
}
} else {
return false
}
}
}
return false
}
// Returns true if the image was created since the filter image. Returns
// false otherwise
func matchesBeforeImage(image storage.Image, name string, params *filterParams) bool {
return image.Created.IsZero() || image.Created.Before(params.beforeDate)
}
// Returns true if the image was created since the filter image. Returns
// false otherwise
func matchesSinceImage(image storage.Image, name string, params *filterParams) bool {
return image.Created.IsZero() || image.Created.After(params.sinceDate)
}
func matchesID(imageID, argID string) bool {
return strings.HasPrefix(imageID, argID)
}
func matchesReference(name, argName string) bool {
if argName == "" {
return true
}
splitName := strings.Split(name, ":")
// If the arg contains a tag, we handle it differently than if it does not
if strings.Contains(argName, ":") {
splitArg := strings.Split(argName, ":")
return strings.HasSuffix(splitName[0], splitArg[0]) && (splitName[1] == splitArg[1])
}
return strings.HasSuffix(splitName[0], argName)
}
func formattedSize(size int64) string {
suffixes := [5]string{"B", "KB", "MB", "GB", "TB"}
count := 0
formattedSize := float64(size)
for formattedSize >= 1024 && count < 4 {
formattedSize /= 1024
count++
}
return fmt.Sprintf("%.4g %s", formattedSize, suffixes[count])
}
func outputUsingTemplate(format string, params imageOutputParams) error {
tmpl, err := template.New("image").Parse(format)
if err != nil {
return errors.Wrapf(err, "Template parsing error")
}
err = tmpl.Execute(os.Stdout, params)
if err != nil {
return err
}
if terminal.IsTerminal(int(os.Stdout.Fd())) {
fmt.Println()
}
return nil
}
func outputUsingFormatString(truncate, digests bool, params imageOutputParams) {
if truncate {
fmt.Printf("%-20.12s %-56s", params.ID, params.Name)
} else {
fmt.Printf("%-64s %-56s", params.ID, params.Name)
}
if digests {
fmt.Printf(" %-64s", params.Digest)
}
fmt.Printf(" %-22s %s\n", params.CreatedAt, params.Size)
}