-
Notifications
You must be signed in to change notification settings - Fork 0
/
tempconsul.go
120 lines (102 loc) · 2.12 KB
/
tempconsul.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
package tempconsul
import (
"bufio"
"fmt"
"io"
"os/exec"
"strings"
"syscall"
"time"
)
var (
StartupSuccess = "cluster leadership acquired"
StartupTimeout = 10 * time.Second
)
type Server struct {
cmd *exec.Cmd
}
func (s *Server) Start() error {
if s.cmd != nil {
return fmt.Errorf("consul has already been started")
}
// Build Cmd
s.cmd = exec.Command("consul", "agent", "-dev", "-bind", "127.0.0.1")
serverStdout, err := s.cmd.StdoutPipe()
if err != nil {
s.cmd = nil
return err
}
// Start up the server and wait for success log line
if err = s.cmd.Start(); err != nil {
return err
}
if err = s.waitForSuccessfulStartup(serverStdout); err != nil {
s.Term()
return err
}
return nil
}
func (s *Server) Interrupt() (err error) {
if s.cmd == nil {
return fmt.Errorf("consul is not running")
}
s.cmd.Process.Signal(syscall.SIGINT)
_, err = s.cmd.Process.Wait()
if err != nil {
return err
}
s.cmd = nil
return nil
}
func (s *Server) Term() (err error) {
if s.cmd == nil {
return fmt.Errorf("consul is not running")
}
s.cmd.Process.Signal(syscall.SIGTERM)
_, err = s.cmd.Process.Wait()
if err != nil {
return err
}
s.cmd = nil
return nil
}
// TODO This is gross and weird. Should fix it someday...
func (s *Server) waitForSuccessfulStartup(r io.ReadCloser) error {
scanner := bufio.NewScanner(r)
line := ""
success := make(chan bool, 1)
failure := make(chan bool, 1)
stopWaiting := make(chan bool, 1)
go func() {
for {
select {
case <-stopWaiting: // Timeout
return
default:
if scanner.Scan() {
line = scanner.Text()
if strings.Contains(line, StartupSuccess) {
success <- true
return
}
} else {
failure <- true
return
}
}
}
}()
select {
case <-success:
return nil
case <-failure:
if err := scanner.Err(); err != nil {
return fmt.Errorf("couldn't read consul's stdout: %s", err.Error())
} else {
return fmt.Errorf("consul failed to start up: %s", line)
}
case <-time.After(StartupTimeout):
stopWaiting <- true
return fmt.Errorf("timed-out waiting for consul to start up successfully: %s", line)
}
}