expect.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package expect implements a small expect-style interface
  15. package expect
  16. import (
  17. "bufio"
  18. "fmt"
  19. "io"
  20. "os"
  21. "os/exec"
  22. "strings"
  23. "sync"
  24. "syscall"
  25. "github.com/creack/pty"
  26. )
  27. type ExpectProcess struct {
  28. cmd *exec.Cmd
  29. fpty *os.File
  30. wg sync.WaitGroup
  31. cond *sync.Cond // for broadcasting updates are available
  32. mu sync.Mutex // protects lines and err
  33. lines []string
  34. count int // increment whenever new line gets added
  35. err error
  36. // StopSignal is the signal Stop sends to the process; defaults to SIGKILL.
  37. StopSignal os.Signal
  38. }
  39. // NewExpect creates a new process for expect testing.
  40. func NewExpect(name string, arg ...string) (ep *ExpectProcess, err error) {
  41. // if env[] is nil, use current system env
  42. return NewExpectWithEnv(name, arg, nil)
  43. }
  44. // NewExpectWithEnv creates a new process with user defined env variables for expect testing.
  45. func NewExpectWithEnv(name string, args []string, env []string) (ep *ExpectProcess, err error) {
  46. cmd := exec.Command(name, args...)
  47. cmd.Env = env
  48. ep = &ExpectProcess{
  49. cmd: cmd,
  50. StopSignal: syscall.SIGKILL,
  51. }
  52. ep.cond = sync.NewCond(&ep.mu)
  53. ep.cmd.Stderr = ep.cmd.Stdout
  54. ep.cmd.Stdin = nil
  55. if ep.fpty, err = pty.Start(ep.cmd); err != nil {
  56. return nil, err
  57. }
  58. ep.wg.Add(1)
  59. go ep.read()
  60. return ep, nil
  61. }
  62. func (ep *ExpectProcess) read() {
  63. defer ep.wg.Done()
  64. printDebugLines := os.Getenv("EXPECT_DEBUG") != ""
  65. r := bufio.NewReader(ep.fpty)
  66. for ep.err == nil {
  67. l, rerr := r.ReadString('\n')
  68. ep.mu.Lock()
  69. ep.err = rerr
  70. if l != "" {
  71. if printDebugLines {
  72. fmt.Printf("%s-%d: %s", ep.cmd.Path, ep.cmd.Process.Pid, l)
  73. }
  74. ep.lines = append(ep.lines, l)
  75. ep.count++
  76. if len(ep.lines) == 1 {
  77. ep.cond.Signal()
  78. }
  79. }
  80. ep.mu.Unlock()
  81. }
  82. ep.cond.Signal()
  83. }
  84. // ExpectFunc returns the first line satisfying the function f.
  85. func (ep *ExpectProcess) ExpectFunc(f func(string) bool) (string, error) {
  86. ep.mu.Lock()
  87. for {
  88. for len(ep.lines) == 0 && ep.err == nil {
  89. ep.cond.Wait()
  90. }
  91. if len(ep.lines) == 0 {
  92. break
  93. }
  94. l := ep.lines[0]
  95. ep.lines = ep.lines[1:]
  96. if f(l) {
  97. ep.mu.Unlock()
  98. return l, nil
  99. }
  100. }
  101. ep.mu.Unlock()
  102. return "", ep.err
  103. }
  104. // Expect returns the first line containing the given string.
  105. func (ep *ExpectProcess) Expect(s string) (string, error) {
  106. return ep.ExpectFunc(func(txt string) bool { return strings.Contains(txt, s) })
  107. }
  108. // LineCount returns the number of recorded lines since
  109. // the beginning of the process.
  110. func (ep *ExpectProcess) LineCount() int {
  111. ep.mu.Lock()
  112. defer ep.mu.Unlock()
  113. return ep.count
  114. }
  115. // Stop kills the expect process and waits for it to exit.
  116. func (ep *ExpectProcess) Stop() error { return ep.close(true) }
  117. // Signal sends a signal to the expect process
  118. func (ep *ExpectProcess) Signal(sig os.Signal) error {
  119. return ep.cmd.Process.Signal(sig)
  120. }
  121. // Close waits for the expect process to exit.
  122. func (ep *ExpectProcess) Close() error { return ep.close(false) }
  123. func (ep *ExpectProcess) close(kill bool) error {
  124. if ep.cmd == nil {
  125. return ep.err
  126. }
  127. if kill {
  128. ep.Signal(ep.StopSignal)
  129. }
  130. err := ep.cmd.Wait()
  131. ep.fpty.Close()
  132. ep.wg.Wait()
  133. if err != nil {
  134. ep.err = err
  135. if !kill && strings.Contains(err.Error(), "exit status") {
  136. // non-zero exit code
  137. err = nil
  138. } else if kill && strings.Contains(err.Error(), "signal:") {
  139. err = nil
  140. }
  141. }
  142. ep.cmd = nil
  143. return err
  144. }
  145. func (ep *ExpectProcess) Send(command string) error {
  146. _, err := io.WriteString(ep.fpty, command)
  147. return err
  148. }