expect.go 4.1 KB

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