forked from canonical/lxd
/
exec.go
215 lines (177 loc) · 4.99 KB
/
exec.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
211
212
213
214
215
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
"syscall"
"github.com/gorilla/websocket"
"github.com/lxc/lxd"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/gnuflag"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/termios"
)
type envList []string
func (f *envList) String() string {
return fmt.Sprint(*f)
}
func (f *envList) Set(value string) error {
if f == nil {
*f = make(envList, 1)
} else {
*f = append(*f, value)
}
return nil
}
type execCmd struct {
modeFlag string
envArgs envList
forceInteractive bool
forceNonInteractive bool
disableStdin bool
}
func (c *execCmd) showByDefault() bool {
return true
}
func (c *execCmd) usage() string {
return i18n.G(
`Usage: lxc exec [<remote>:]<container> [-t] [-T] [-n] [--mode=auto|interactive|non-interactive] [--env KEY=VALUE...] [--] <command line>
Execute commands in containers.
Mode defaults to non-interactive, interactive mode is selected if both stdin AND stdout are terminals (stderr is ignored).`)
}
func (c *execCmd) flags() {
gnuflag.Var(&c.envArgs, "env", i18n.G("Environment variable to set (e.g. HOME=/home/foo)"))
gnuflag.StringVar(&c.modeFlag, "mode", "auto", i18n.G("Override the terminal mode (auto, interactive or non-interactive)"))
gnuflag.BoolVar(&c.forceInteractive, "t", false, i18n.G("Force pseudo-terminal allocation"))
gnuflag.BoolVar(&c.forceNonInteractive, "T", false, i18n.G("Disable pseudo-terminal allocation"))
gnuflag.BoolVar(&c.disableStdin, "n", false, i18n.G("Disable stdin (reads from /dev/null)"))
}
func (c *execCmd) sendTermSize(control *websocket.Conn) error {
width, height, err := termios.GetSize(int(syscall.Stdout))
if err != nil {
return err
}
logger.Debugf("Window size is now: %dx%d", width, height)
w, err := control.NextWriter(websocket.TextMessage)
if err != nil {
return err
}
msg := api.ContainerExecControl{}
msg.Command = "window-resize"
msg.Args = make(map[string]string)
msg.Args["width"] = strconv.Itoa(width)
msg.Args["height"] = strconv.Itoa(height)
buf, err := json.Marshal(msg)
if err != nil {
return err
}
_, err = w.Write(buf)
w.Close()
return err
}
func (c *execCmd) forwardSignal(control *websocket.Conn, sig syscall.Signal) error {
logger.Debugf("Forwarding signal: %s", sig)
w, err := control.NextWriter(websocket.TextMessage)
if err != nil {
return err
}
msg := api.ContainerExecControl{}
msg.Command = "signal"
msg.Signal = int(sig)
buf, err := json.Marshal(msg)
if err != nil {
return err
}
_, err = w.Write(buf)
w.Close()
return err
}
func (c *execCmd) run(config *lxd.Config, args []string) error {
if len(args) < 2 {
return errArgs
}
if c.forceInteractive && c.forceNonInteractive {
return fmt.Errorf(i18n.G("You can't pass -t and -T at the same time"))
}
if c.modeFlag != "auto" && (c.forceInteractive || c.forceNonInteractive) {
return fmt.Errorf(i18n.G("You can't pass -t or -T at the same time as --mode"))
}
remote, name := config.ParseRemoteAndContainer(args[0])
d, err := lxd.NewClient(config, remote)
if err != nil {
return err
}
/* FIXME: Default values for HOME and USER are now handled by LXD.
This code should be removed after most users upgraded.
*/
env := map[string]string{"HOME": "/root", "USER": "root"}
if myTerm, ok := c.getTERM(); ok {
env["TERM"] = myTerm
}
for _, arg := range c.envArgs {
pieces := strings.SplitN(arg, "=", 2)
value := ""
if len(pieces) > 1 {
value = pieces[1]
}
env[pieces[0]] = value
}
cfd := int(syscall.Stdin)
var interactive bool
if c.disableStdin {
interactive = false
} else if c.modeFlag == "interactive" || c.forceInteractive {
interactive = true
} else if c.modeFlag == "non-interactive" || c.forceNonInteractive {
interactive = false
} else {
interactive = termios.IsTerminal(cfd) && termios.IsTerminal(int(syscall.Stdout))
}
var oldttystate *termios.State
if interactive {
oldttystate, err = termios.MakeRaw(cfd)
if err != nil {
return err
}
defer termios.Restore(cfd, oldttystate)
}
handler := c.controlSocketHandler
if !interactive {
handler = nil
}
var width, height int
if interactive {
width, height, err = termios.GetSize(int(syscall.Stdout))
if err != nil {
return err
}
}
var stdin io.ReadCloser
stdin = os.Stdin
if c.disableStdin {
stdin = ioutil.NopCloser(bytes.NewReader(nil))
}
stdout := c.getStdout()
ret, err := d.Exec(name, args[1:], env, stdin, stdout, os.Stderr, handler, width, height)
if err != nil {
return err
}
if oldttystate != nil {
/* A bit of a special case here: we want to exit with the same code as
* the process inside the container, so we explicitly exit here
* instead of returning an error.
*
* Additionally, since os.Exit() exits without running deferred
* functions, we restore the terminal explicitly.
*/
termios.Restore(cfd, oldttystate)
}
os.Exit(ret)
return fmt.Errorf(i18n.G("unreachable return reached"))
}