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 for cli network prune --filter flag #10254

Merged
merged 2 commits into from
May 14, 2021
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
15 changes: 15 additions & 0 deletions cmd/podman/common/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,21 @@ func ReadPodIDFiles(files []string) ([]string, error) {
return ids, nil
}

// ParseFilters transforms one filter format to another and validates input
func ParseFilters(filter []string) (map[string][]string, error) {
// TODO Remove once filter refactor is finished and url.Values done.
filters := map[string][]string{}
for _, f := range filter {
t := strings.SplitN(f, "=", 2)
filters = make(map[string][]string)
if len(t) < 2 {
return map[string][]string{}, errors.Errorf("filter input must be in the form of filter=value: %s is invalid", f)
}
filters[t[0]] = append(filters[t[0]], t[1])
}
return filters, nil
}

// createExpose parses user-provided exposed port definitions and converts them
// into SpecGen format.
// TODO: The SpecGen format should really handle ranges more sanely - we could
Expand Down
15 changes: 5 additions & 10 deletions cmd/podman/containers/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ import (
"bufio"
"context"
"fmt"
"net/url"
"os"
"strings"

"github.com/containers/common/pkg/completion"
"github.com/containers/podman/v3/cmd/podman/common"
"github.com/containers/podman/v3/cmd/podman/registry"
"github.com/containers/podman/v3/cmd/podman/utils"
"github.com/containers/podman/v3/cmd/podman/validate"
"github.com/containers/podman/v3/pkg/domain/entities"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -50,6 +49,7 @@ func init() {
func prune(cmd *cobra.Command, args []string) error {
var (
pruneOptions = entities.ContainerPruneOptions{}
err error
)
if !force {
reader := bufio.NewReader(os.Stdin)
Expand All @@ -64,14 +64,9 @@ func prune(cmd *cobra.Command, args []string) error {
}
}

// TODO Remove once filter refactor is finished and url.Values done.
for _, f := range filter {
t := strings.SplitN(f, "=", 2)
pruneOptions.Filters = make(url.Values)
if len(t) < 2 {
return errors.Errorf("filter input must be in the form of filter=value: %s is invalid", f)
}
pruneOptions.Filters.Add(t[0], t[1])
pruneOptions.Filters, err = common.ParseFilters(filter)
if err != nil {
return err
}
responses, err := registry.ContainerEngine().ContainerPrune(context.Background(), pruneOptions)

Expand Down
16 changes: 12 additions & 4 deletions cmd/podman/networks/prune.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"strings"

"github.com/containers/common/pkg/completion"
"github.com/containers/podman/v3/cmd/podman/common"
"github.com/containers/podman/v3/cmd/podman/registry"
"github.com/containers/podman/v3/cmd/podman/utils"
Expand All @@ -31,12 +32,14 @@ var (
var (
networkPruneOptions entities.NetworkPruneOptions
force bool
filter = []string{}
)

func networkPruneFlags(flags *pflag.FlagSet) {
//TODO: Not implemented but for future reference
//flags.StringSliceVar(&networkPruneOptions.Filters,"filters", []string{}, "provide filter values (e.g. 'until=<timestamp>')")
func networkPruneFlags(cmd *cobra.Command, flags *pflag.FlagSet) {
flags.BoolVarP(&force, "force", "f", false, "do not prompt for confirmation")
filterFlagName := "filter"
flags.StringArrayVar(&filter, filterFlagName, []string{}, "Provide filter values (e.g. 'label=<key>=<value>')")
_ = cmd.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone)
}

func init() {
Expand All @@ -46,12 +49,13 @@ func init() {
Parent: networkCmd,
})
flags := networkPruneCommand.Flags()
networkPruneFlags(flags)
networkPruneFlags(networkPruneCommand, flags)
}

func networkPrune(cmd *cobra.Command, _ []string) error {
var (
errs utils.OutputErrors
err error
)
if !force {
reader := bufio.NewReader(os.Stdin)
Expand All @@ -65,6 +69,10 @@ func networkPrune(cmd *cobra.Command, _ []string) error {
return nil
}
}
networkPruneOptions.Filters, err = common.ParseFilters(filter)
if err != nil {
return err
}
responses, err := registry.ContainerEngine().NetworkPrune(registry.Context(), networkPruneOptions)
if err != nil {
setExitCode(err)
Expand Down
2 changes: 1 addition & 1 deletion docs/source/markdown/podman-network-ls.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Displays a list of existing podman networks.
#### **--filter**, **-f**

Filter output based on conditions given.
Multiple filters can be given with multiple uses of the --filter flag.
Multiple filters can be given with multiple uses of the --filter option.
Filters with the same key work inclusive with the only exception being
`label` which is exclusive. Filters with different keys always work exclusive.

Expand Down
14 changes: 14 additions & 0 deletions docs/source/markdown/podman-network-prune.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,20 @@ the so-called default network which goes by the name of *podman*.

Do not prompt for confirmation

#### **--filter**

Filter output based on conditions given.
Multiple filters can be given with multiple uses of the --filter option.
Filters with the same key work inclusive with the only exception being
`label` which is exclusive. Filters with different keys always work exclusive.

Valid filters are listed below:

| **Filter** | **Description** |
| ---------- | ------------------------------------------------------------------------------------- |
| label | [Key] or [Key=Value] Label assigned to a network |
| until | only remove networks created before given timestamp |

## EXAMPLE
Prune networks

Expand Down
46 changes: 46 additions & 0 deletions test/e2e/network_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,52 @@ var _ = Describe("Podman network", func() {
Expect(nc.ExitCode()).To(Equal(0))
})

It("podman network prune --filter", func() {
net1 := "macvlan" + stringid.GenerateNonCryptoID() + "net1"

nc := podmanTest.Podman([]string{"network", "create", net1})
nc.WaitWithDefaultTimeout()
defer podmanTest.removeCNINetwork(net1)
Expect(nc.ExitCode()).To(Equal(0))

list := podmanTest.Podman([]string{"network", "ls", "--format", "{{.Name}}"})
list.WaitWithDefaultTimeout()
Expect(list.ExitCode()).To(BeZero())

Expect(StringInSlice(net1, list.OutputToStringArray())).To(BeTrue())
if !isRootless() {
Expect(StringInSlice("podman", list.OutputToStringArray())).To(BeTrue())
}

// -f needed only to skip y/n question
prune := podmanTest.Podman([]string{"network", "prune", "-f", "--filter", "until=50"})
prune.WaitWithDefaultTimeout()
Expect(prune.ExitCode()).To(BeZero())

listAgain := podmanTest.Podman([]string{"network", "ls", "--format", "{{.Name}}"})
listAgain.WaitWithDefaultTimeout()
Expect(listAgain.ExitCode()).To(BeZero())

Expect(StringInSlice(net1, listAgain.OutputToStringArray())).To(BeTrue())
if !isRootless() {
Expect(StringInSlice("podman", list.OutputToStringArray())).To(BeTrue())
}

// -f needed only to skip y/n question
prune = podmanTest.Podman([]string{"network", "prune", "-f", "--filter", "until=5000000000000"})
prune.WaitWithDefaultTimeout()
Expect(prune.ExitCode()).To(BeZero())

listAgain = podmanTest.Podman([]string{"network", "ls", "--format", "{{.Name}}"})
listAgain.WaitWithDefaultTimeout()
Expect(listAgain.ExitCode()).To(BeZero())

Expect(StringInSlice(net1, listAgain.OutputToStringArray())).To(BeFalse())
if !isRootless() {
Expect(StringInSlice("podman", list.OutputToStringArray())).To(BeTrue())
}
})

It("podman network prune", func() {
// Create two networks
// Check they are there
Expand Down