Skip to content

Commit 034470e

Browse files
Merge pull request #9689 from boaz0/boaz-1
add restart-policy to container filters & --filter to podman start
2 parents 4418416 + efdc7d8 commit 034470e

File tree

8 files changed

+148
-4
lines changed

8 files changed

+148
-4
lines changed

cmd/podman/containers/start.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package containers
33
import (
44
"fmt"
55
"os"
6+
"strings"
67

78
"github.com/containers/podman/v3/cmd/podman/common"
89
"github.com/containers/podman/v3/cmd/podman/registry"
@@ -42,7 +43,9 @@ var (
4243
)
4344

4445
var (
45-
startOptions entities.ContainerStartOptions
46+
startOptions = entities.ContainerStartOptions{
47+
Filters: make(map[string][]string),
48+
}
4649
)
4750

4851
func startFlags(cmd *cobra.Command) {
@@ -56,6 +59,8 @@ func startFlags(cmd *cobra.Command) {
5659

5760
flags.BoolVarP(&startOptions.Interactive, "interactive", "i", false, "Keep STDIN open even if not attached")
5861
flags.BoolVar(&startOptions.SigProxy, "sig-proxy", false, "Proxy received signals to the process (default true if attaching, false otherwise)")
62+
flags.StringSliceVarP(&filters, "filter", "f", []string{}, "Filter output based on conditions given")
63+
_ = cmd.RegisterFlagCompletionFunc("filter", common.AutocompletePsFilters)
5964

6065
flags.BoolVar(&startOptions.All, "all", false, "Start all containers regardless of their state or configuration")
6166

@@ -116,7 +121,18 @@ func start(cmd *cobra.Command, args []string) error {
116121
startOptions.Stdout = os.Stdout
117122
}
118123

119-
responses, err := registry.ContainerEngine().ContainerStart(registry.GetContext(), args, startOptions)
124+
var containers []string = args
125+
if len(filters) > 0 {
126+
for _, f := range filters {
127+
split := strings.SplitN(f, "=", 2)
128+
if len(split) == 1 {
129+
return errors.Errorf("invalid filter %q", f)
130+
}
131+
startOptions.Filters[split[0]] = append(startOptions.Filters[split[0]], split[1])
132+
}
133+
}
134+
135+
responses, err := registry.ContainerEngine().ContainerStart(registry.GetContext(), containers, startOptions)
120136
if err != nil {
121137
return err
122138
}

docs/source/markdown/podman-start.1.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,31 @@ Proxy received signals to the process (non-TTY mode only). SIGCHLD, SIGSTOP, and
4242

4343
Start all the containers created by Podman, default is only running containers.
4444

45+
#### **\-\-filter**, **-f**
46+
47+
Filter what containers are going to be started from the given arguments.
48+
Multiple filters can be given with multiple uses of the --filter flag.
49+
Filters with the same key work inclusive with the only exception being
50+
`label` which is exclusive. Filters with different keys always work exclusive.
51+
52+
Valid filters are listed below:
53+
54+
| **Filter** | **Description** |
55+
| --------------- | -------------------------------------------------------------------------------- |
56+
| id | [ID] Container's ID (accepts regex) |
57+
| name | [Name] Container's name (accepts regex) |
58+
| label | [Key] or [Key=Value] Label assigned to a container |
59+
| exited | [Int] Container's exit code |
60+
| status | [Status] Container's status: 'created', 'exited', 'paused', 'running', 'unknown' |
61+
| ancestor | [ImageName] Image or descendant used to create container |
62+
| before | [ID] or [Name] Containers created before this container |
63+
| since | [ID] or [Name] Containers created since this container |
64+
| volume | [VolumeName] or [MountpointDestination] Volume mounted in container |
65+
| health | [Status] healthy or unhealthy |
66+
| pod | [Pod] name or full or partial ID of pod |
67+
| network | [Network] name or full ID of network |
68+
69+
4570
## EXAMPLE
4671

4772
podman start mywebserver

libpod/define/container.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,12 @@ const (
1717
// handling of system restart, which Podman does not yet support.
1818
RestartPolicyUnlessStopped = "unless-stopped"
1919
)
20+
21+
// RestartPolicyMap maps between restart-policy valid values to restart policy types
22+
var RestartPolicyMap = map[string]string{
23+
"none": RestartPolicyNone,
24+
RestartPolicyNo: RestartPolicyNo,
25+
RestartPolicyAlways: RestartPolicyAlways,
26+
RestartPolicyOnFailure: RestartPolicyOnFailure,
27+
RestartPolicyUnlessStopped: RestartPolicyUnlessStopped,
28+
}

pkg/domain/entities/containers.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,6 +265,7 @@ type ContainerExistsOptions struct {
265265
// ContainerStartOptions describes the val from the
266266
// CLI needed to start a container
267267
type ContainerStartOptions struct {
268+
Filters map[string][]string
268269
All bool
269270
Attach bool
270271
DetachKeys string

pkg/domain/filters/containers.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package filters
22

33
import (
4+
"fmt"
45
"strconv"
56
"strings"
67
"time"
@@ -226,6 +227,32 @@ func GenerateContainerFilterFuncs(filter string, filterValues []string, r *libpo
226227
}
227228
return false
228229
}, nil
230+
case "restart-policy":
231+
invalidPolicyNames := []string{}
232+
for _, policy := range filterValues {
233+
if _, ok := define.RestartPolicyMap[policy]; !ok {
234+
invalidPolicyNames = append(invalidPolicyNames, policy)
235+
}
236+
}
237+
var filterValueError error = nil
238+
if len(invalidPolicyNames) > 0 {
239+
errPrefix := "invalid restart policy"
240+
if len(invalidPolicyNames) > 1 {
241+
errPrefix = "invalid restart policies"
242+
}
243+
filterValueError = fmt.Errorf("%s %s", strings.Join(invalidPolicyNames, ", "), errPrefix)
244+
}
245+
return func(c *libpod.Container) bool {
246+
for _, policy := range filterValues {
247+
if policy == "none" && c.RestartPolicy() == define.RestartPolicyNone {
248+
return true
249+
}
250+
if c.RestartPolicy() == policy {
251+
return true
252+
}
253+
}
254+
return false
255+
}, filterValueError
229256
}
230257
return nil, errors.Errorf("%s is an invalid filter", filter)
231258
}

pkg/domain/infra/abi/containers.go

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -694,7 +694,33 @@ func (ic *ContainerEngine) ContainerExecDetached(ctx context.Context, nameOrID s
694694
func (ic *ContainerEngine) ContainerStart(ctx context.Context, namesOrIds []string, options entities.ContainerStartOptions) ([]*entities.ContainerStartReport, error) {
695695
reports := []*entities.ContainerStartReport{}
696696
var exitCode = define.ExecErrorCodeGeneric
697-
ctrs, rawInputs, err := getContainersAndInputByContext(options.All, options.Latest, namesOrIds, ic.Libpod)
697+
containersNamesOrIds := namesOrIds
698+
if len(options.Filters) > 0 {
699+
filterFuncs := make([]libpod.ContainerFilter, 0, len(options.Filters))
700+
if len(options.Filters) > 0 {
701+
for k, v := range options.Filters {
702+
generatedFunc, err := dfilters.GenerateContainerFilterFuncs(k, v, ic.Libpod)
703+
if err != nil {
704+
return nil, err
705+
}
706+
filterFuncs = append(filterFuncs, generatedFunc)
707+
}
708+
}
709+
candidates, err := ic.Libpod.GetContainers(filterFuncs...)
710+
if err != nil {
711+
return nil, err
712+
}
713+
containersNamesOrIds = []string{}
714+
for _, candidate := range candidates {
715+
for _, nameOrID := range namesOrIds {
716+
if nameOrID == candidate.ID() || nameOrID == candidate.Name() {
717+
containersNamesOrIds = append(containersNamesOrIds, nameOrID)
718+
}
719+
}
720+
}
721+
}
722+
723+
ctrs, rawInputs, err := getContainersAndInputByContext(options.All, options.Latest, containersNamesOrIds, ic.Libpod)
698724
if err != nil {
699725
return nil, err
700726
}

pkg/domain/infra/tunnel/containers.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,7 +506,30 @@ func startAndAttach(ic *ContainerEngine, name string, detachKeys *string, input,
506506
func (ic *ContainerEngine) ContainerStart(ctx context.Context, namesOrIds []string, options entities.ContainerStartOptions) ([]*entities.ContainerStartReport, error) {
507507
reports := []*entities.ContainerStartReport{}
508508
var exitCode = define.ExecErrorCodeGeneric
509-
ctrs, err := getContainersByContext(ic.ClientCtx, options.All, false, namesOrIds)
509+
containersNamesOrIds := namesOrIds
510+
if len(options.Filters) > 0 {
511+
containersNamesOrIds = []string{}
512+
opts := new(containers.ListOptions).WithFilters(options.Filters).WithAll(true)
513+
candidates, listErr := containers.List(ic.ClientCtx, opts)
514+
if listErr != nil {
515+
return nil, listErr
516+
}
517+
for _, candidate := range candidates {
518+
for _, nameOrID := range namesOrIds {
519+
if nameOrID == candidate.ID {
520+
containersNamesOrIds = append(containersNamesOrIds, nameOrID)
521+
continue
522+
}
523+
for _, containerName := range candidate.Names {
524+
if containerName == nameOrID {
525+
containersNamesOrIds = append(containersNamesOrIds, nameOrID)
526+
continue
527+
}
528+
}
529+
}
530+
}
531+
}
532+
ctrs, err := getContainersByContext(ic.ClientCtx, options.All, false, containersNamesOrIds)
510533
if err != nil {
511534
return nil, err
512535
}

test/system/045-start.bats

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,21 @@ load helpers
4040
fi
4141
}
4242

43+
@test "podman start --filter - start only containers that match the filter" {
44+
run_podman run -d $IMAGE /bin/true
45+
cid="$output"
46+
run_podman start --filter restart-policy=always $cid "CID of restart-policy=always container"
47+
is "$output" ""
48+
49+
run_podman start --filter restart-policy=none $cid "CID of restart-policy=none container"
50+
is "$output" "$cid"
51+
}
52+
53+
@test "podman start --filter invalid-restart-policy - return error" {
54+
run_podman run -d $IMAGE /bin/true
55+
cid="$output"
56+
run_podman 125 start --filter restart-policy=fakepolicy $cid "CID of restart-policy=<not-exists> container"
57+
is "$output" "Error: fakepolicy invalid restart policy"
58+
}
59+
4360
# vim: filetype=sh

0 commit comments

Comments
 (0)