-
Notifications
You must be signed in to change notification settings - Fork 950
/
Copy pathstart.go
210 lines (186 loc) · 5.71 KB
/
start.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"strings"
"github.com/alibaba/pouch/apis/types"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
// startDescription is used to describe start command in detail and auto generate command doc.
var startDescription = "Start one or more created container objects in Pouchd. " +
"When starting, the relevant resource preserved during creating period comes into use. " +
"This is useful when you wish to start a container which has been created in advance." +
"The container you started will be running if no error occurs."
// StartCommand use to implement 'start' command, it start one or more containers.
type StartCommand struct {
baseCommand
detachKeys string
attach bool
stdin bool
checkpoint string
cpDir string
}
// Init initialize start command.
func (s *StartCommand) Init(c *Cli) {
s.cli = c
s.cmd = &cobra.Command{
Use: "start [OPTIONS] CONTAINER [CONTAINER...]",
Short: "Start one or more created or stopped containers",
Long: startDescription,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return s.runStart(args)
},
Example: startExample(),
}
s.addFlags()
}
// addFlags adds flags for specific command.
func (s *StartCommand) addFlags() {
flagSet := s.cmd.Flags()
flagSet.StringVar(&s.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
flagSet.BoolVarP(&s.attach, "attach", "a", false, "Attach container's STDOUT and STDERR")
flagSet.BoolVarP(&s.stdin, "interactive", "i", false, "Attach container's STDIN")
flagSet.StringVar(&s.checkpoint, "checkpoint", "", "Restore container state from the checkpoint")
flagSet.StringVar(&s.cpDir, "checkpoint-dir", "", "Directory to store checkpoints images")
}
// runStart is the entry of start command.
func (s *StartCommand) runStart(args []string) error {
ctx := context.Background()
apiClient := s.cli.Client()
// attach to io.
if s.attach || s.stdin {
var wait chan struct{}
// If we want to attach to a container, we should make sure we only have one container.
if len(args) > 1 {
return fmt.Errorf("cannot start and attach multiple containers at once")
}
container := args[0]
c, err := apiClient.ContainerGet(ctx, container)
if err != nil {
return err
}
if err := checkTty(s.attach, c.Config.Tty, os.Stdout.Fd()); err != nil {
return err
}
if c.Config.Tty {
in, out, err := setRawMode(s.stdin, false)
if err != nil {
return fmt.Errorf("failed to set raw mode")
}
defer func() {
if err := restoreMode(in, out); err != nil {
fmt.Fprintf(os.Stderr, "failed to restore term mode")
}
}()
}
conn, br, err := apiClient.ContainerAttach(ctx, container, s.stdin)
if err != nil {
return fmt.Errorf("failed to attach container: %v", err)
}
defer conn.Close()
wait = make(chan struct{})
go func() {
io.Copy(os.Stdout, br)
close(wait)
}()
go func() {
io.Copy(conn, os.Stdin)
}()
// start container
if err := apiClient.ContainerStart(ctx, container, types.ContainerStartOptions{
DetachKeys: s.detachKeys,
CheckpointID: s.checkpoint,
CheckpointDir: s.cpDir,
}); err != nil {
return fmt.Errorf("failed to start container %s: %v", container, err)
}
// wait the io to finish.
if s.attach || s.stdin {
<-wait
}
info, err := apiClient.ContainerGet(ctx, container)
if err != nil {
return err
}
code := info.State.ExitCode
if code != 0 {
return ExitError{Code: int(code)}
}
} else {
// We're not going to attach to any container, so we just start as many containers as we want.
var errs []string
for _, name := range args {
if err := apiClient.ContainerStart(ctx, name, types.ContainerStartOptions{
DetachKeys: s.detachKeys,
CheckpointID: s.checkpoint,
CheckpointDir: s.cpDir,
}); err != nil {
errs = append(errs, err.Error())
continue
}
fmt.Printf("%s\n", name)
}
if len(errs) > 0 {
return errors.New("failed to start containers: " + strings.Join(errs, ""))
}
}
return nil
}
func setRawMode(stdin, stdout bool) (*terminal.State, *terminal.State, error) {
var (
in *terminal.State
out *terminal.State
err error
)
if stdin {
if in, err = terminal.MakeRaw(0); err != nil {
return nil, nil, err
}
}
if stdout {
if out, err = terminal.MakeRaw(1); err != nil {
return nil, nil, err
}
}
return in, out, nil
}
func restoreMode(in, out *terminal.State) error {
if in != nil {
if err := terminal.Restore(0, in); err != nil {
return err
}
}
if out != nil {
if err := terminal.Restore(1, out); err != nil {
return err
}
}
return nil
}
// CheckTty checks if we are trying to attach to a container tty
// from a non-tty client input stream, and if so, returns an error.
func checkTty(attachStdin, ttyMode bool, fd uintptr) error {
if ttyMode && attachStdin && !terminal.IsTerminal(int(fd)) {
return errors.New("the input device is not a TTY")
}
return nil
}
// startExample shows examples in start command, and is used in auto-generated cli docs.
func startExample() string {
return `$ pouch ps -a
Name ID Status Created Image Runtime
foo2 5a0ede created 1 second ago registry.hub.docker.com/library/busybox:latest runc
foo1 e05637 created 6 seconds ago registry.hub.docker.com/library/busybox:latest runc
$ pouch start foo1 foo2
foo1
foo2
$ pouch ps
Name ID Status Created Image Runtime
foo2 5a0ede Up 2 seconds 12 seconds ago registry.hub.docker.com/library/busybox:latest runc
foo1 e05637 Up 3 seconds 17 seconds ago registry.hub.docker.com/library/busybox:latest runc`
}