-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscenario.go
270 lines (223 loc) · 6.4 KB
/
scenario.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package e2e
import (
"fmt"
"os"
"strings"
"sync"
"github.com/pkg/errors"
tsdb_errors "github.com/prometheus/prometheus/tsdb/errors"
)
const (
ContainerSharedDir = "/shared"
)
type Service interface {
Name() string
Start(networkName, dir string) error
WaitReady() error
// It should be ok to Stop and Kill more than once, with next invokes being noop.
Kill() error
Stop() error
}
type Scenario struct {
services []Service
networkName string
sharedDir string
}
func NewScenario(networkName string) (*Scenario, error) {
s := &Scenario{networkName: networkName}
var err error
s.sharedDir, err = GetTempDirectory()
if err != nil {
return nil, err
}
// Force a shutdown in order to cleanup from a spurious situation in case
// the previous tests run didn't cleanup correctly.
s.shutdown()
args := []string{
"network", "create", networkName,
}
if extraArgs := os.Getenv("DOCKER_NETWORK_CREATE_EXTRA_ARGS"); extraArgs != "" {
args = append(
args,
strings.Split(extraArgs, ",")...,
)
}
// Setup the docker network.
if out, err := RunCommandAndGetOutput("docker", args...); err != nil {
logger.Log(string(out))
s.clean()
return nil, errors.Wrapf(err, "create docker network '%s'", networkName)
}
return s, nil
}
// SharedDir returns the absolute path of the directory on the host that is shared with all services in docker.
func (s *Scenario) SharedDir() string {
return s.sharedDir
}
// NetworkName returns the network name that scenario is responsible for.
func (s *Scenario) NetworkName() string {
return s.networkName
}
func (s *Scenario) isRegistered(name string) bool {
for _, service := range s.services {
if service.Name() == name {
return true
}
}
return false
}
func (s *Scenario) StartAndWaitReady(services ...Service) error {
if err := s.Start(services...); err != nil {
return err
}
return s.WaitReady(services...)
}
func (s *Scenario) Start(services ...Service) error {
var (
wg = sync.WaitGroup{}
startedMx = sync.Mutex{}
started = make([]Service, 0, len(services))
errsMx = sync.Mutex{}
errs = tsdb_errors.NewMulti()
)
// Ensure provided services don't conflict with existing ones.
if err := s.assertNoConflicts(services...); err != nil {
return err
}
// Start the services concurrently.
wg.Add(len(services))
for _, service := range services {
go func(service Service) {
defer wg.Done()
logger.Log("Starting", service.Name())
// Start the service.
if err := service.Start(s.networkName, s.SharedDir()); err != nil {
errsMx.Lock()
errs.Add(err)
errsMx.Unlock()
return
}
logger.Log("Started", service.Name())
startedMx.Lock()
started = append(started, service)
startedMx.Unlock()
}(service)
}
// Wait until all services have been started.
wg.Wait()
// Add the successfully started services to the scenario.
s.services = append(s.services, started...)
return errs.Err()
}
func (s *Scenario) Stop(services ...Service) error {
for _, service := range services {
if !s.isRegistered(service.Name()) {
return fmt.Errorf("unable to stop service %s because it does not exist", service.Name())
}
if err := service.Stop(); err != nil {
return err
}
// Remove the service from the list of services.
for i, entry := range s.services {
if entry.Name() == service.Name() {
s.services = append(s.services[:i], s.services[i+1:]...)
break
}
}
}
return nil
}
func (s *Scenario) WaitReady(services ...Service) error {
for _, service := range services {
if !s.isRegistered(service.Name()) {
return fmt.Errorf("unable to wait for service %s because it does not exist", service.Name())
}
if err := service.WaitReady(); err != nil {
return err
}
}
return nil
}
func (s *Scenario) Close() {
if s == nil {
return
}
s.shutdown()
s.clean()
}
func (s *Scenario) assertNoConflicts(services ...Service) error {
// Build a map of services already registered.
names := map[string]struct{}{}
for _, service := range s.services {
names[service.Name()] = struct{}{}
}
// Check if input services conflict with already existing ones or between them.
for _, service := range services {
if _, exists := names[service.Name()]; exists {
return fmt.Errorf("another service with the same name '%s' exists", service.Name())
}
names[service.Name()] = struct{}{}
}
return nil
}
// TODO(bwplotka): Add comments.
func (s *Scenario) clean() {
if err := os.RemoveAll(s.sharedDir); err != nil {
logger.Log("error while removing sharedDir", s.sharedDir, "err:", err)
}
}
func (s *Scenario) shutdown() {
// Kill the services concurrently.
wg := sync.WaitGroup{}
wg.Add(len(s.services))
for _, srv := range s.services {
go func(service Service) {
defer wg.Done()
if err := service.Kill(); err != nil {
logger.Log("Unable to kill service", service.Name(), ":", err.Error())
}
}(srv)
}
// Wait until all services have been killed.
wg.Wait()
// Ensure there are no leftover containers.
if out, err := RunCommandAndGetOutput(
"docker",
"ps",
"-a",
"--quiet",
"--filter",
fmt.Sprintf("network=%s", s.networkName),
); err == nil {
for _, containerID := range strings.Split(string(out), "\n") {
containerID = strings.TrimSpace(containerID)
if containerID == "" {
continue
}
if out, err = RunCommandAndGetOutput("docker", "rm", "--force", containerID); err != nil {
logger.Log(string(out))
logger.Log("Unable to cleanup leftover container", containerID, ":", err.Error())
}
}
} else {
logger.Log(string(out))
logger.Log("Unable to cleanup leftover containers:", err.Error())
}
// Teardown the docker network. In case the network does not exists (ie. this function
// is called during the setup of the scenario) we skip the removal in order to not log
// an error which may be misleading.
if ok, err := existDockerNetwork(s.networkName); ok || err != nil {
if out, err := RunCommandAndGetOutput("docker", "network", "rm", s.networkName); err != nil {
logger.Log(string(out))
logger.Log("Unable to remove docker network", s.networkName, ":", err.Error())
}
}
}
func existDockerNetwork(networkName string) (bool, error) {
out, err := RunCommandAndGetOutput("docker", "network", "ls", "--quiet", "--filter", fmt.Sprintf("name=%s", networkName))
if err != nil {
logger.Log(string(out))
logger.Log("Unable to check if docker network", networkName, "exists:", err.Error())
}
return strings.TrimSpace(string(out)) != "", nil
}