Skip to content

Commit 9fcc1d1

Browse files
authored
Merge pull request #424 from Random-Liu/add-filter-by-image
Add support to filter containers by image.
2 parents 4a917fd + 6fbb223 commit 9fcc1d1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

cmd/crictl/container.go

+14
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,11 @@ var listContainersCommand = cli.Command{
274274
Value: "",
275275
Usage: "Filter by pod id",
276276
},
277+
cli.StringFlag{
278+
Name: "image",
279+
Value: "",
280+
Usage: "Filter by container image",
281+
},
277282
cli.StringFlag{
278283
Name: "state",
279284
Value: "",
@@ -313,6 +318,9 @@ var listContainersCommand = cli.Command{
313318
if err = getRuntimeClient(context); err != nil {
314319
return err
315320
}
321+
if err = getImageClient(context); err != nil {
322+
return err
323+
}
316324

317325
opts := listOptions{
318326
id: context.String("id"),
@@ -326,6 +334,7 @@ var listContainersCommand = cli.Command{
326334
latest: context.Bool("latest"),
327335
last: context.Int("last"),
328336
noTrunc: context.Bool("no-trunc"),
337+
image: context.String("image"),
329338
}
330339
opts.labels, err = parseLabelStringSlice(context.StringSlice("label"))
331340
if err != nil {
@@ -639,6 +648,11 @@ func ListContainers(client pb.RuntimeServiceClient, opts listOptions) error {
639648
if !matchesRegex(opts.nameRegexp, c.Metadata.Name) {
640649
continue
641650
}
651+
if match, err := matchesImage(opts.image, c.GetImage().GetImage()); err != nil {
652+
return fmt.Errorf("failed to check image match %v", err)
653+
} else if !match {
654+
continue
655+
}
642656
if opts.quiet {
643657
fmt.Printf("%s\n", c.Id)
644658
continue

cmd/crictl/util.go

+24
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ type listOptions struct {
7171
last int
7272
// out with truncating the id
7373
noTrunc bool
74+
// image used by the container
75+
image string
7476
}
7577

7678
type execOptions struct {
@@ -321,3 +323,25 @@ func matchesRegex(pattern, target string) bool {
321323
}
322324
return matched
323325
}
326+
327+
func matchesImage(image, containerImage string) (bool, error) {
328+
if image == "" {
329+
return true, nil
330+
}
331+
if imageClient == nil {
332+
getImageClient(nil)
333+
}
334+
r1, err := ImageStatus(imageClient, image, false)
335+
if err != nil {
336+
return false, err
337+
}
338+
r2, err := ImageStatus(imageClient, containerImage, false)
339+
if err != nil {
340+
return false, err
341+
}
342+
if r1.Image == nil || r2.Image == nil {
343+
// Always return not match if the image doesn't exist.
344+
return false, nil
345+
}
346+
return r1.Image.Id == r2.Image.Id, nil
347+
}

0 commit comments

Comments
 (0)