This repository has been archived by the owner on Jun 14, 2021. It is now read-only.
/
pseudoterm.go
375 lines (302 loc) · 7.78 KB
/
pseudoterm.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
/*
Package pseudoterm is a framework for running iterative programs programmatically with Go.
https://github.com/henvic/picel
*/
package pseudoterm
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"regexp"
"strings"
"time"
"github.com/kr/pty"
)
var (
// EOT is the End Of Transmission character
EOT = []byte{4}
// LineReaderInterval is the time to sleep between checks for output
// Too low or too high mess things up (lower performance or high CPU usage).
LineReaderInterval = 10 * time.Millisecond
// SkipWrite is used as a return value from Story HandleLine to indicate
// that a line should not be written when reading a line on a given step.
SkipWrite = errors.New("Skip writing line input")
// SkipZeroMatches is used as a return value from Story HandleLine to indicate
// that there are no more steps left to be dealt with.
SkipZeroMatches = errors.New("Skip line input due to no match available")
// ErrUnsupported is used to indicate there is
ErrUnsupported = pty.ErrUnsupported
)
// Terminal is a pseudo terminal you can use to run commands
// on a pseudo tty programmatically
type Terminal struct {
Command *exec.Cmd
EchoStream io.Writer
CopyStreamError error
processState *os.ProcessState
terminal *os.File
bfs *bytes.Buffer
end chan empty
}
// Story is interface you can implement to handle commands
type Story interface {
Setup() (ctx context.Context, err error)
Teardown()
TickHandler() (err error)
HandleLine(s string) (in string, err error)
}
// ExecutionError indicates if any happened during the execution
type ExecutionError struct {
RunError error
SigtermError error
}
func (e ExecutionError) Error() string {
var msgs []string
if e.RunError != nil {
msgs = append(msgs, "Run error: "+e.RunError.Error())
}
if e.SigtermError != nil {
msgs = append(msgs, "SIGTERM signal error: "+e.SigtermError.Error())
}
return strings.Join(msgs, "; ")
}
type empty struct{}
// Run starts the program and handle lines printed by it
func (t *Terminal) Run(story Story) (err error) {
if err = t.Start(); err != nil {
return err
}
err = t.Watch(story)
var et = t.Stop()
if err == nil && et == nil {
return nil
}
return ExecutionError{
RunError: err,
SigtermError: et,
}
}
// Stop the program
func (t *Terminal) Stop() (err error) {
if t.processState == nil {
if _, err = t.Write(EOT); err != nil {
return err
}
return t.terminal.Close()
}
return err
}
// Start the program
func (t *Terminal) Start() (err error) {
if t.terminal != nil {
return errors.New("Already started")
}
t.end = make(chan empty, 1)
t.terminal, err = pty.Start(t.Command)
if err == nil {
t.copyStreamToBuffer()
go func() {
// we don't care if process was terminated correctly or not
// as we only care about having an open connection to it or not
t.processState, _ = t.Command.Process.Wait()
t.end <- empty{}
}()
}
return err
}
// Wait for process to end and return process state
func (t *Terminal) Wait() (ps *os.ProcessState) {
<-t.end
return t.processState
}
// Write bytes to the pseudo terminal
func (t *Terminal) Write(b []byte) (n int, err error) {
return t.terminal.Write(b)
}
// WriteString to the pseudo terminal
func (t *Terminal) WriteString(s string) (n int, err error) {
return t.terminal.WriteString(s)
}
// WriteLine to the pseudo terminal
func (t *Terminal) WriteLine(s string) (n int, err error) {
return t.terminal.WriteString(s + "\n")
}
// Watch starts handling lines printed by the program
func (t *Terminal) Watch(s Story) error {
defer s.Teardown()
var ctx, err = s.Setup()
if err != nil {
return err
}
var ok bool
var endReadLine = make(chan empty, 1)
go func() {
ok, err = t.readLine(s)
endReadLine <- empty{}
}()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-endReadLine:
if ok || err != nil {
return err
}
go func() {
ok, err = t.readLine(s)
endReadLine <- empty{}
}()
default:
time.Sleep(LineReaderInterval)
}
}
}
func (t *Terminal) copyStreamToBuffer() {
t.bfs = &bytes.Buffer{}
go func() {
if t.EchoStream == nil {
_, t.CopyStreamError = io.Copy(t.bfs, t.terminal)
} else {
var tee = io.TeeReader(t.terminal, t.EchoStream)
_, t.CopyStreamError = io.Copy(t.bfs, tee)
}
}()
}
func (t *Terminal) readLine(s Story) (end bool, err error) {
if t.processState != nil {
return true, nil
}
line, err := t.bfs.ReadString('\n')
if err != nil && err != io.EOF {
return false, err
}
if err := s.TickHandler(); err != nil {
return false, err
}
return t.handleLine(line, s)
}
func (t *Terminal) handleLine(line string, s Story) (end bool, err error) {
if len(line) != 0 {
in, err := s.HandleLine(line)
switch {
case err == SkipWrite || err == SkipZeroMatches:
case err == nil:
if _, e := t.WriteLine(in); e != nil {
return false, e
}
default:
return false, err
}
}
return false, nil
}
// QueueStory is a command execution story with sequential steps
// that must be fulfilled before the next is executed
type QueueStory struct {
Sequence []Step
Timeout time.Duration
pastStepTime time.Time
ctx context.Context
ctxCancelFunc context.CancelFunc
}
// Step is like a route rule to handle lines
type Step struct {
Read string
ReadRegex *regexp.Regexp
ReadFunc func(in string) bool
Write string
SkipWrite bool
Timeout time.Duration
timeoutCtx context.Context
}
var errAlreadyInitialized = errors.New("Story has already initialized")
// Add steps to a QueueStory
func (q *QueueStory) Add(args ...Step) {
q.Sequence = append(q.Sequence, args...)
}
// Setup executed by Terminal on Watch()
func (q *QueueStory) Setup() (ctx context.Context, err error) {
if q.ctx != nil {
return nil, errAlreadyInitialized
}
q.pastStepTime = time.Now()
q.ctx, q.ctxCancelFunc = context.WithCancel(context.Background())
if q.Timeout != time.Duration(0) {
q.ctx, q.ctxCancelFunc = context.WithTimeout(q.ctx, q.Timeout)
}
return q.ctx, nil
}
// Cancel Story
func (q *QueueStory) Cancel() {
q.ctxCancelFunc()
}
// Teardown executed by Terminal during Watch() teardown
func (q *QueueStory) Teardown() {
if q.ctxCancelFunc != nil {
q.ctxCancelFunc()
}
}
// TickHandler is called on terminal Watch between LineReaderInterval
// regardless if there are changes or not, before HandleLine
func (q *QueueStory) TickHandler() error {
if len(q.Sequence) == 0 {
return nil
}
var step = q.Sequence[0]
if step.Timeout == time.Duration(0) {
return nil
}
if time.Now().Before(q.pastStepTime.Add(step.Timeout)) {
return nil
}
q.ctx, q.ctxCancelFunc = context.WithDeadline(q.ctx, time.Time{})
return fmt.Errorf("Timed out while waiting for line \"%v\": timeout %v",
q.Sequence[0].Read,
q.Sequence[0].Timeout)
}
// HandleLine handles a QueueStory line the program prints
func (q *QueueStory) HandleLine(s string) (in string, err error) {
if len(q.Sequence) == 0 {
return "", SkipZeroMatches
}
if match := q.matcher(s, q.Sequence[0]); !match {
return "", SkipWrite
}
var step = q.shift()
q.pastStepTime = time.Now()
if step.SkipWrite {
return "", SkipWrite
}
return step.Write, nil
}
func (q *QueueStory) matcher(in string, step Step) bool {
switch {
case step.ReadFunc != nil:
return step.ReadFunc(in)
case step.ReadRegex != nil:
return step.ReadRegex.MatchString(in)
default:
return similar(in, step.Read)
}
}
// Success tells if all steps are executed and there is none left
func (q *QueueStory) Success() bool {
return q.ctx != nil && len(q.Sequence) == 0
}
func (q *QueueStory) shift() Step {
var step Step
if len(q.Sequence) != 0 {
step = q.Sequence[0]
q.Sequence = q.Sequence[1:]
} else {
q.Sequence = []Step{}
}
return step
}
func similar(s, ref string) bool {
return strings.TrimSpace(s) == strings.TrimSpace(ref)
}