-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathdebug_shell.go
More file actions
289 lines (245 loc) · 5.88 KB
/
debug_shell.go
File metadata and controls
289 lines (245 loc) · 5.88 KB
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
package dap
import (
"context"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"sync"
"github.com/docker/buildx/build"
"github.com/docker/buildx/util/ioset"
"github.com/docker/cli/cli-plugins/metadata"
"github.com/google/go-dap"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
type shell struct {
// SocketPath is set on the first time Init is invoked
// and stays that way.
SocketPath string
// Locks access to the session from the debug adapter.
// Only one debug thread can access the shell at a time.
sem *semaphore.Weighted
// Initialized once per shell and reused.
once sync.Once
err error
l net.Listener
eg *errgroup.Group
// For the specific session.
fwd *ioset.Forwarder
connected chan struct{}
mu sync.RWMutex
}
func newShell() *shell {
sh := &shell{
sem: semaphore.NewWeighted(1),
}
sh.resetSession()
return sh
}
func (s *shell) resetSession() {
s.mu.Lock()
defer s.mu.Unlock()
s.fwd = nil
s.connected = make(chan struct{})
}
// Init initializes the shell for connections on the client side.
// Attach will block until the terminal has been initialized.
func (s *shell) Init() error {
return s.listen()
}
func (s *shell) listen() error {
s.once.Do(func() {
var dir string
dir, s.err = os.MkdirTemp("", "buildx-dap-exec")
if s.err != nil {
return
}
defer func() {
if s.err != nil {
os.RemoveAll(dir)
}
}()
s.SocketPath = filepath.Join(dir, "s.sock")
lc := net.ListenConfig{}
s.l, s.err = lc.Listen(context.Background(), "unix", s.SocketPath)
if s.err != nil {
return
}
s.eg, _ = errgroup.WithContext(context.Background())
s.eg.Go(s.acceptLoop)
})
return s.err
}
func (s *shell) acceptLoop() error {
for {
if err := s.accept(); err != nil {
if errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
}
}
func (s *shell) accept() error {
conn, err := s.l.Accept()
if err != nil {
return err
}
s.mu.Lock()
defer s.mu.Unlock()
if s.fwd != nil {
writeLine(conn, "Error: Already connected to exec instance.")
conn.Close()
return nil
}
// Set the input of the forwarder to the connection.
s.fwd = ioset.NewForwarder()
s.fwd.SetIn(&ioset.In{
Stdin: io.NopCloser(conn),
Stdout: conn,
Stderr: nopCloser{conn},
})
close(s.connected)
writeLine(conn, "Attached to build process.")
return nil
}
// Attach will attach the given thread to the shell.
// Only one container can attach to a shell at any given time.
// Other attaches will block until the context is canceled or it is
// able to reserve the shell for its own use.
//
// This method is intended to be called by paused threads.
func (s *shell) Attach(ctx context.Context, t *thread) {
rCtx := t.rCtx
if rCtx == nil {
return
}
var f dap.StackFrame
if len(t.stackTrace) > 0 {
f = t.frames[t.stackTrace[0]].StackFrame
}
cfg := &build.InvokeConfig{Tty: true}
if len(cfg.Entrypoint) == 0 && len(cfg.Cmd) == 0 {
cfg.Entrypoint = []string{"/bin/sh"} // launch shell by default
cfg.Cmd = []string{}
cfg.NoCmd = false
}
for {
if err := s.attach(ctx, f, rCtx, cfg); err != nil {
return
}
}
}
func (s *shell) wait(ctx context.Context) error {
s.mu.RLock()
connected := s.connected
s.mu.RUnlock()
select {
case <-connected:
return nil
case <-ctx.Done():
return context.Cause(ctx)
}
}
func (s *shell) attach(ctx context.Context, f dap.StackFrame, rCtx *build.ResultHandle, cfg *build.InvokeConfig) (retErr error) {
if err := s.wait(ctx); err != nil {
return err
}
in, out := ioset.Pipe()
defer in.Close()
defer out.Close()
s.mu.RLock()
fwd := s.fwd
s.mu.RUnlock()
fwd.SetOut(&out)
defer func() {
if retErr != nil {
fwd.SetOut(nil)
}
}()
if err := s.sem.Acquire(ctx, 1); err != nil {
return err
}
defer s.sem.Release(1)
ctr, err := build.NewContainer(ctx, rCtx, cfg)
if err != nil {
return err
}
defer ctr.Cancel()
// Check if the entrypoint is executable. If it isn't, don't bother
// trying to invoke.
if reason, ok := ctr.CanInvoke(ctx, cfg); !ok {
writeLineF(in.Stdout, "Build container is not executable. (reason: %s)", reason)
<-ctx.Done()
return context.Cause(ctx)
}
writeLineF(in.Stdout, "Running %s in build container from line %d.",
strings.Join(append(cfg.Entrypoint, cfg.Cmd...), " "),
f.Line,
)
writeLine(in.Stdout, "Changes to the container will be reset after the next step is executed.")
err = ctr.Exec(ctx, cfg, in.Stdin, in.Stdout, in.Stderr)
// Send newline to properly terminate the output.
writeLine(in.Stdout, "")
if err != nil {
return err
}
fwd.Close()
s.resetSession()
return nil
}
// SendRunInTerminalRequest will send the request to the client to attach to
// the socket path that was created by Init. This is intended to be run
// from the adapter and interact directly with the client.
func (s *shell) SendRunInTerminalRequest(ctx Context) error {
var args []string
if docker := os.Getenv(metadata.ReexecEnvvar); docker != "" {
args = []string{docker, "buildx"}
} else if len(os.Args) > 0 {
args = []string{os.Args[0]}
} else {
return errors.New("cannot find exec target for buildx")
}
args = append(args, "dap", "attach", s.SocketPath)
req := &dap.RunInTerminalRequest{
Request: dap.Request{
Command: "runInTerminal",
},
Arguments: dap.RunInTerminalRequestArguments{
Kind: "integrated",
Args: args,
Env: map[string]any{
"BUILDX_EXPERIMENTAL": "1",
},
},
}
resp := ctx.Request(req)
if !resp.GetResponse().Success {
return errors.New(resp.GetResponse().Message)
}
return nil
}
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error {
return nil
}
func writeLine(w io.Writer, msg string) {
if os.PathSeparator == '\\' {
fmt.Fprint(w, msg+"\r\n")
} else {
fmt.Fprintln(w, msg)
}
}
func writeLineF(w io.Writer, format string, a ...any) {
if os.PathSeparator == '\\' {
fmt.Fprintf(w, format+"\r\n", a...)
} else {
fmt.Fprintf(w, format+"\n", a...)
}
}