forked from AliyunContainerService/pouch
/
start.go
115 lines (98 loc) · 2.23 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
package main
import (
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh/terminal"
)
// StartCommand use to implement 'start' command, it start a container.
type StartCommand struct {
baseCommand
attach bool
stdin bool
}
// Init initialize start command.
func (s *StartCommand) Init(c *Cli) {
s.cli = c
s.cmd = &cobra.Command{
Use: "start [container]",
Short: "Start a created container",
Args: cobra.MinimumNArgs(1),
}
s.cmd.Flags().BoolVarP(&s.attach, "attach", "a", false, "attach the container's io or not")
s.cmd.Flags().BoolVarP(&s.stdin, "interactive", "i", false, "attach container's stdin")
}
// Run is the entry of start command.
func (s *StartCommand) Run(args []string) {
container := args[0]
// attach to io.
apiClient := s.cli.Client()
var wait chan struct{}
if s.attach || s.stdin {
in, out, err := setRawMode(s.stdin, false)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to set raw mode")
return
}
defer func() {
if err := restoreMode(in, out); err != nil {
fmt.Fprintf(os.Stderr, "failed to restore term mode")
}
}()
conn, br, err := apiClient.ContainerAttach(container, s.stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to attach container: %v \n", err)
return
}
wait = make(chan struct{})
go func() {
io.Copy(os.Stdout, br)
close(wait)
}()
go func() {
io.Copy(conn, os.Stdin)
close(wait)
}()
}
// start container
if err := apiClient.ContainerStart(container, ""); err != nil {
fmt.Fprintf(os.Stderr, "failed to start container %s: %v\n", container, err)
return
}
// wait the io to finish.
if s.attach || s.stdin {
<-wait
}
}
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
}