summaryrefslogtreecommitdiff
path: root/cmd/kpod/images.go
blob: 71bc877c92dd626c2162a735bfc578caab50bb76 (plain)
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
package main

import (
	"fmt"
	"reflect"
	"strings"
	"time"

	"github.com/containers/image/types"
	"github.com/containers/storage"
	"github.com/docker/go-units"
	digest "github.com/opencontainers/go-digest"
	"github.com/pkg/errors"
	"github.com/projectatomic/libpod/cmd/kpod/formats"
	"github.com/projectatomic/libpod/libpod"
	"github.com/projectatomic/libpod/libpod/common"
	"github.com/urfave/cli"
)

type imagesTemplateParams struct {
	Repository string
	Tag        string
	ID         string
	Digest     digest.Digest
	Created    string
	Size       string
}

type imagesJSONParams struct {
	ID      string        `json:"id"`
	Name    []string      `json:"names"`
	Digest  digest.Digest `json:"digest"`
	Created time.Time     `json:"created"`
	Size    int64         `json:"size"`
}

type imagesOptions struct {
	quiet     bool
	noHeading bool
	noTrunc   bool
	digests   bool
	format    string
}

var (
	imagesFlags = []cli.Flag{
		cli.BoolFlag{
			Name:  "quiet, q",
			Usage: "display only image IDs",
		},
		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:  "digests",
			Usage: "show digests",
		},
		cli.StringFlag{
			Name:  "format",
			Usage: "Change the output format to JSON or a Go template",
		},
		cli.StringFlag{
			Name:  "filter, f",
			Usage: "filter output based on conditions provided (default [])",
		},
	}

	imagesDescription = "lists locally stored images."
	imagesCommand     = cli.Command{
		Name:        "images",
		Usage:       "list images in local storage",
		Description: imagesDescription,
		Flags:       imagesFlags,
		Action:      imagesCmd,
		ArgsUsage:   "",
	}
)

func imagesCmd(c *cli.Context) error {
	if err := validateFlags(c, imagesFlags); err != nil {
		return err
	}

	runtime, err := getRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "Could not get runtime")
	}
	defer runtime.Shutdown(false)

	var format string
	if c.IsSet("format") {
		format = c.String("format")
	} else {
		format = genImagesFormat(c.Bool("quiet"), c.Bool("noheading"), c.Bool("digests"))
	}

	opts := imagesOptions{
		quiet:     c.Bool("quiet"),
		noHeading: c.Bool("noheading"),
		noTrunc:   c.Bool("no-trunc"),
		digests:   c.Bool("digests"),
		format:    format,
	}

	var imageInput string
	if len(c.Args()) == 1 {
		imageInput = c.Args().Get(0)
	}
	if len(c.Args()) > 1 {
		return errors.New("'kpod images' requires at most 1 argument")
	}

	params, err := runtime.ParseImageFilter(imageInput, c.String("filter"))
	if err != nil {
		return errors.Wrapf(err, "error parsing filter")
	}

	// generate the different filters
	labelFilter := generateImagesFilter(params, "label")
	beforeImageFilter := generateImagesFilter(params, "before-image")
	sinceImageFilter := generateImagesFilter(params, "since-image")
	danglingFilter := generateImagesFilter(params, "dangling")
	referenceFilter := generateImagesFilter(params, "reference")
	imageInputFilter := generateImagesFilter(params, "image-input")

	images, err := runtime.GetImages(params, labelFilter, beforeImageFilter, sinceImageFilter, danglingFilter, referenceFilter, imageInputFilter)
	if err != nil {
		return errors.Wrapf(err, "could not get list of images matching filter")
	}

	return generateImagesOutput(runtime, images, opts)
}

func genImagesFormat(quiet, noHeading, digests bool) (format string) {
	if quiet {
		return formats.IDString
	}
	format = "table {{.Repository}}\t{{.Tag}}\t"
	if noHeading {
		format = "{{.Repository}}\t{{.Tag}}\t"
	}
	if digests {
		format += "{{.Digest}}\t"
	}
	format += "{{.ID}}\t{{.Created}}\t{{.Size}}\t"
	return
}

// imagesToGeneric creates an empty array of interfaces for output
func imagesToGeneric(templParams []imagesTemplateParams, JSONParams []imagesJSONParams) (genericParams []interface{}) {
	if len(templParams) > 0 {
		for _, v := range templParams {
			genericParams = append(genericParams, interface{}(v))
		}
		return
	}
	for _, v := range JSONParams {
		genericParams = append(genericParams, interface{}(v))
	}
	return
}

// generate the header based on the template provided
func (i *imagesTemplateParams) headerMap() map[string]string {
	v := reflect.Indirect(reflect.ValueOf(i))
	values := make(map[string]string)

	for i := 0; i < v.NumField(); i++ {
		key := v.Type().Field(i).Name
		value := key
		if value == "ID" {
			value = "Image" + value
		}
		values[key] = strings.ToUpper(splitCamelCase(value))
	}
	return values
}

// getImagesTemplateOutput returns the images information to be printed in human readable format
func getImagesTemplateOutput(runtime *libpod.Runtime, images []*storage.Image, opts imagesOptions) (imagesOutput []imagesTemplateParams) {
	var (
		lastID string
	)
	for _, img := range images {
		if opts.quiet && lastID == img.ID {
			continue // quiet should not show the same ID multiple times
		}
		createdTime := img.Created

		imageID := "sha256:" + img.ID
		if !opts.noTrunc {
			imageID = img.ID[:idTruncLength]
		}

		repository := "<none>"
		tag := "<none>"
		if len(img.Names) > 0 {
			arr := strings.Split(img.Names[0], ":")
			repository = arr[0]
			if len(arr) == 2 {
				tag = arr[1]
			}
		}

		info, imageDigest, size, _ := runtime.InfoAndDigestAndSize(*img)
		if info != nil {
			createdTime = info.Created
		}

		params := imagesTemplateParams{
			Repository: repository,
			Tag:        tag,
			ID:         imageID,
			Digest:     imageDigest,
			Created:    units.HumanDuration(time.Since((createdTime))) + " ago",
			Size:       units.HumanSizeWithPrecision(float64(size), 3),
		}
		imagesOutput = append(imagesOutput, params)
	}
	return
}

// getImagesJSONOutput returns the images information in its raw form
func getImagesJSONOutput(runtime *libpod.Runtime, images []*storage.Image) (imagesOutput []imagesJSONParams) {
	for _, img := range images {
		createdTime := img.Created

		info, imageDigest, size, _ := runtime.InfoAndDigestAndSize(*img)
		if info != nil {
			createdTime = info.Created
		}

		params := imagesJSONParams{
			ID:      img.ID,
			Name:    img.Names,
			Digest:  imageDigest,
			Created: createdTime,
			Size:    size,
		}
		imagesOutput = append(imagesOutput, params)
	}
	return
}

// generateImagesOutput generates the images based on the format provided
func generateImagesOutput(runtime *libpod.Runtime, images []*storage.Image, opts imagesOptions) error {
	if len(images) == 0 {
		return nil
	}

	var out formats.Writer

	switch opts.format {
	case formats.JSONString:
		imagesOutput := getImagesJSONOutput(runtime, images)
		out = formats.JSONStructArray{Output: imagesToGeneric([]imagesTemplateParams{}, imagesOutput)}
	default:
		imagesOutput := getImagesTemplateOutput(runtime, images, opts)
		out = formats.StdoutTemplateArray{Output: imagesToGeneric(imagesOutput, []imagesJSONParams{}), Template: opts.format, Fields: imagesOutput[0].headerMap()}

	}

	return formats.Writer(out).Out()
}

// generateImagesFilter returns an ImageFilter based on filterType
// to add more filters, define a new case and write what the ImageFilter function should do
func generateImagesFilter(params *libpod.ImageFilterParams, filterType string) libpod.ImageFilter {
	switch filterType {
	case "label":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.Label == "" {
				return true
			}

			pair := strings.SplitN(params.Label, "=", 2)
			if val, ok := info.Labels[pair[0]]; ok {
				if len(pair) == 2 && val == pair[1] {
					return true
				}
				if len(pair) == 1 {
					return true
				}
			}
			return false
		}
	case "before-image":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.BeforeImage.IsZero() {
				return true
			}
			return info.Created.Before(params.BeforeImage)
		}
	case "since-image":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.SinceImage.IsZero() {
				return true
			}
			return info.Created.After(params.SinceImage)
		}
	case "dangling":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.Dangling == "" {
				return true
			}
			if common.IsFalse(params.Dangling) && params.ImageName != "<none>" {
				return true
			}
			if common.IsTrue(params.Dangling) && params.ImageName == "<none>" {
				return true
			}
			return false
		}
	case "reference":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.ReferencePattern == "" {
				return true
			}
			return libpod.MatchesReference(params.ImageName, params.ReferencePattern)
		}
	case "image-input":
		return func(image *storage.Image, info *types.ImageInspectInfo) bool {
			if params == nil || params.ImageInput == "" {
				return true
			}
			return libpod.MatchesReference(params.ImageName, params.ImageInput)
		}
	default:
		fmt.Println("invalid filter type", filterType)
		return nil
	}
}