forked from AliyunContainerService/pouch
/
stop.go
76 lines (65 loc) · 2.13 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
74
75
76
package main
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"github.com/spf13/cobra"
)
// stopDescription is used to describe stop command in detail and auto generate command doc.
var stopDescription = "Stop one or more running containers in Pouchd. Waiting the given number of seconds before forcefully killing the container." +
"This is useful when you wish to stop a container. And Pouchd will stop this running container and release the resource. " +
"The container that you stopped will be terminated. "
// StopCommand use to implement 'stop' command, it stops a container.
type StopCommand struct {
baseCommand
timeout int
}
// Init initialize stop command.
func (s *StopCommand) Init(c *Cli) {
s.cli = c
s.cmd = &cobra.Command{
Use: "stop [OPTIONS] CONTAINER [CONTAINER...]",
Short: "Stop one or more running containers",
Long: stopDescription,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return s.runStop(args)
},
Example: stopExample(),
}
s.addFlags()
}
// addFlags adds flags for specific command.
func (s *StopCommand) addFlags() {
flagSet := s.cmd.Flags()
flagSet.IntVarP(&s.timeout, "time", "t", 10, "Seconds to wait for stop before killing it")
}
// runStop is the entry of stop command.
func (s *StopCommand) runStop(args []string) error {
ctx := context.Background()
apiClient := s.cli.Client()
var errs []string
for _, name := range args {
if err := apiClient.ContainerStop(ctx, name, strconv.Itoa(s.timeout)); err != nil {
errs = append(errs, err.Error())
continue
}
fmt.Printf("%s\n", name)
}
if len(errs) > 0 {
return errors.New(strings.Join(errs, "\n"))
}
return nil
}
// stopExample shows examples in stop command, and is used in auto-generated cli docs.
func stopExample() string {
return `$ pouch ps
Name ID Status Image Runtime
foo 71b9c1 Running docker.io/library/busybox:latest runc
$ pouch stop foo
$ pouch ps -a
Name ID Status Image Runtime
foo 71b9c1 Stopped docker.io/library/busybox:latest runc`
}