-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmanager.go
More file actions
426 lines (366 loc) · 11.5 KB
/
Copy pathmanager.go
File metadata and controls
426 lines (366 loc) · 11.5 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
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
//go:build !windows
package terminal
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"sync"
"syscall"
"time"
"github.com/creack/pty" // Import the pty package for creating pseudo-terminal devices.
"github.com/google/uuid" // UUID package for generating unique identifiers.
logging "github.com/omniviewdev/plugin-sdk/log"
"github.com/omniviewdev/omniview/backend/pkg/apperror"
sdkexec "github.com/omniviewdev/plugin-sdk/pkg/v1/exec"
"github.com/omniviewdev/plugin-sdk/pkg/types"
)
const (
DefaultLocalShell = "/bin/zsh"
DefaultReadBufferSize = 20480
InitialRows = 27
InitialCols = 72
)
// Manager manages terminal sessions, allowing creation, attachment, and more.
type Manager struct {
ctx context.Context
log logging.Logger
sessions map[string]*sdkexec.Session
ptys map[string]*os.File
cmds map[string]*exec.Cmd
cancels map[string]context.CancelFunc
buffers map[string]*sdkexec.OutputBuffer
inMux chan sdkexec.StreamInput
outMux chan sdkexec.StreamOutput
resizeMux chan sdkexec.StreamResize
mux sync.RWMutex
}
// NewManager initializes a new Manager instance. Because we want to be a bit more
// latency sensitive with the local manager, we're going to directly return
// the channels for in and out that the exec controller will use.
func NewManager(
ctx context.Context,
log logging.Logger,
) (*Manager, chan sdkexec.StreamInput, chan sdkexec.StreamOutput, chan sdkexec.StreamResize) {
inMux := make(chan sdkexec.StreamInput)
outMux := make(chan sdkexec.StreamOutput)
resizeMux := make(chan sdkexec.StreamResize)
mgr := &Manager{
ctx: ctx,
log: log.Named("TerminalManager"),
sessions: make(map[string]*sdkexec.Session),
ptys: make(map[string]*os.File),
cmds: make(map[string]*exec.Cmd),
cancels: make(map[string]context.CancelFunc),
buffers: make(map[string]*sdkexec.OutputBuffer),
inMux: inMux,
outMux: outMux,
resizeMux: resizeMux,
}
go mgr.forwardSignals()
return mgr, inMux, outMux, resizeMux
}
// GetSession returns a session by its ID.
func (m *Manager) GetSession(sessionID string) (*sdkexec.Session, error) {
m.mux.RLock()
defer m.mux.RUnlock()
session, exists := m.sessions[sessionID]
if !exists {
return nil, apperror.SessionNotFound(sessionID)
}
return session, nil
}
// ListSessions returns a list of details for all active sessions.
func (m *Manager) ListSessions(_ *types.PluginContext) []*sdkexec.Session {
m.mux.RLock()
defer m.mux.RUnlock()
sessions := make([]*sdkexec.Session, 0, len(m.sessions))
for _, session := range m.sessions {
sessions = append(sessions, session)
}
m.log.Debugw(context.Background(), "listed sessions", "count", len(sessions))
return sessions
}
// StartSession creates a new terminal session with a given command.
func (m *Manager) StartSession(
pCtx *types.PluginContext,
opts sdkexec.SessionOptions,
) (*sdkexec.Session, error) {
logger := m.log.With(logging.Any("action", "StartSession"))
logger.Debugw(context.Background(), "starting session", "command", opts.Command, "tty", opts.TTY)
// Derive from manager context so shutdown cascades to all sessions.
ctx, cancel := context.WithCancel(m.ctx)
// determine the default shell from the commands passed in, since we may want to add flags
shell := DefaultLocalShell
newopts := []string{}
if len(opts.Command) > 0 {
switch opts.Command[0] {
// test for active shells
case "zsh":
shell = "zsh"
newopts = []string{"--login", "-i"}
newopts = append(newopts, opts.Command[1:]...)
case "/bin/zsh":
shell = "/bin/zsh"
newopts = []string{"--login", "-i"}
newopts = append(newopts, opts.Command[1:]...)
case "bash":
shell = "bash"
newopts = []string{"--login"}
newopts = append(newopts, opts.Command[1:]...)
case "/bin/bash":
shell = "/bin/bash"
newopts = []string{"--login"}
newopts = append(newopts, opts.Command[1:]...)
case "sh":
shell = "sh"
case "/bin/sh":
shell = "/bin/sh"
}
}
// start default shell with commands appended to it
//nolint:gosec // whole point is to get a local shell from the local IDE, so this is just
// going to be exactly what the user wants
cmd := exec.CommandContext(ctx, shell, newopts...)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("SHELL=%s", shell), "TERM=xterm-256color")
if opts.Labels == nil {
opts.Labels = make(map[string]string)
}
ptyFile, err := pty.Start(cmd)
if err != nil {
err = apperror.Wrap(err, apperror.TypeSessionFailed, 500, "Failed to start terminal")
logger.Errorw(ctx, "failed to start terminal", "error", err)
cancel()
return nil, err
}
// set an initial size for the pty, otherwise we get really weird behavior
if err = pty.Setsize(ptyFile, &pty.Winsize{Rows: InitialRows, Cols: InitialCols}); err != nil {
err = apperror.Wrap(err, apperror.TypeSessionFailed, 500, "Failed to configure terminal size")
cancel()
return nil, err
}
// Generate a unique ID for the session.
if opts.ID == "" {
opts.ID = uuid.NewString()
}
session := &sdkexec.Session{
ID: opts.ID,
Command: opts.Command,
Labels: opts.Labels,
Params: opts.Params,
Attached: false,
CreatedAt: time.Now(),
}
m.mux.Lock()
m.sessions[opts.ID] = session
m.ptys[opts.ID] = ptyFile
m.cmds[opts.ID] = cmd
m.cancels[opts.ID] = cancel
m.buffers[opts.ID] = sdkexec.NewDefaultOutputBuffer()
m.mux.Unlock()
logger.Debugw(ctx, "session started",
"session", session,
"command", session.Command,
)
// Start handling terminal output in a separate goroutine.
go m.handleOutStream(ctx, opts.ID, ptyFile)
go m.handleSessionClose(ctx, opts.ID)
go m.handleWaitForCompletion(ctx, opts.ID, cmd)
return session, nil
}
func (m *Manager) ResizeSession(sessionID string, rows, cols uint16) error {
m.mux.RLock()
defer m.mux.RUnlock()
ptyFile, exists := m.ptys[sessionID]
if !exists {
err := apperror.SessionNotFound(sessionID)
m.log.Errorw(context.Background(), "session not found", "error", err)
return err
}
if err := pty.Setsize(ptyFile, &pty.Winsize{Rows: rows, Cols: cols}); err != nil {
m.log.Errorw(context.Background(), "error resizing pty", "session", sessionID, "error", err)
return err
}
return nil
}
func (m *Manager) handleWaitForCompletion(_ context.Context, sessionID string, cmd *exec.Cmd) {
if err := cmd.Wait(); err != nil {
m.log.Errorw(context.Background(), "error waiting for command", "session", sessionID, "error", err)
}
m.terminateSession(sessionID)
}
// forwardSignals listens for host-process signals once and forwards them to
// all active terminal child processes. Runs for the lifetime of the Manager.
func (m *Manager) forwardSignals() {
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT)
defer signal.Stop(ch)
for {
select {
case sig := <-ch:
m.mux.RLock()
for sid, cmd := range m.cmds {
if cmd.Process != nil {
if err := cmd.Process.Signal(sig); err != nil {
m.log.Debugw(context.Background(), "failed to forward signal",
"signal", sig, "session", sid, "error", err)
}
}
}
m.mux.RUnlock()
case <-m.ctx.Done():
return
}
}
}
// handleSessionClose waits for a session's context to be cancelled and emits
// a CLOSE signal to the frontend.
func (m *Manager) handleSessionClose(ctx context.Context, sessionID string) {
<-ctx.Done()
m.outMux <- sdkexec.StreamOutput{
SessionID: sessionID,
Target: sdkexec.StreamTargetStdOut,
Data: []byte("Session terminated"),
Signal: sdkexec.StreamSignalClose,
}
}
func (m *Manager) handleOutStream(
_ context.Context,
sessionID string,
stream io.Reader,
) {
for {
buf := make([]byte, DefaultReadBufferSize)
read, err := stream.Read(buf)
if err != nil {
if err != io.EOF {
m.log.Errorw(context.Background(),
"error reading from stream",
"session", sessionID,
"error", err,
)
}
m.mux.RLock()
_, exists := m.sessions[sessionID]
m.mux.RUnlock()
if exists {
m.terminateSession(sessionID)
}
return
}
if len(buf) > 0 {
m.outMux <- sdkexec.StreamOutput{
SessionID: sessionID,
Target: sdkexec.StreamTargetStdOut,
Data: buf[:read],
}
m.mux.RLock()
buffer, ok := m.buffers[sessionID]
m.mux.RUnlock()
if !ok {
// soft error
m.log.Errorw(context.Background(), "failed to write to session buffer: couldn't find session")
continue
}
buffer.Append(buf[:read])
}
}
}
// WriteToSession writes a string to the session's input.
func (m *Manager) writeToSession(sessionID string, bytes []byte) error {
m.mux.RLock()
defer m.mux.RUnlock()
ptyFile, exists := m.ptys[sessionID]
if !exists {
err := apperror.SessionNotFound(sessionID)
m.log.Errorw(context.Background(), "session not found", "error", err)
return err
}
if _, err := ptyFile.Write(bytes); err != nil {
m.log.Errorw(context.Background(), "error writing to session", "session", sessionID, "error", err)
return err
}
return nil
}
// WriteSession writes data to the session's input.
func (m *Manager) WriteSession(sessionID string, input []byte) error {
return m.writeToSession(sessionID, input)
}
// AttachToSession marks a session as attached and returns its current output buffer.
func (m *Manager) AttachSession(sessionID string) (*sdkexec.Session, []byte, error) {
m.mux.Lock()
defer m.mux.Unlock()
session, exists := m.sessions[sessionID]
if !exists {
err := apperror.SessionNotFound(sessionID)
m.log.Errorw(context.Background(), "session not found", "error", err)
return nil, nil, err
}
buffer := m.buffers[sessionID]
var data []byte
if buffer != nil {
data = buffer.GetAll()
}
m.log.Debugw(context.Background(), "session buffer loaded", "session", sessionID, "bufferSize", len(data))
// pointer, no need to reassign
session.Attached = true
m.outMux <- sdkexec.StreamOutput{
SessionID: sessionID,
Target: sdkexec.StreamTargetStdOut,
Data: data,
}
m.log.Debugw(context.Background(), "session attached", "session", sessionID)
return session, data, nil
}
// DetachFromSession marks a session as not attached, stopping output broadcast.
func (m *Manager) DetachSession(sessionID string) (*sdkexec.Session, error) {
m.mux.Lock()
defer m.mux.Unlock()
session, exists := m.sessions[sessionID]
if !exists {
err := apperror.SessionNotFound(sessionID)
m.log.Errorw(context.Background(), "session not found", "error", err)
return nil, err
}
session.Attached = false
m.log.Debugw(context.Background(), "session detached", "session", sessionID)
return session, nil
}
// CloseSession cancels the session's context, effectively terminating
// its command, and removes it from the manager.
func (m *Manager) CloseSession(sessionID string) error {
m.mux.Lock()
defer m.mux.Unlock()
_, exists := m.sessions[sessionID]
if !exists {
err := apperror.SessionNotFound(sessionID)
m.log.Errorw(context.Background(), "session not found", "error", err)
return err
}
m.terminateSessionLocked(sessionID)
return nil
}
// terminateSession acquires the lock and terminates the session.
func (m *Manager) terminateSession(sessionID string) {
m.mux.Lock()
defer m.mux.Unlock()
m.terminateSessionLocked(sessionID)
}
// terminateSessionLocked terminates a session. Caller must hold m.mux.
func (m *Manager) terminateSessionLocked(sessionID string) {
if cancel, ok := m.cancels[sessionID]; ok {
cancel()
}
if ptyFile, ok := m.ptys[sessionID]; ok {
ptyFile.Close()
}
delete(m.sessions, sessionID)
delete(m.ptys, sessionID)
delete(m.cmds, sessionID)
delete(m.cancels, sessionID)
delete(m.buffers, sessionID)
m.log.Debugw(context.Background(), "session terminated", "session", sessionID)
}