expect.go 3.6 KB

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