-
Notifications
You must be signed in to change notification settings - Fork 9
/
terminalapi.go
79 lines (63 loc) · 1.88 KB
/
terminalapi.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package devsession
import (
"context"
"fmt"
"io"
"net/http"
"github.com/gorilla/websocket"
"google.golang.org/protobuf/encoding/protojson"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/console/termios"
"namespacelabs.dev/foundation/internal/runtime"
)
func serveTerminal(s sessionLike, w http.ResponseWriter, r *http.Request, serverID string) {
serveStream("terminal", w, r, func(ctx context.Context, ws *websocket.Conn, w io.Writer) error {
// XXX rather than obtaining the current one, it should be encoded in the request to logs.
cluster, server, err := s.ResolveServer(r.Context(), serverID)
if err != nil {
return err
}
inr, inw := io.Pipe()
resizeCh := make(chan termios.WinSize, 1)
go func() {
defer inr.Close()
defer close(resizeCh)
readerLoop(ctx, ws, func(b []byte) error {
ti := &TerminalInput{}
if err := protojson.Unmarshal(b, ti); err != nil {
return err
}
if ti.Stdin != nil {
if _, err := inw.Write(ti.Stdin); err != nil {
return err
}
}
if ti.Resize != nil {
w := ti.Resize.Width
h := ti.Resize.Height
if w > 0xffff {
w = 0xffff
}
if h > 0xffff {
h = 0xffff
}
fmt.Fprintf(console.Debug(ctx), "(%s) resizing terminal %dx%d\n", r.RemoteAddr, w, h)
resizeCh <- termios.WinSize{
Width: uint16(w),
Height: uint16(h),
}
}
return nil
})
}()
// Returns when stdout is drained; which may happen when w fails to write, e.g. when ws is closed.
return cluster.StartTerminal(ctx, server, runtime.TerminalIO{
TTY: true,
Stdin: inr, Stdout: w, Stderr: w,
ResizeQueue: resizeCh,
}, "sh")
})
}