Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support to filter containers by image. #424

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}