-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
stop.go
73 lines (64 loc) · 1.86 KB
/
stop.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package container
import (
"context"
"fmt"
"strings"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/docker/cli/cli/command/completion"
"github.com/docker/docker/api/types/container"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
type stopOptions struct {
signal string
timeout int
timeoutChanged bool
containers []string
}
// NewStopCommand creates a new cobra.Command for `docker stop`
func NewStopCommand(dockerCli command.Cli) *cobra.Command {
var opts stopOptions
cmd := &cobra.Command{
Use: "stop [OPTIONS] CONTAINER [CONTAINER...]",
Short: "Stop one or more running containers",
Args: cli.RequiresMinArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
opts.containers = args
opts.timeoutChanged = cmd.Flags().Changed("time")
return runStop(dockerCli, &opts)
},
Annotations: map[string]string{
"aliases": "docker container stop, docker stop",
},
ValidArgsFunction: completion.ContainerNames(dockerCli, false),
}
flags := cmd.Flags()
flags.StringVarP(&opts.signal, "signal", "s", "", "Signal to send to the container")
flags.IntVarP(&opts.timeout, "time", "t", 0, "Seconds to wait before killing the container")
return cmd
}
func runStop(dockerCli command.Cli, opts *stopOptions) error {
var timeout *int
if opts.timeoutChanged {
timeout = &opts.timeout
}
errChan := parallelOperation(context.Background(), opts.containers, func(ctx context.Context, id string) error {
return dockerCli.Client().ContainerStop(ctx, id, container.StopOptions{
Signal: opts.signal,
Timeout: timeout,
})
})
var errs []string
for _, ctr := range opts.containers {
if err := <-errChan; err != nil {
errs = append(errs, err.Error())
continue
}
_, _ = fmt.Fprintln(dockerCli.Out(), ctr)
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
}