forked from google/goexpect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expect.go
1181 lines (1080 loc) · 30.3 KB
/
expect.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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package expect is a Go version of the classic TCL Expect.
package expect
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"os/exec"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc/codes"
"github.com/google/goterm/term"
)
// DefaultTimeout is the default Expect timeout.
const DefaultTimeout = 60 * time.Second
const (
bufferSize = 8192 // bufferSize sets the size of the io buffers.
checkDuration = 2 * time.Second // checkDuration how often to check for new output.
)
// Status contains an errormessage and a status code.
type Status struct {
code codes.Code
msg string
}
// NewStatus creates a Status with the provided code and message.
func NewStatus(code codes.Code, msg string) *Status {
return &Status{code, msg}
}
// NewStatusf returns a Status with the providead code and a formatted message.
func NewStatusf(code codes.Code, format string, a ...interface{}) *Status {
return NewStatus(code, fmt.Sprintf(fmt.Sprintf(format, a...)))
}
// Err is a helper to handle errors.
func (s *Status) Err() error {
if s == nil || s.code == codes.OK {
return nil
}
return s
}
// Error is here to adhere to the error interface.
func (s *Status) Error() string {
return s.msg
}
// Option represents one Expecter option.
type Option func(*GExpect) Option
// CheckDuration changes the default duration checking for new incoming data.
func CheckDuration(d time.Duration) Option {
return func(e *GExpect) Option {
prev := e.chkDuration
e.chkDuration = d
return CheckDuration(prev)
}
}
// Verbose enables/disables verbose logging of matches and sends.
func Verbose(v bool) Option {
return func(e *GExpect) Option {
prev := e.verbose
e.verbose = v
return Verbose(prev)
}
}
// VerboseWriter sets an alternate destination for verbose logs.
func VerboseWriter(w io.Writer) Option {
return func(e *GExpect) Option {
prev := e.verboseWriter
e.verboseWriter = w
return VerboseWriter(prev)
}
}
// NoCheck turns off the Expect alive checks.
func NoCheck() Option {
return changeChk(func(*GExpect) bool {
return true
})
}
// DebugCheck adds logging to the check function.
// The check function for the spawners are called at creation/timeouts and I/O so can
// be usable for printing current state during debugging.
func DebugCheck(l *log.Logger) Option {
lg := log.Printf
if l != nil {
lg = l.Printf
}
return func(e *GExpect) Option {
prev := e.chk
e.chkMu.Lock()
e.chk = func(ge *GExpect) bool {
res := prev(ge)
ge.mu.Lock()
lg("chk: %t, ge: %v", res, ge)
ge.mu.Unlock()
return res
}
e.chkMu.Unlock()
return changeChk(prev)
}
}
// ChangeCheck changes the Expect check function.
func ChangeCheck(f func() bool) Option {
return changeChk(func(*GExpect) bool {
return f()
})
}
func changeChk(f func(*GExpect) bool) Option {
return func(e *GExpect) Option {
prev := e.chk
e.chkMu.Lock()
e.chk = f
e.chkMu.Unlock()
return changeChk(prev)
}
}
// SetEnv sets the environmental variables of the spawned process.
func SetEnv(env []string) Option {
return func(e *GExpect) Option {
prev := e.cmd.Env
e.cmd.Env = env
return SetEnv(prev)
}
}
// BatchCommands.
const (
// BatchSend for invoking Send in a batch
BatchSend = iota
// BatchExpect for invoking Expect in a batch
BatchExpect
// BatchSwitchCase for invoking ExpectSwitchCase in a batch
BatchSwitchCase
)
// TimeoutError is the error returned by all Expect functions upon timer expiry.
type TimeoutError int
// Error implements the Error interface.
func (t TimeoutError) Error() string {
return fmt.Sprintf("expect: timer expired after %d seconds", time.Duration(t)/time.Second)
}
// BatchRes returned from ExpectBatch for every Expect command executed.
type BatchRes struct {
// Idx is used to match the result with the []Batcher commands sent in.
Idx int
// Out output buffer for the expect command at Batcher[Idx].
Output string
// Match regexp matches for expect command at Batcher[Idx].
Match []string
}
// Batcher interface is used to make it more straightforward and readable to create
// batches of Expects.
//
// var batch = []Batcher{
// &BExpT{"password",8},
// &BSnd{"password\n"},
// &BExp{"olakar@router>"},
// &BSnd{ "show interface description\n"},
// &BExp{ "olakar@router>"},
// }
//
// var batchSwCaseReplace = []Batcher{
// &BCasT{[]Caser{
// &BCase{`([0-9]) -- .*\(MASTER\)`, `\1` + "\n"}}, 1},
// &BExp{`prompt/>`},
// }
type Batcher interface {
// cmd returns the Batch command.
Cmd() int
// Arg returns the command argument.
Arg() string
// Timeout returns the timeout duration for the command , <0 gives default value.
Timeout() time.Duration
// Cases returns the Caser structure for SwitchCase commands.
Cases() []Caser
}
// BExp implements the Batcher interface for Expect commands using the default timeout.
type BExp struct {
// R contains the Expect command regular expression.
R string
}
// Cmd returns the Expect command (BatchExpect).
func (be *BExp) Cmd() int {
return BatchExpect
}
// Arg returns the Expect regular expression.
func (be *BExp) Arg() string {
return be.R
}
// Timeout always returns -1 which sets it to the value used to call the ExpectBatch function.
func (be *BExp) Timeout() time.Duration {
return -1
}
// Cases always returns nil for the Expect command.
func (be *BExp) Cases() []Caser {
return nil
}
// BExpT implements the Batcher interface for Expect commands adding a timeout option to the BExp
// type.
type BExpT struct {
// R contains the Expect command regular expression.
R string
// T holds the Expect command timeout in seconds.
T int
}
// Cmd returns the Expect command (BatchExpect).
func (bt *BExpT) Cmd() int {
return BatchExpect
}
// Timeout returns the timeout in seconds.
func (bt *BExpT) Timeout() time.Duration {
return time.Duration(bt.T) * time.Second
}
// Arg returns the Expect regular expression.
func (bt *BExpT) Arg() string {
return bt.R
}
// Cases always return nil for the Expect command.
func (bt *BExpT) Cases() []Caser {
return nil
}
// BSnd implements the Batcher interface for Send commands.
type BSnd struct {
S string
}
// Cmd returns the Send command(BatchSend).
func (bs *BSnd) Cmd() int {
return BatchSend
}
// Arg returns the data to be sent.
func (bs *BSnd) Arg() string {
return bs.S
}
// Timeout always returns 0 , Send doesn't have a timeout.
func (bs *BSnd) Timeout() time.Duration {
return 0
}
// Cases always returns nil , not used for Send commands.
func (bs *BSnd) Cases() []Caser {
return nil
}
// BCas implements the Batcher interface for SwitchCase commands.
type BCas struct {
// C holds the Caser array for the SwitchCase command.
C []Caser
}
// Cmd returns the SwitchCase command(BatchSwitchCase).
func (bc *BCas) Cmd() int {
return BatchSwitchCase
}
// Arg returns an empty string , not used for SwitchCase.
func (bc *BCas) Arg() string {
return ""
}
// Timeout returns -1 , setting it to the default value.
func (bc *BCas) Timeout() time.Duration {
return -1
}
// Cases returns the Caser structure.
func (bc *BCas) Cases() []Caser {
return bc.C
}
// BCasT implements the Batcher interfacs for SwitchCase commands, adding a timeout option
// to the BCas type.
type BCasT struct {
// Cs holds the Caser array for the SwitchCase command.
C []Caser
// Tout holds the SwitchCase timeout in seconds.
T int
}
// Timeout returns the timeout in seconds.
func (bct *BCasT) Timeout() time.Duration {
return time.Duration(bct.T) * time.Second
}
// Cmd returns the SwitchCase command(BatchSwitchCase).
func (bct *BCasT) Cmd() int {
return BatchSwitchCase
}
// Arg returns an empty string , not used for SwitchCase.
func (bct *BCasT) Arg() string {
return ""
}
// Cases returns the Caser structure.
func (bct *BCasT) Cases() []Caser {
return bct.C
}
// Tag represents the state for a Caser.
type Tag int32
const (
// OKTag marks the desired state was reached.
OKTag = Tag(iota)
// FailTag means reaching this state will fail the Switch/Case.
FailTag
// ContinueTag will recheck for matches.
ContinueTag
// NextTag skips match and continues to the next one.
NextTag
// NoTag signals no tag was set for this case.
NoTag
)
// OK returns the OK Tag and status.
func OK() func() (Tag, *Status) {
return func() (Tag, *Status) {
return OKTag, NewStatus(codes.OK, "state reached")
}
}
// Fail returns Fail Tag and status.
func Fail(s *Status) func() (Tag, *Status) {
return func() (Tag, *Status) {
return FailTag, s
}
}
// Continue returns the Continue Tag and status.
func Continue(s *Status) func() (Tag, *Status) {
return func() (Tag, *Status) {
return ContinueTag, s
}
}
// Next returns the Next Tag and status.
func Next() func() (Tag, *Status) {
return func() (Tag, *Status) {
return NextTag, NewStatus(codes.Unimplemented, "Next returns not implemented")
}
}
// LogContinue logs the message and returns the Continue Tag and status.
func LogContinue(msg string, s *Status) func() (Tag, *Status) {
return func() (Tag, *Status) {
log.Print(msg)
return ContinueTag, s
}
}
// Caser is an interface for ExpectSwitchCase and Batch to be able to handle
// both the Case struct and the more script friendly BCase struct.
type Caser interface {
// RE returns a compiled regexp
RE() (*regexp.Regexp, error)
// Send returns the send string
String() string
// Tag returns the Tag.
Tag() (Tag, *Status)
// Retry returns true if there are retries left.
Retry() bool
}
// Case used by the ExpectSwitchCase to take different Cases.
// Implements the Caser interface.
type Case struct {
// R is the compiled regexp to match.
R *regexp.Regexp
// S is the string to send if Regexp matches.
S string
// T is the Tag for this Case.
T func() (Tag, *Status)
// Rt specifies number of times to retry, only used for cases tagged with Continue.
Rt int
}
// Tag returns the tag for this case.
func (c *Case) Tag() (Tag, *Status) {
if c.T == nil {
return NoTag, NewStatus(codes.OK, "no Tag set")
}
return c.T()
}
// RE returns the compiled regular expression.
func (c *Case) RE() (*regexp.Regexp, error) {
return c.R, nil
}
// Retry decrements the Retry counter and checks if there are any retries left.
func (c *Case) Retry() bool {
defer func() { c.Rt-- }()
return c.Rt > 0
}
// Send returns the string to send if regexp matches
func (c *Case) String() string {
return c.S
}
// BCase with just a string is a bit more friendly to scripting.
// Implements the Caser interface.
type BCase struct {
// R contains the string regular expression.
R string
// S contains the string to be sent if R matches.
S string
// T contains the Tag.
T func() (Tag, *Status)
// Rt contains the number of retries.
Rt int
}
// RE returns the compiled regular expression.
func (b *BCase) RE() (*regexp.Regexp, error) {
if b.R == "" {
return nil, nil
}
return regexp.Compile(b.R)
}
// Send returns the string to send.
func (b *BCase) String() string {
return b.S
}
// Tag returns the BCase Tag.
func (b *BCase) Tag() (Tag, *Status) {
if b.T == nil {
return NoTag, NewStatus(codes.OK, "no Tag set")
}
return b.T()
}
// Retry decrements the Retry counter and checks if there are any retries left.
func (b *BCase) Retry() bool {
b.Rt--
return b.Rt > -1
}
// Expecter interface primarily to make testing easier.
type Expecter interface {
// Expect reads output from a spawned session and tries matching it with the provided regular expression.
// It returns all output found until match.
Expect(*regexp.Regexp, time.Duration) (string, []string, error)
// ExpectBatch takes an array of BatchEntries and runs through them in order. For every Expect
// command a BatchRes entry is created with output buffer and sub matches.
// Failure of any of the batch commands will stop the execution, returning the results up to the
// failure.
ExpectBatch([]Batcher, time.Duration) ([]BatchRes, error)
// ExpectSwitchCase makes it possible to Expect with multiple regular expressions and actions. Returns the
// full output and submatches of the commands together with an index for the matching Case.
ExpectSwitchCase([]Caser, time.Duration) (string, []string, int, error)
// Send sends data into the spawned session.
Send(string) error
// Close closes the spawned session and files.
Close() error
}
// GExpect implements the Expecter interface.
type GExpect struct {
// pty holds the virtual terminal used to interact with the spawned commands.
pty *term.PTY
// cmd contains the cmd information for the spawned process.
cmd *exec.Cmd
ssh *ssh.Session
// snd is the channel used by the Send command to send data into the spawned command.
snd chan string
// rcv is used to signal the Expect commands that new data arrived.
rcv chan struct{}
// chkMu lock protecting the check function.
chkMu sync.RWMutex
// chk contains the function to check if the spawned command is alive.
chk func(*GExpect) bool
// cls contains the function to close spawned command.
cls func(*GExpect) error
// timeout contains the default timeout for a spawned command.
timeout time.Duration
// chkDuration contains the duration between checks for new incoming data.
chkDuration time.Duration
// verbose enables verbose logging.
verbose bool
// verboseWriter if set specifies where to write verbose information.
verboseWriter io.Writer
// mu protects the output buffer. It must be held for any operations on out.
mu sync.Mutex
out bytes.Buffer
}
// String implements the stringer interface.
func (e *GExpect) String() string {
res := fmt.Sprintf("%p: ", e)
if e.pty != nil {
_, name := e.pty.PTSName()
res += fmt.Sprintf("pty: %s ", name)
}
switch {
case e.cmd != nil:
res += fmt.Sprintf("cmd: %s(%d) ", e.cmd.Path, e.cmd.Process.Pid)
case e.ssh != nil:
res += fmt.Sprint("ssh session ")
}
res += fmt.Sprintf("buf: %q", e.out.String())
return res
}
// ExpectBatch takes an array of BatchEntry and executes them in order filling in the BatchRes
// array for any Expect command executed.
func (e *GExpect) ExpectBatch(batch []Batcher, timeout time.Duration) ([]BatchRes, error) {
res := []BatchRes{}
for i, b := range batch {
switch b.Cmd() {
case BatchExpect:
re, err := regexp.Compile(b.Arg())
if err != nil {
return res, err
}
to := b.Timeout()
if to < 0 {
to = timeout
}
out, match, err := e.Expect(re, to)
res = append(res, BatchRes{i, out, match})
if err != nil {
return res, err
}
case BatchSend:
if err := e.Send(b.Arg()); err != nil {
return res, err
}
case BatchSwitchCase:
to := b.Timeout()
if to < 0 {
to = timeout
}
out, match, _, err := e.ExpectSwitchCase(b.Cases(), to)
res = append(res, BatchRes{i, out, match})
if err != nil {
return res, err
}
default:
return res, errors.New("unknown command:" + strconv.Itoa(b.Cmd()))
}
}
return res, nil
}
func (e *GExpect) check() bool {
e.chkMu.RLock()
defer e.chkMu.RUnlock()
return e.chk(e)
}
// ExpectSwitchCase checks each Case against the accumulated out buffer, sending specified
// string back. Leaving Send empty will Send nothing to the process.
// Substring expansion can be used eg.
// Case{`vf[0-9]{2}.[a-z]{3}[0-9]{2}\.net).*UP`,`show arp \1`}
// Given: vf11.hnd01.net UP 35 (4) 34 (4) CONNECTED 0 0/0
// Would send: show arp vf11.hnd01.net
func (e *GExpect) ExpectSwitchCase(cs []Caser, timeout time.Duration) (string, []string, int, error) {
// Compile all regexps
rs := make([]*regexp.Regexp, 0, len(cs))
for _, c := range cs {
re, err := c.RE()
if err != nil {
return "", []string{""}, -1, err
}
rs = append(rs, re)
}
// Setup timeouts
// timeout == 0 => Just dump the buffer and exit.
// timeout < 0 => Set default value.
if timeout < 0 {
timeout = e.timeout
}
timer := time.NewTimer(timeout)
check := e.chkDuration
// Check if any new data arrived every checkDuration interval.
// If timeout/4 is less than the checkout interval we set the checkout to
// timeout/4. If timeout ends up being 0 we bump it to one to keep the Ticker from
// panicking.
// All this b/c of the unreliable channel send setup in the read function,making it
// possible for Expect* functions to miss the rcv signal.
//
// from read():
// // Ping Expect function
// select {
// case e.rcv <- struct{}{}:
// default:
// }
//
// A signal is only sent if any Expect function is running. Expect could miss it
// while playing around with buffers and matching regular expressions.
if timeout>>2 < check {
check = timeout >> 2
if check <= 0 {
check = 1
}
}
chTicker := time.NewTicker(check)
defer chTicker.Stop()
// Read in current data and start actively check for matches.
var tbuf bytes.Buffer
if _, err := io.Copy(&tbuf, e); err != nil {
return tbuf.String(), nil, -1, fmt.Errorf("io.Copy failed: %v", err)
}
for {
L1:
for i, c := range cs {
if rs[i] == nil {
continue
}
match := rs[i].FindStringSubmatch(tbuf.String())
if match == nil {
continue
}
t, s := c.Tag()
if t == NextTag && !c.Retry() {
continue
}
if e.verbose {
if e.verboseWriter != nil {
vStr := fmt.Sprintln(term.Green("Match for RE:").String() + fmt.Sprintf(" %q found: %q Buffer: %s", rs[i].String(), match, tbuf.String()))
for n, bytesRead, err := 0, 0, error(nil); bytesRead < len(vStr); bytesRead += n {
n, err = e.verboseWriter.Write([]byte(vStr)[n:])
if err != nil {
log.Printf("Write to Verbose Writer failed: %v", err)
break
}
}
} else {
log.Printf("Match for RE: %q found: %q Buffer: %q", rs[i].String(), match, tbuf.String())
}
}
// Clear the buffer directly after match.
o := tbuf.String()
tbuf.Reset()
st := c.String()
// Replace the submatches \[0-9]+ in the send string.
if len(match) > 1 && len(st) > 0 {
for i := 1; i < len(match); i++ {
// \(submatch) will be expanded in the Send string.
// To escape use \\(number).
si := strconv.Itoa(i)
r := strings.NewReplacer(`\\`+si, `\`+si, `\`+si, `\\`+si)
st = r.Replace(st)
st = strings.Replace(st, `\\`+si, match[i], -1)
}
}
// Don't send anything if string is empty.
if st != "" {
if err := e.Send(st); err != nil {
return o, match, i, fmt.Errorf("failed to send: %q err: %v", st, err)
}
}
// Tag handling.
switch t {
case OKTag, FailTag, NoTag:
return o, match, i, s.Err()
case ContinueTag:
if !c.Retry() {
return o, match, i, s.Err()
}
break L1
case NextTag:
break L1
default:
s = NewStatusf(codes.Unknown, "Tag: %d unknown, err: %v", t, s)
}
return o, match, i, s.Err()
}
if !e.check() {
nr, err := io.Copy(&tbuf, e)
if err != nil {
return tbuf.String(), nil, -1, fmt.Errorf("io.Copy failed: %v", err)
}
if nr == 0 {
return tbuf.String(), nil, -1, errors.New("expect: Process not running")
}
}
select {
case <-timer.C:
// Expect timeout.
nr, err := io.Copy(&tbuf, e)
if err != nil {
return tbuf.String(), nil, -1, fmt.Errorf("io.Copy failed: %v", err)
}
// If we got no new data we return otherwise give it another chance to match.
if nr == 0 {
return tbuf.String(), nil, -1, TimeoutError(timeout)
}
timer = time.NewTimer(timeout)
case <-chTicker.C:
// Periodical timer to make sure data is handled in case the <-e.rcv channel
// was missed.
if _, err := io.Copy(&tbuf, e); err != nil {
return tbuf.String(), nil, -1, fmt.Errorf("io.Copy failed: %v", err)
}
case <-e.rcv:
// Data to fetch.
if _, err := io.Copy(&tbuf, e); err != nil {
return tbuf.String(), nil, -1, fmt.Errorf("io.Copy failed: %v", err)
}
}
}
}
// GenOptions contains the options needed to set up a generic Spawner.
type GenOptions struct {
// In is where Expect Send messages will be written.
In io.WriteCloser
// Out will be read and matched by the expecter.
Out io.Reader
// Wait is used by expect to know when the session is over and cleanup of io Go routines should happen.
Wait func() error
// Close will be called as part of the expect Close, should normally include a Close of the In WriteCloser.
Close func() error
// Check is called everytime a Send or Expect function is called to makes sure the session is still running.
Check func() bool
}
// SpawnGeneric is used to write generic Spawners. It returns an Expecter. The returned channel will give the return
// status of the spawned session, in practice this means the return value of the provided Wait function.
func SpawnGeneric(opt *GenOptions, timeout time.Duration, opts ...Option) (*GExpect, <-chan error, error) {
switch {
case opt == nil:
return nil, nil, errors.New("GenOptions is <nil>")
case opt.In == nil:
return nil, nil, errors.New("In can't be <nil>")
case opt.Out == nil:
return nil, nil, errors.New("Out can't be <nil>")
case opt.Wait == nil:
return nil, nil, errors.New("Wait can't be <nil>")
case opt.Close == nil:
return nil, nil, errors.New("Close can't be <nil>")
case opt.Check == nil:
return nil, nil, errors.New("Check can't be <nil>")
}
if timeout < 1 {
timeout = DefaultTimeout
}
e := &GExpect{
rcv: make(chan struct{}),
snd: make(chan string),
timeout: timeout,
chkDuration: checkDuration,
cls: func(e *GExpect) error {
return opt.Close()
},
chk: func(e *GExpect) bool {
return opt.Check()
},
}
for _, o := range opts {
o(e)
}
errCh := make(chan error, 1)
go e.waitForSession(errCh, opt.Wait, opt.In, opt.Out, nil)
return e, errCh, nil
}
// SpawnFake spawns an expect.Batcher.
func SpawnFake(b []Batcher, timeout time.Duration, opt ...Option) (*GExpect, <-chan error, error) {
rr, rw := io.Pipe()
wr, ww := io.Pipe()
done := make(chan struct{})
srv, _, err := SpawnGeneric(&GenOptions{
In: ww,
Out: rr,
Wait: func() error {
<-done
return nil
},
Close: func() error {
return ww.Close()
},
Check: func() bool { return true },
}, timeout, opt...)
if err != nil {
return nil, nil, err
}
go func() {
res, err := srv.ExpectBatch(b, timeout)
if err != nil {
log.Printf("ExpectBatch(%v,%v) failed: %v, out: %v", b, timeout, err, res)
}
close(done)
}()
return SpawnGeneric(&GenOptions{
In: rw,
Out: wr,
Close: func() error {
return rw.Close()
},
Check: func() bool { return true },
Wait: func() error {
<-done
return nil
},
}, timeout, opt...)
}
// SpawnWithArgs starts a new process and collects the output. The error
// channel returns the result of the command Spawned when it finishes.
// Arguments may contain spaces.
func SpawnWithArgs(command []string, timeout time.Duration, opts ...Option) (*GExpect, <-chan error, error) {
pty, err := term.OpenPTY()
if err != nil {
return nil, nil, err
}
var t term.Termios
t.Raw()
t.Set(pty.Slave)
if timeout < 1 {
timeout = DefaultTimeout
}
// Get the command up and running
cmd := exec.Command(command[0], command[1:]...)
// This ties the commands Stdin,Stdout & Stderr to the virtual terminal we created
cmd.Stdin, cmd.Stdout, cmd.Stderr = pty.Slave, pty.Slave, pty.Slave
// New process needs to be the process leader and control of a tty
cmd.SysProcAttr = &syscall.SysProcAttr{
Setsid: true,
Setctty: true}
e := &GExpect{
rcv: make(chan struct{}),
snd: make(chan string),
cmd: cmd,
timeout: timeout,
chkDuration: checkDuration,
pty: pty,
cls: func(e *GExpect) error {
if e.cmd != nil {
return e.cmd.Process.Kill()
}
return nil
},
chk: func(e *GExpect) bool {
if e.cmd.Process == nil {
return false
}
// Sending Signal 0 to a process returns nil if process can take a signal , something else if not.
return e.cmd.Process.Signal(syscall.Signal(0)) == nil
},
}
for _, o := range opts {
o(e)
}
res := make(chan error, 1)
go e.runcmd(res)
// Wait until command started
return e, res, <-res
}
// Spawn starts a new process and collects the output. The error channel
// returns the result of the command Spawned when it finishes. Arguments may
// not contain spaces.
func Spawn(command string, timeout time.Duration, opts ...Option) (*GExpect, <-chan error, error) {
return SpawnWithArgs(strings.Fields(command), timeout, opts...)
}
// SpawnSSH starts an interactive SSH session,ties it to a PTY and collects the output. The returned channel sends the
// state of the SSH session after it finishes.
func SpawnSSH(sshClient *ssh.Client, timeout time.Duration, opts ...Option) (*GExpect, <-chan error, error) {
tios := term.Termios{}
tios.Raw()
tios.Wz.WsCol, tios.Wz.WsRow = sshTermWidth, sshTermHeight
return SpawnSSHPTY(sshClient, timeout, tios, opts...)
}
const (
sshTerm = "xterm"
sshTermWidth = 132
sshTermHeight = 43
)
// SpawnSSHPTY starts an interactive SSH session and ties it to a local PTY, optionally requests a remote PTY.
func SpawnSSHPTY(sshClient *ssh.Client, timeout time.Duration, term term.Termios, opts ...Option) (*GExpect, <-chan error, error) {
if sshClient == nil {
return nil, nil, errors.New("*ssh.Client is nil")
}
if timeout < 1 {
timeout = DefaultTimeout
}
// Setup interactive session
session, err := sshClient.NewSession()
if err != nil {
return nil, nil, err
}
e := &GExpect{
rcv: make(chan struct{}),
snd: make(chan string),
chk: func(e *GExpect) bool {
if e.ssh == nil {
return false
}
_, err := e.ssh.SendRequest("dummy", false, nil)
return err == nil
},
cls: func(e *GExpect) error {
if e.ssh != nil {
return e.ssh.Close()
}
return nil
},
ssh: session,
timeout: timeout,
chkDuration: checkDuration,
}
for _, o := range opts {
o(e)
}
if term.Wz.WsCol == 0 {
term.Wz.WsCol = sshTermWidth
}
if term.Wz.WsRow == 0 {
term.Wz.WsRow = sshTermHeight
}
if err := session.RequestPty(sshTerm, int(term.Wz.WsRow), int(term.Wz.WsCol), term.ToSSH()); err != nil {
return nil, nil, err
}
inPipe, err := session.StdinPipe()
if err != nil {
return nil, nil, err
}
outPipe, err := session.StdoutPipe()
if err != nil {
return nil, nil, err
}
errPipe, err := session.StderrPipe()
if err != nil {
return nil, nil, err
}
if err := session.Shell(); err != nil {
return nil, nil, err
}
// Shell started.
errCh := make(chan error, 1)
go e.waitForSession(errCh, session.Wait, inPipe, outPipe, errPipe)
return e, errCh, nil
}
func (e *GExpect) waitForSession(r chan error, wait func() error, sIn io.WriteCloser, sOut io.Reader, sErr io.Reader) {
chDone := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for {