-
Notifications
You must be signed in to change notification settings - Fork 0
/
hive.go
499 lines (454 loc) · 15 KB
/
hive.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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package hivesim
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/core-coin/go-core/v2/p2p/enode"
"github.com/core-coin/hive/internal/simapi"
)
// Simulation wraps the simulation HTTP API provided by hive.
type Simulation struct {
url string
m testMatcher
docs *docsCollector
ll int
}
// New looks up the hive host URI using the HIVE_SIMULATOR environment variable
// and connects to it. It will panic if HIVE_SIMULATOR is not set.
// If HIVE_DOCS_MODE is set to "true", it will inhibit most of the functionality
// in order to simplify execution for documentation generation.
func New() *Simulation {
var (
docs *docsCollector
url string
)
if cc := os.Getenv("HIVE_DOCS_MODE"); cc == "true" {
docs = NewDocsCollector()
} else {
var isSet bool
if url, isSet = os.LookupEnv("HIVE_SIMULATOR"); !isSet {
panic("HIVE_SIMULATOR environment variable not set")
} else if url == "" {
panic("HIVE_SIMULATOR environment variable is empty")
}
}
sim := &Simulation{url: url, docs: docs}
if p := os.Getenv("HIVE_TEST_PATTERN"); p != "" {
m, err := parseTestPattern(p)
if err != nil {
fmt.Fprintln(os.Stderr, "Warning: ignoring invalid test pattern regexp: "+err.Error())
}
sim.m = m
}
if ll := os.Getenv("HIVE_LOGLEVEL"); ll != "" {
sim.ll, _ = strconv.Atoi(ll)
}
return sim
}
// NewAt creates a simulation connected to the given API endpoint. You'll will rarely need
// to use this. In simulations launched by hive, use New() instead.
func NewAt(url string) *Simulation {
return &Simulation{url: url}
}
// SetTestPattern sets the regular expression that enables/skips suites and test cases.
// This method is provided for use in unit tests. For simulator runs launched by hive, the
// test pattern is set automatically in New().
func (sim *Simulation) SetTestPattern(p string) {
m, err := parseTestPattern(p)
if err != nil {
panic("invalid test pattern regexp: " + err.Error())
}
sim.m = m
}
// TestPattern returns the regular expressions used to enable/skip suite and test names.
func (sim *Simulation) TestPattern() (suiteExpr string, testNameExpr string) {
se := ""
if sim.m.suite != nil {
se = sim.m.suite.String()
}
te := ""
if sim.m.test != nil {
te = sim.m.test.String()
}
return se, te
}
// CollectTestsOnly returns true if the simulation is running in collect-tests-only mode.
func (sim *Simulation) CollectTestsOnly() bool {
return sim.docs != nil
}
// EndTest finishes the test case, cleaning up everything, logging results, and returning
// an error if the process could not be completed.
func (sim *Simulation) EndTest(testSuite SuiteID, test TestID, testResult TestResult) error {
if sim.docs != nil {
return sim.docs.EndTest(testSuite, test, testResult)
}
url := fmt.Sprintf("%s/testsuite/%d/test/%d", sim.url, testSuite, test)
return post(url, &testResult, nil)
}
// StartSuite signals the start of a test suite.
func (sim *Simulation) StartSuite(suite *simapi.TestRequest, simlog string) (SuiteID, error) {
if sim.docs != nil {
return sim.docs.StartSuite(suite, simlog)
}
var (
url = fmt.Sprintf("%s/testsuite", sim.url)
req = suite
resp SuiteID
)
err := post(url, req, &resp)
return resp, err
}
// EndSuite signals the end of a test suite.
func (sim *Simulation) EndSuite(testSuite SuiteID) error {
if sim.docs != nil {
return sim.docs.EndSuite(testSuite)
}
url := fmt.Sprintf("%s/testsuite/%d", sim.url, testSuite)
return requestDelete(url)
}
// StartTest starts a new test case, returning the testcase id as a context identifier.
func (sim *Simulation) StartTest(testSuite SuiteID, test *simapi.TestRequest) (TestID, error) {
if sim.docs != nil {
return sim.docs.StartTest(testSuite, test)
}
var (
url = fmt.Sprintf("%s/testsuite/%d/test", sim.url, testSuite)
req = test
resp TestID
)
err := post(url, req, &resp)
return resp, err
}
// ClientTypes returns all client types available to this simulator run. This depends on
// both the available client set and the command line filters.
func (sim *Simulation) ClientTypes() ([]*ClientDefinition, error) {
if sim.docs != nil {
return sim.docs.ClientTypes()
}
var (
url = fmt.Sprintf("%s/clients", sim.url)
resp []*ClientDefinition
)
err := get(url, &resp)
return resp, err
}
// StartClient starts a new node (or other container) with the specified parameters. One
// parameter must be named CLIENT and should contain one of the client types from
// GetClientTypes. The input is used as environment variables in the new container.
// Returns container id and ip.
func (sim *Simulation) StartClient(testSuite SuiteID, test TestID, parameters map[string]string, initFiles map[string]string) (string, net.IP, error) {
if sim.docs != nil {
return "", nil, errors.New("StartClient is not supported in docs mode")
}
clientType, ok := parameters["CLIENT"]
if !ok {
return "", nil, errors.New("missing 'CLIENT' parameter")
}
return sim.StartClientWithOptions(testSuite, test, clientType, Params(parameters), WithStaticFiles(initFiles))
}
// StartClientWithOptions starts a new node (or other container) with specified options.
// Returns container id and ip.
func (sim *Simulation) StartClientWithOptions(testSuite SuiteID, test TestID, clientType string, options ...StartOption) (string, net.IP, error) {
if sim.docs != nil {
return "", nil, errors.New("StartClientWithOptions is not supported in docs mode")
}
var (
url = fmt.Sprintf("%s/testsuite/%d/test/%d/node", sim.url, testSuite, test)
resp simapi.StartNodeResponse
)
setup := &clientSetup{
files: make(map[string]func() (io.ReadCloser, error)),
config: simapi.NodeConfig{
Client: clientType,
Environment: make(map[string]string),
},
}
for _, opt := range options {
opt.apply(setup)
}
err := setup.postWithFiles(url, &resp)
if err != nil {
return "", nil, err
}
ip := net.ParseIP(resp.IP)
if ip == nil {
return resp.ID, nil, fmt.Errorf("no IP address returned")
}
return resp.ID, ip, nil
}
// StopClient signals to the host that the node is no longer required.
func (sim *Simulation) StopClient(testSuite SuiteID, test TestID, nodeid string) error {
if sim.docs != nil {
return errors.New("StopClient is not supported in docs mode")
}
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s", sim.url, testSuite, test, nodeid), nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// PauseClient signals to the host that the node needs to be paused.
func (sim *Simulation) PauseClient(testSuite SuiteID, test TestID, nodeid string) error {
if sim.docs != nil {
return errors.New("PauseClient is not supported in docs mode")
}
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s/pause", sim.url, testSuite, test, nodeid), nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// UnpauseClient signals to the host that the node needs to be unpaused.
func (sim *Simulation) UnpauseClient(testSuite SuiteID, test TestID, nodeid string) error {
if sim.docs != nil {
return errors.New("UnpauseClient is not supported in docs mode")
}
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s/pause", sim.url, testSuite, test, nodeid), nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// ClientEnodeURL returns the enode URL of a running client.
func (sim *Simulation) ClientEnodeURL(testSuite SuiteID, test TestID, node string) (string, error) {
if sim.docs != nil {
return "", errors.New("ClientEnodeURL is not supported in docs mode")
}
return sim.ClientEnodeURLNetwork(testSuite, test, node, "bridge")
}
// ClientEnodeURLCustomNetwork returns the enode URL of a running client in a custom network.
func (sim *Simulation) ClientEnodeURLNetwork(testSuite SuiteID, test TestID, node string, network string) (string, error) {
if sim.docs != nil {
return "", errors.New("ClientEnodeURLNetwork is not supported in docs mode")
}
resp, err := sim.ClientExec(testSuite, test, node, []string{"enode.sh"})
if err != nil {
return "", err
}
if resp.ExitCode != 0 {
return "", errors.New("unexpected exit code for enode.sh")
}
// Check that the container returned a valid enode URL.
output := strings.TrimSpace(resp.Stdout)
n, err := enode.ParseV4(output)
if err != nil {
return "", err
}
// Check ports returned
tcpPort := n.TCP()
if tcpPort == 0 {
tcpPort = 30303
}
udpPort := n.UDP()
if udpPort == 0 {
udpPort = 30303
}
// Get the actual IP for the container
ip, err := sim.ContainerNetworkIP(testSuite, network, node)
if err != nil {
return "", err
}
// Change IP with the real IP for the desired docker network
fixedIP := enode.NewV4(n.Pubkey(), net.ParseIP(ip), tcpPort, udpPort)
return fixedIP.URLv4(), nil
}
// ClientExec runs a command in a running client.
func (sim *Simulation) ClientExec(testSuite SuiteID, test TestID, nodeid string, cmd []string) (*ExecInfo, error) {
if sim.docs != nil {
return nil, errors.New("ClientExec is not supported in docs mode")
}
var (
url = fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s/exec", sim.url, testSuite, test, nodeid)
req = &simapi.ExecRequest{Command: cmd}
resp *ExecInfo
)
err := post(url, req, &resp)
return resp, err
}
// CreateNetwork sends a request to the hive server to create a docker network by
// the given name.
func (sim *Simulation) CreateNetwork(testSuite SuiteID, networkName string) error {
if sim.docs != nil {
return errors.New("CreateNetwork is not supported in docs mode")
}
url := fmt.Sprintf("%s/testsuite/%d/network/%s", sim.url, testSuite, networkName)
return post(url, nil, nil)
}
// RemoveNetwork sends a request to the hive server to remove the given network.
func (sim *Simulation) RemoveNetwork(testSuite SuiteID, network string) error {
if sim.docs != nil {
return errors.New("RemoveNetwork is not supported in docs mode")
}
url := fmt.Sprintf("%s/testsuite/%d/network/%s", sim.url, testSuite, network)
return requestDelete(url)
}
// ConnectContainer sends a request to the hive server to connect the given
// container to the given network.
func (sim *Simulation) ConnectContainer(testSuite SuiteID, network, containerID string) error {
if sim.docs != nil {
return errors.New("ConnectContainer is not supported in docs mode")
}
url := fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID)
return post(url, nil, nil)
}
// DisconnectContainer sends a request to the hive server to disconnect the given
// container from the given network.
func (sim *Simulation) DisconnectContainer(testSuite SuiteID, network, containerID string) error {
if sim.docs != nil {
return errors.New("DisconnectContainer is not supported in docs mode")
}
url := fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID)
return requestDelete(url)
}
// ContainerNetworkIP returns the IP address of a container on the given network. If the
// container ID is "simulation", it returns the IP address of the simulator container.
func (sim *Simulation) ContainerNetworkIP(testSuite SuiteID, network, containerID string) (string, error) {
if sim.docs != nil {
return "", errors.New("ContainerNetworkIP is not supported in docs mode")
}
var (
url = fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID)
resp string
)
err := get(url, &resp)
return resp, err
}
func (setup *clientSetup) postWithFiles(url string, result interface{}) error {
var (
pipeR, pipeW = io.Pipe()
bufW = bufio.NewWriter(pipeW)
pipeErrCh = make(chan error, 1)
form = multipart.NewWriter(bufW)
)
go func() (err error) {
defer func() { pipeErrCh <- err }()
defer pipeW.Close()
// Write 'config' parameter first.
fw, err := form.CreateFormField("config")
if err != nil {
return err
}
if err := json.NewEncoder(fw).Encode(&setup.config); err != nil {
return err
}
// Now upload the files.
for filename, open := range setup.files {
fw, err := form.CreateFormFile(filename, filepath.Base(filename))
if err != nil {
return err
}
fileReader, err := open()
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: upload error for %s: %v\n", filename, err)
return err
}
_, copyErr := io.Copy(fw, fileReader)
fileReader.Close()
if copyErr != nil {
return copyErr
}
}
// Form must be closed or the request will be missing the terminating boundary.
if err := form.Close(); err != nil {
return err
}
return bufW.Flush()
}()
// Send the request.
req, err := http.NewRequest("POST", url, pipeR)
if err != nil {
return err
}
req.Header.Set("content-type", form.FormDataContentType())
httpErr := request(req, result)
// Wait for the uploader goroutine to finish.
uploadErr := <-pipeErrCh
if httpErr == nil && uploadErr != nil {
return uploadErr
}
return httpErr
}
func get(url string, result interface{}) error {
httpReq, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(fmt.Errorf("can't create HTTP request: %v", err))
}
return request(httpReq, result)
}
func requestDelete(url string) error {
httpReq, err := http.NewRequest("DELETE", url, nil)
if err != nil {
panic(fmt.Errorf("can't create HTTP request: %v", err))
}
return request(httpReq, nil)
}
func post(url string, requestObj interface{}, result interface{}) error {
var reqBody []byte
if requestObj != nil {
var err error
if reqBody, err = json.Marshal(requestObj); err != nil {
panic(fmt.Errorf("error encoding request body: %v", err))
}
}
httpReq, err := http.NewRequest("POST", url, bytes.NewReader(reqBody))
if err != nil {
panic(fmt.Errorf("can't create HTTP request: %v", err))
}
if len(reqBody) > 0 {
httpReq.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(reqBody)), nil
}
httpReq.Header.Set("content-type", "application/json")
}
return request(httpReq, result)
}
func request(httpReq *http.Request, result interface{}) error {
resp, err := http.DefaultClient.Do(httpReq)
if err != nil {
return err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
switch {
case resp.StatusCode >= 400:
// It's an error response.
switch resp.Header.Get("content-type") {
case "application/json":
var errobj simapi.Error
if err := dec.Decode(&errobj); err != nil {
return fmt.Errorf("request failed (status %d) and can't decode error message: %v", resp.StatusCode, err)
}
return errors.New(errobj.Error)
default:
respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
if len(respBody) == 0 {
return fmt.Errorf("request failed (status %d)", resp.StatusCode)
}
return fmt.Errorf("request failed (status %d): %s", resp.StatusCode, respBody)
}
case resp.StatusCode >= 200 && resp.StatusCode < 300:
// Request was successful.
if result != nil {
if err := dec.Decode(result); err != nil {
return fmt.Errorf("invalid response (status %d): %v", resp.StatusCode, err)
}
}
return nil
default:
// 1xx and 3xx should never happen.
return fmt.Errorf("invalid response status code %d", resp.StatusCode)
}
}