forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconsole.go
386 lines (314 loc) · 8.21 KB
/
console.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package main
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/exec"
"runtime"
"strconv"
"sync"
"github.com/gorilla/websocket"
"github.com/spf13/cobra"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
cli "github.com/lxc/lxd/shared/cmd"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/termios"
)
type cmdConsole struct {
global *cmdGlobal
flagShowLog bool
flagType string
}
func (c *cmdConsole) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("console", i18n.G("[<remote>:]<instance>"))
cmd.Short = i18n.G("Attach to instance consoles")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Attach to instance consoles
This command allows you to interact with the boot console of an instance
as well as retrieve past log entries from it.`))
cmd.RunE = c.Run
cmd.Flags().BoolVar(&c.flagShowLog, "show-log", false, i18n.G("Retrieve the instance's console log"))
cmd.Flags().StringVarP(&c.flagType, "type", "t", "console", i18n.G("Type of connection to establish: 'console' for serial console, 'vga' for SPICE graphical output")+"``")
return cmd
}
func (c *cmdConsole) sendTermSize(control *websocket.Conn) error {
width, height, err := termios.GetSize(int(os.Stdout.Fd()))
if err != nil {
return err
}
logger.Debugf("Window size is now: %dx%d", width, height)
msg := api.InstanceExecControl{}
msg.Command = "window-resize"
msg.Args = make(map[string]string)
msg.Args["width"] = strconv.Itoa(width)
msg.Args["height"] = strconv.Itoa(height)
return control.WriteJSON(msg)
}
type readWriteCloser struct {
io.Reader
io.WriteCloser
}
type stdinMirror struct {
r io.Reader
consoleDisconnect chan struct{}
foundEscape *bool
}
// The pty has been switched to raw mode so we will only ever read a single
// byte. The buffer size is therefore uninteresting to us.
func (er stdinMirror) Read(p []byte) (int, error) {
n, err := er.r.Read(p)
v := rune(p[0])
if v == '\u0001' && !*er.foundEscape {
*er.foundEscape = true
return 0, err
}
if v == 'q' && *er.foundEscape {
close(er.consoleDisconnect)
return 0, err
}
*er.foundEscape = false
return n, err
}
func (c *cmdConsole) Run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// Validate flags.
if !shared.StringInSlice(c.flagType, []string{"console", "vga"}) {
return fmt.Errorf(i18n.G("Unknown output type %q"), c.flagType)
}
// Connect to LXD
remote, name, err := conf.ParseRemote(args[0])
if err != nil {
return err
}
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
// Show the current log if requested
if c.flagShowLog {
if c.flagType != "console" {
return fmt.Errorf(i18n.G("The --show-log flag is only supported for by 'console' output type"))
}
console := &lxd.InstanceConsoleLogArgs{}
log, err := d.GetInstanceConsoleLog(name, console)
if err != nil {
return err
}
stuff, err := ioutil.ReadAll(log)
if err != nil {
return err
}
fmt.Printf("\n"+i18n.G("Console log:")+"\n\n%s\n", string(stuff))
return nil
}
return c.Console(d, name)
}
func (c *cmdConsole) Console(d lxd.InstanceServer, name string) error {
if c.flagType == "" {
c.flagType = "console"
}
switch c.flagType {
case "console":
return c.console(d, name)
case "vga":
return c.vga(d, name)
}
return fmt.Errorf(i18n.G("Unknown console type %q"), c.flagType)
}
func (c *cmdConsole) console(d lxd.InstanceServer, name string) error {
// Configure the terminal
cfd := int(os.Stdin.Fd())
oldTTYstate, err := termios.MakeRaw(cfd)
if err != nil {
return err
}
defer termios.Restore(cfd, oldTTYstate)
handler := c.controlSocketHandler
var width, height int
width, height, err = termios.GetSize(int(os.Stdin.Fd()))
if err != nil {
return err
}
// Prepare the remote console
req := api.InstanceConsolePost{
Width: width,
Height: height,
Type: "console",
}
consoleDisconnect := make(chan bool)
manualDisconnect := make(chan struct{})
sendDisconnect := make(chan struct{})
defer close(sendDisconnect)
consoleArgs := lxd.InstanceConsoleArgs{
Terminal: &readWriteCloser{stdinMirror{os.Stdin,
manualDisconnect, new(bool)}, os.Stdout},
Control: handler,
ConsoleDisconnect: consoleDisconnect,
}
go func() {
select {
case <-sendDisconnect:
case <-manualDisconnect:
}
close(consoleDisconnect)
}()
fmt.Printf(i18n.G("To detach from the console, press: <ctrl>+a q") + "\n\r")
// Attach to the instance console
op, err := d.ConsoleInstance(name, req, &consoleArgs)
if err != nil {
return err
}
// Wait for the operation to complete
err = op.Wait()
if err != nil {
return err
}
return nil
}
func (c *cmdConsole) vga(d lxd.InstanceServer, name string) error {
var err error
conf := c.global.conf
// We currently use the control websocket just to abort in case of errors.
controlDone := make(chan struct{}, 1)
handler := func(control *websocket.Conn) {
<-controlDone
closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
control.WriteMessage(websocket.CloseMessage, closeMsg)
}
// Prepare the remote console.
req := api.InstanceConsolePost{
Type: "vga",
}
chDisconnect := make(chan bool)
chViewer := make(chan struct{})
consoleArgs := lxd.InstanceConsoleArgs{
Control: handler,
ConsoleDisconnect: chDisconnect,
}
// Setup local socket.
var socket string
var listener net.Listener
if runtime.GOOS != "windows" {
// Create a temporary unix socket mirroring the instance's spice socket.
if !shared.PathExists(conf.ConfigPath("sockets")) {
err := os.MkdirAll(conf.ConfigPath("sockets"), 0700)
if err != nil {
return err
}
}
// Generate a random file name.
path, err := ioutil.TempFile(conf.ConfigPath("sockets"), "*.spice")
if err != nil {
return err
}
path.Close()
err = os.Remove(path.Name())
if err != nil {
return err
}
// Listen on the socket.
listener, err = net.Listen("unix", path.Name())
if err != nil {
return err
}
defer os.Remove(path.Name())
socket = fmt.Sprintf("spice+unix://%s", path.Name())
} else {
listener, err = net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
addr := listener.Addr().(*net.TCPAddr)
socket = fmt.Sprintf("spice://127.0.0.1:%d", addr.Port)
}
// Clean everything up when the viewer is done.
go func() {
<-chViewer
listener.Close()
close(chDisconnect)
}()
// Spawn the remote console.
op, connect, err := d.ConsoleInstanceDynamic(name, req, &consoleArgs)
if err != nil {
close(chViewer)
return err
}
// Handle connections to the socket.
wgConnections := sync.WaitGroup{}
chConnected := make(chan struct{})
go func() {
hasConnected := false
for {
conn, err := listener.Accept()
if err != nil {
return
}
if !hasConnected {
hasConnected = true
close(chConnected)
}
wgConnections.Add(1)
go func(conn io.ReadWriteCloser) {
defer wgConnections.Done()
err = connect(conn)
if err != nil {
return
}
}(conn)
}
}()
// Use either spicy or remote-viewer if available.
remoteViewer := c.findCommand("remote-viewer")
spicy := c.findCommand("spicy")
if remoteViewer != "" || spicy != "" {
var cmd *exec.Cmd
if remoteViewer != "" {
cmd = exec.Command(remoteViewer, socket)
} else {
cmd = exec.Command(spicy, fmt.Sprintf("--uri=%s", socket))
}
// Start the command.
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Start()
// Handle the command exiting.
go func() {
cmd.Wait()
close(chViewer)
}()
// Kill the viewer on remote disconnection.
go func() {
<-chConnected
wgConnections.Wait()
if cmd.Process == nil {
return
}
cmd.Process.Kill()
}()
} else {
fmt.Println(i18n.G("LXD automatically uses either spicy or remote-viewer when present."))
fmt.Println(i18n.G("As neither could be found, the raw SPICE socket can be found at:"))
fmt.Printf(" %s\n", socket)
// Wait for all connections to complete.
<-chConnected
wgConnections.Wait()
close(chViewer)
}
// Wait for the operation to complete.
err = op.Wait()
if err != nil {
return err
}
return nil
}