Skip to content

Commit

Permalink
Merge pull request #424 from Random-Liu/add-filter-by-image
Browse files Browse the repository at this point in the history
Add support to filter containers by image.
  • Loading branch information
k8s-ci-robot authored Jan 3, 2019
2 parents 4a917fd + 6fbb223 commit 9fcc1d1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
14 changes: 14 additions & 0 deletions cmd/crictl/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,11 @@ var listContainersCommand = cli.Command{
Value: "",
Usage: "Filter by pod id",
},
cli.StringFlag{
Name: "image",
Value: "",
Usage: "Filter by container image",
},
cli.StringFlag{
Name: "state",
Value: "",
Expand Down Expand Up @@ -313,6 +318,9 @@ var listContainersCommand = cli.Command{
if err = getRuntimeClient(context); err != nil {
return err
}
if err = getImageClient(context); err != nil {
return err
}

opts := listOptions{
id: context.String("id"),
Expand All @@ -326,6 +334,7 @@ var listContainersCommand = cli.Command{
latest: context.Bool("latest"),
last: context.Int("last"),
noTrunc: context.Bool("no-trunc"),
image: context.String("image"),
}
opts.labels, err = parseLabelStringSlice(context.StringSlice("label"))
if err != nil {
Expand Down Expand Up @@ -639,6 +648,11 @@ func ListContainers(client pb.RuntimeServiceClient, opts listOptions) error {
if !matchesRegex(opts.nameRegexp, c.Metadata.Name) {
continue
}
if match, err := matchesImage(opts.image, c.GetImage().GetImage()); err != nil {
return fmt.Errorf("failed to check image match %v", err)
} else if !match {
continue
}
if opts.quiet {
fmt.Printf("%s\n", c.Id)
continue
Expand Down
24 changes: 24 additions & 0 deletions cmd/crictl/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ type listOptions struct {
last int
// out with truncating the id
noTrunc bool
// image used by the container
image string
}

type execOptions struct {
Expand Down Expand Up @@ -321,3 +323,25 @@ func matchesRegex(pattern, target string) bool {
}
return matched
}

func matchesImage(image, containerImage string) (bool, error) {
if image == "" {
return true, nil
}
if imageClient == nil {
getImageClient(nil)
}
r1, err := ImageStatus(imageClient, image, false)
if err != nil {
return false, err
}
r2, err := ImageStatus(imageClient, containerImage, false)
if err != nil {
return false, err
}
if r1.Image == nil || r2.Image == nil {
// Always return not match if the image doesn't exist.
return false, nil
}
return r1.Image.Id == r2.Image.Id, nil
}

0 comments on commit 9fcc1d1

Please sign in to comment.