expect.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. "github.com/kr/pty"
  25. )
  26. type ExpectProcess struct {
  27. cmd *exec.Cmd
  28. fpty *os.File
  29. wg sync.WaitGroup
  30. ptyMu sync.Mutex // protects accessing fpty
  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. }
  37. var printDebugLines = os.Getenv("EXPECT_DEBUG") != ""
  38. // NewExpect creates a new process for expect testing.
  39. func NewExpect(name string, arg ...string) (ep *ExpectProcess, err error) {
  40. // if env[] is nil, use current system env
  41. return NewExpectWithEnv(name, arg, nil)
  42. }
  43. // NewExpectWithEnv creates a new process with user defined env variables for expect testing.
  44. func NewExpectWithEnv(name string, args []string, env []string) (ep *ExpectProcess, err error) {
  45. cmd := exec.Command(name, args...)
  46. cmd.Env = env
  47. ep = &ExpectProcess{cmd: cmd}
  48. ep.cond = sync.NewCond(&ep.mu)
  49. ep.cmd.Stderr = ep.cmd.Stdout
  50. ep.cmd.Stdin = nil
  51. if ep.fpty, err = pty.Start(ep.cmd); err != nil {
  52. return nil, err
  53. }
  54. ep.wg.Add(1)
  55. go ep.read()
  56. return ep, nil
  57. }
  58. func (ep *ExpectProcess) read() {
  59. defer ep.wg.Done()
  60. r := bufio.NewReader(ep.fpty)
  61. for ep.err == nil {
  62. ep.ptyMu.Lock()
  63. l, rerr := r.ReadString('\n')
  64. ep.ptyMu.Unlock()
  65. ep.mu.Lock()
  66. ep.err = rerr
  67. if l != "" {
  68. if printDebugLines {
  69. fmt.Printf("%s-%d: %s", ep.cmd.Path, ep.cmd.Process.Pid, l)
  70. }
  71. ep.lines = append(ep.lines, l)
  72. ep.count++
  73. if len(ep.lines) == 1 {
  74. ep.cond.Signal()
  75. }
  76. }
  77. ep.mu.Unlock()
  78. }
  79. ep.cond.Signal()
  80. }
  81. // ExpectFunc returns the first line satisfying the function f.
  82. func (ep *ExpectProcess) ExpectFunc(f func(string) bool) (string, error) {
  83. ep.mu.Lock()
  84. for {
  85. for len(ep.lines) == 0 && ep.err == nil {
  86. ep.cond.Wait()
  87. }
  88. if len(ep.lines) == 0 {
  89. break
  90. }
  91. l := ep.lines[0]
  92. ep.lines = ep.lines[1:]
  93. if f(l) {
  94. ep.mu.Unlock()
  95. return l, nil
  96. }
  97. }
  98. ep.mu.Unlock()
  99. return "", ep.err
  100. }
  101. // Expect returns the first line containing the given string.
  102. func (ep *ExpectProcess) Expect(s string) (string, error) {
  103. return ep.ExpectFunc(func(txt string) bool { return strings.Contains(txt, s) })
  104. }
  105. // LineCount returns the number of recorded lines since
  106. // the beginning of the process.
  107. func (ep *ExpectProcess) LineCount() int {
  108. ep.mu.Lock()
  109. defer ep.mu.Unlock()
  110. return ep.count
  111. }
  112. // Stop kills the expect process and waits for it to exit.
  113. func (ep *ExpectProcess) Stop() error { return ep.close(true) }
  114. // Signal sends a signal to the expect process
  115. func (ep *ExpectProcess) Signal(sig os.Signal) error {
  116. return ep.cmd.Process.Signal(sig)
  117. }
  118. // Close waits for the expect process to exit.
  119. func (ep *ExpectProcess) Close() error { return ep.close(false) }
  120. func (ep *ExpectProcess) close(kill bool) error {
  121. if ep.cmd == nil {
  122. return ep.err
  123. }
  124. if kill {
  125. ep.Signal(os.Interrupt)
  126. }
  127. err := ep.cmd.Wait()
  128. ep.ptyMu.Lock()
  129. ep.fpty.Close()
  130. ep.ptyMu.Unlock()
  131. ep.wg.Wait()
  132. if err != nil {
  133. ep.err = err
  134. if !kill && strings.Contains(err.Error(), "exit status") {
  135. // non-zero exit code
  136. err = nil
  137. } else if kill && strings.Contains(err.Error(), "signal:") {
  138. err = nil
  139. }
  140. }
  141. ep.cmd = nil
  142. return err
  143. }
  144. func (ep *ExpectProcess) Send(command string) error {
  145. _, err := io.WriteString(ep.fpty, command)
  146. return err
  147. }