-
Notifications
You must be signed in to change notification settings - Fork 907
/
instance_console.go
750 lines (621 loc) · 17.9 KB
/
instance_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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"time"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
liblxc "github.com/lxc/go-lxc"
"golang.org/x/sys/unix"
"github.com/canonical/lxd/lxd/cluster"
"github.com/canonical/lxd/lxd/db/operationtype"
"github.com/canonical/lxd/lxd/instance"
"github.com/canonical/lxd/lxd/instance/instancetype"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/request"
"github.com/canonical/lxd/lxd/response"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/version"
"github.com/canonical/lxd/shared/ws"
)
type consoleWs struct {
// instance currently worked on
instance instance.Instance
// websocket connections to bridge pty fds to
conns map[int]*websocket.Conn
// map dynamic websocket connections to their associated console file
dynamic map[*websocket.Conn]*os.File
// locks needed to access the "conns" member
connsLock sync.Mutex
// channel to wait until all websockets are properly connected
allConnected chan bool
// channel to wait until the control socket is connected
controlConnected chan bool
// map file descriptors to secret
fds map[int]string
// terminal width
width int
// terminal height
height int
// channel type (either console or vga)
protocol string
}
// Metadata returns a map of metadata.
func (s *consoleWs) Metadata() any {
fds := shared.Jmap{}
for fd, secret := range s.fds {
if fd == -1 {
fds[api.SecretNameControl] = secret
} else {
fds[strconv.Itoa(fd)] = secret
}
}
return shared.Jmap{"fds": fds}
}
// Connect connects to the websocket.
func (s *consoleWs) Connect(op *operations.Operation, r *http.Request, w http.ResponseWriter) error {
switch s.protocol {
case instance.ConsoleTypeConsole:
return s.connectConsole(op, r, w)
case instance.ConsoleTypeVGA:
return s.connectVGA(op, r, w)
default:
return fmt.Errorf("Unknown protocol %q", s.protocol)
}
}
func (s *consoleWs) connectConsole(op *operations.Operation, r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
}
for fd, fdSecret := range s.fds {
if secret == fdSecret {
conn, err := ws.Upgrader.Upgrade(w, r, nil)
if err != nil {
return err
}
s.connsLock.Lock()
s.conns[fd] = conn
s.connsLock.Unlock()
if fd == -1 {
s.controlConnected <- true
return nil
}
s.connsLock.Lock()
for i, c := range s.conns {
if i != -1 && c == nil {
s.connsLock.Unlock()
return nil
}
}
s.connsLock.Unlock()
s.allConnected <- true
return nil
}
}
/* If we didn't find the right secret, the user provided a bad one,
* which 403, not 404, since this operation actually exists */
return os.ErrPermission
}
func (s *consoleWs) connectVGA(op *operations.Operation, r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
}
for fd, fdSecret := range s.fds {
if secret != fdSecret {
continue
}
conn, err := ws.Upgrader.Upgrade(w, r, nil)
if err != nil {
return err
}
if fd == -1 {
logger.Debug("VGA control websocket connected")
s.connsLock.Lock()
s.conns[fd] = conn
s.connsLock.Unlock()
s.controlConnected <- true
return nil
}
logger.Debug("VGA dynamic websocket connected")
console, _, err := s.instance.Console("vga")
if err != nil {
_ = conn.Close()
return err
}
// Mirror the console and websocket.
go func() {
l := logger.AddContext(logger.Ctx{"address": conn.RemoteAddr().String()})
defer l.Debug("Finished mirroring websocket to console")
l.Debug("Started mirroring websocket")
readDone, writeDone := ws.Mirror(conn, console)
<-readDone
l.Debug("Finished mirroring console to websocket")
<-writeDone
}()
s.connsLock.Lock()
s.dynamic[conn] = console
s.connsLock.Unlock()
return nil
}
// If we didn't find the right secret, the user provided a bad one,
// which 403, not 404, since this operation actually exists.
return os.ErrPermission
}
// Do connects to the websocket and executes the operation.
func (s *consoleWs) Do(op *operations.Operation) error {
switch s.protocol {
case instance.ConsoleTypeConsole:
return s.doConsole(op)
case instance.ConsoleTypeVGA:
return s.doVGA(op)
default:
return fmt.Errorf("Unknown protocol %q", s.protocol)
}
}
func (s *consoleWs) doConsole(op *operations.Operation) error {
defer logger.Debug("Console websocket finished")
<-s.allConnected
// Get console from instance.
console, consoleDisconnectCh, err := s.instance.Console(s.protocol)
if err != nil {
return err
}
defer func() { _ = console.Close() }()
// Detect size of window and set it into console.
if s.width > 0 && s.height > 0 {
_ = shared.SetSize(int(console.Fd()), s.width, s.height)
}
consoleDoneCh := make(chan struct{})
// Wait for control socket to connect and then read messages from the remote side in a loop.
go func() {
defer logger.Debugf("Console control websocket finished")
res := <-s.controlConnected
if !res {
return
}
for {
s.connsLock.Lock()
conn := s.conns[-1]
s.connsLock.Unlock()
_, r, err := conn.NextReader()
if err != nil {
logger.Debugf("Got error getting next reader: %v", err)
close(consoleDoneCh)
return
}
buf, err := io.ReadAll(r)
if err != nil {
logger.Debugf("Failed to read message: %v", err)
break
}
command := api.InstanceConsoleControl{}
err = json.Unmarshal(buf, &command)
if err != nil {
logger.Debugf("Failed to unmarshal control socket command: %s", err)
continue
}
if command.Command == "window-resize" {
winchWidth, err := strconv.Atoi(command.Args["width"])
if err != nil {
logger.Debugf("Unable to extract window width: %s", err)
continue
}
winchHeight, err := strconv.Atoi(command.Args["height"])
if err != nil {
logger.Debugf("Unable to extract window height: %s", err)
continue
}
err = shared.SetSize(int(console.Fd()), winchWidth, winchHeight)
if err != nil {
logger.Debugf("Failed to set window size to: %dx%d", winchWidth, winchHeight)
continue
}
logger.Debugf("Set window size to: %dx%d", winchWidth, winchHeight)
}
}
}()
// Mirror the console and websocket.
mirrorDoneCh := make(chan struct{})
go func() {
s.connsLock.Lock()
conn := s.conns[0]
s.connsLock.Unlock()
l := logger.AddContext(logger.Ctx{"address": conn.RemoteAddr().String()})
defer l.Debug("Finished mirroring websocket to console")
l.Debug("Started mirroring websocket")
readDone, writeDone := ws.Mirror(conn, console)
<-readDone
l.Debug("Finished mirroring console to websocket")
<-writeDone
close(mirrorDoneCh)
}()
// Wait until either the console or the websocket is done.
select {
case <-mirrorDoneCh:
close(consoleDisconnectCh)
case <-consoleDoneCh:
close(consoleDisconnectCh)
}
// Get the console and control websockets.
s.connsLock.Lock()
consoleConn := s.conns[0]
ctrlConn := s.conns[-1]
s.connsLock.Unlock()
defer func() {
_ = consoleConn.WriteMessage(websocket.BinaryMessage, []byte("\n\r"))
_ = consoleConn.Close()
_ = ctrlConn.Close()
}()
// Write a reset escape sequence to the console to cancel any ongoing reads to the handle
// and then close it. This ordering is important, close the console before closing the
// websocket to ensure console doesn't get stuck reading.
_, err = console.Write([]byte("\x1bc"))
if err != nil {
_ = console.Close()
return err
}
err = console.Close()
if err != nil {
return err
}
// Indicate to the control socket go routine to end if not already.
close(s.controlConnected)
return nil
}
func (s *consoleWs) doVGA(op *operations.Operation) error {
defer logger.Debug("VGA websocket finished")
consoleDoneCh := make(chan struct{})
// The control socket is used to terminate the operation.
go func() {
defer logger.Debugf("VGA control websocket finished")
res := <-s.controlConnected
if !res {
return
}
for {
s.connsLock.Lock()
conn := s.conns[-1]
s.connsLock.Unlock()
_, _, err := conn.NextReader()
if err != nil {
logger.Debugf("Got error getting next reader: %v", err)
close(consoleDoneCh)
return
}
}
}()
// Wait until the control channel is done.
<-consoleDoneCh
s.connsLock.Lock()
control := s.conns[-1]
s.connsLock.Unlock()
err := control.Close()
// Close all dynamic connections.
for conn, console := range s.dynamic {
_ = conn.Close()
_ = console.Close()
}
// Indicate to the control socket go routine to end if not already.
close(s.controlConnected)
return err
}
// swagger:operation POST /1.0/instances/{name}/console instances instance_console_post
//
// Connect to console
//
// Connects to the console of an instance.
//
// The returned operation metadata will contain two websockets, one for data and one for control.
//
// ---
// consumes:
// - application/json
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// - in: body
// name: console
// description: Console request
// schema:
// $ref: "#/definitions/InstanceConsolePost"
// responses:
// "202":
// $ref: "#/responses/Operation"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "500":
// $ref: "#/responses/InternalServerError"
func instanceConsolePost(d *Daemon, r *http.Request) response.Response {
s := d.State()
instanceType, err := urlInstanceTypeDetect(r)
if err != nil {
return response.SmartError(err)
}
projectName := request.ProjectParam(r)
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
if shared.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
}
post := api.InstanceConsolePost{}
buf, err := io.ReadAll(r.Body)
if err != nil {
return response.BadRequest(err)
}
err = json.Unmarshal(buf, &post)
if err != nil {
return response.BadRequest(err)
}
// Forward the request if the container is remote.
client, err := cluster.ConnectIfInstanceIsRemote(s, projectName, name, r, instanceType)
if err != nil {
return response.SmartError(err)
}
if client != nil {
url := api.NewURL().Path(version.APIVersion, "instances", name, "console").Project(projectName)
resp, _, err := client.RawQuery("POST", url.String(), post, "")
if err != nil {
return response.SmartError(err)
}
opAPI, err := resp.MetadataAsOperation()
if err != nil {
return response.SmartError(err)
}
return operations.ForwardedOperationResponse(projectName, opAPI)
}
if post.Type == "" {
post.Type = instance.ConsoleTypeConsole
}
// Basic parameter validation.
if !shared.ValueInSlice(post.Type, []string{instance.ConsoleTypeConsole, instance.ConsoleTypeVGA}) {
return response.BadRequest(fmt.Errorf("Unknown console type %q", post.Type))
}
inst, err := instance.LoadByProjectAndName(s, projectName, name)
if err != nil {
return response.SmartError(err)
}
if post.Type == instance.ConsoleTypeVGA && inst.Type() != instancetype.VM {
return response.BadRequest(fmt.Errorf("VGA console is only supported by virtual machines"))
}
if !inst.IsRunning() {
return response.BadRequest(fmt.Errorf("Instance is not running"))
}
if inst.IsFrozen() {
return response.BadRequest(fmt.Errorf("Instance is frozen"))
}
ws := &consoleWs{}
ws.fds = map[int]string{}
ws.conns = map[int]*websocket.Conn{}
ws.conns[-1] = nil
ws.conns[0] = nil
ws.dynamic = map[*websocket.Conn]*os.File{}
for i := -1; i < len(ws.conns)-1; i++ {
ws.fds[i], err = shared.RandomCryptoString()
if err != nil {
return response.InternalError(err)
}
}
ws.allConnected = make(chan bool, 1)
ws.controlConnected = make(chan bool, 1)
ws.instance = inst
ws.width = post.Width
ws.height = post.Height
ws.protocol = post.Type
resources := map[string][]api.URL{}
resources["instances"] = []api.URL{*api.NewURL().Path(version.APIVersion, "instances", ws.instance.Name())}
if inst.Type() == instancetype.Container {
resources["containers"] = resources["instances"]
}
op, err := operations.OperationCreate(s, projectName, operations.OperationClassWebsocket, operationtype.ConsoleShow, resources, ws.Metadata(), ws.Do, nil, ws.Connect, r)
if err != nil {
return response.InternalError(err)
}
return operations.OperationResponse(op)
}
// swagger:operation GET /1.0/instances/{name}/console instances instance_console_get
//
// Get console log
//
// Gets the console log for the instance.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// responses:
// "200":
// description: Raw console log
// content:
// application/octet-stream:
// schema:
// type: string
// example: some-text
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "404":
// $ref: "#/responses/NotFound"
// "500":
// $ref: "#/responses/InternalServerError"
func instanceConsoleLogGet(d *Daemon, r *http.Request) response.Response {
s := d.State()
instanceType, err := urlInstanceTypeDetect(r)
if err != nil {
return response.SmartError(err)
}
projectName := request.ProjectParam(r)
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
if shared.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
}
// Forward the request if the container is remote.
resp, err := forwardedResponseIfInstanceIsRemote(s, r, projectName, name, instanceType)
if err != nil {
return response.SmartError(err)
}
if resp != nil {
return resp
}
if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) {
return response.BadRequest(fmt.Errorf("Querying the console buffer requires liblxc >= 3.0"))
}
inst, err := instance.LoadByProjectAndName(s, projectName, name)
if err != nil {
return response.SmartError(err)
}
if inst.Type() != instancetype.Container {
return response.SmartError(fmt.Errorf("Instance is not container type"))
}
c, ok := inst.(instance.Container)
if !ok {
return response.SmartError(fmt.Errorf("Invalid instance type"))
}
ent := response.FileResponseEntry{}
if !c.IsRunning() {
// Hand back the contents of the console ringbuffer logfile.
consoleBufferLogPath := c.ConsoleBufferLogPath()
ent.Path = consoleBufferLogPath
ent.Filename = consoleBufferLogPath
return response.FileResponse(r, []response.FileResponseEntry{ent}, nil)
}
// Query the container's console ringbuffer.
console := liblxc.ConsoleLogOptions{
ClearLog: false,
ReadLog: true,
ReadMax: 0,
WriteToLogFile: true,
}
// Send a ringbuffer request to the container.
logContents, err := c.ConsoleLog(console)
if err != nil {
errno, isErrno := shared.GetErrno(err)
if !isErrno {
return response.SmartError(err)
}
if errno == unix.ENODATA {
return response.FileResponse(r, []response.FileResponseEntry{ent}, nil)
}
return response.SmartError(err)
}
ent.File = bytes.NewReader([]byte(logContents))
ent.FileModified = time.Now()
ent.FileSize = int64(len(logContents))
return response.FileResponse(r, []response.FileResponseEntry{ent}, nil)
}
// swagger:operation DELETE /1.0/instances/{name}/console instances instance_console_delete
//
// Clear the console log
//
// Clears the console log buffer.
//
// ---
// produces:
// - application/json
// parameters:
// - in: query
// name: project
// description: Project name
// type: string
// example: default
// responses:
// "200":
// $ref: "#/responses/EmptySyncResponse"
// "400":
// $ref: "#/responses/BadRequest"
// "403":
// $ref: "#/responses/Forbidden"
// "404":
// $ref: "#/responses/NotFound"
// "500":
// $ref: "#/responses/InternalServerError"
func instanceConsoleLogDelete(d *Daemon, r *http.Request) response.Response {
if !liblxc.RuntimeLiblxcVersionAtLeast(liblxc.Version(), 3, 0, 0) {
return response.BadRequest(fmt.Errorf("Clearing the console buffer requires liblxc >= 3.0"))
}
name, err := url.PathUnescape(mux.Vars(r)["name"])
if err != nil {
return response.SmartError(err)
}
if shared.IsSnapshot(name) {
return response.BadRequest(fmt.Errorf("Invalid instance name"))
}
projectName := request.ProjectParam(r)
inst, err := instance.LoadByProjectAndName(d.State(), projectName, name)
if err != nil {
return response.SmartError(err)
}
if inst.Type() != instancetype.Container {
return response.SmartError(fmt.Errorf("Instance is not container type"))
}
c, ok := inst.(instance.Container)
if !ok {
return response.SmartError(fmt.Errorf("Invalid instance type"))
}
truncateConsoleLogFile := func(path string) error {
// Check that this is a regular file. We don't want to try and unlink
// /dev/stderr or /dev/null or something.
st, err := os.Stat(path)
if err != nil {
return err
}
if !st.Mode().IsRegular() {
return fmt.Errorf("The console log is not a regular file")
}
if path == "" {
return fmt.Errorf("Container does not keep a console logfile")
}
return os.Truncate(path, 0)
}
if !inst.IsRunning() {
consoleLogpath := c.ConsoleBufferLogPath()
return response.SmartError(truncateConsoleLogFile(consoleLogpath))
}
// Send a ringbuffer request to the container.
console := liblxc.ConsoleLogOptions{
ClearLog: true,
ReadLog: false,
ReadMax: 0,
WriteToLogFile: false,
}
_, err = c.ConsoleLog(console)
if err != nil {
errno, isErrno := shared.GetErrno(err)
if !isErrno {
return response.SmartError(err)
}
if errno == unix.ENODATA {
return response.SmartError(nil)
}
return response.SmartError(err)
}
return response.SmartError(nil)
}