forked from marioevz/hive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhive.go
356 lines (322 loc) · 10.8 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
package hivesim
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
)
// Simulation wraps the simulation HTTP API provided by hive.
type Simulation struct {
url string
}
// 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.
func New() *Simulation {
simulator, isSet := os.LookupEnv("HIVE_SIMULATOR")
if !isSet {
panic("HIVE_SIMULATOR environment variable not set")
}
return &Simulation{url: simulator}
}
// 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}
}
// 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, summaryResult TestResult) error {
// post results (which deletes the test case - because DELETE message body is not always supported)
summaryResultData, err := json.Marshal(summaryResult)
if err != nil {
return err
}
vals := make(url.Values)
vals.Add("summaryresult", string(summaryResultData))
_, err = wrapHTTPErrorsPost(fmt.Sprintf("%s/testsuite/%d/test/%d", sim.url, testSuite, test), vals)
return err
}
// StartSuite signals the start of a test suite.
func (sim *Simulation) StartSuite(name, description, simlog string) (SuiteID, error) {
vals := make(url.Values)
vals.Add("name", name)
vals.Add("description", description)
vals.Add("simlog", simlog)
idstring, err := wrapHTTPErrorsPost(fmt.Sprintf("%s/testsuite", sim.url), vals)
if err != nil {
return 0, err
}
id, err := strconv.Atoi(idstring)
if err != nil {
return 0, err
}
return SuiteID(id), nil
}
// EndSuite signals the end of a test suite.
func (sim *Simulation) EndSuite(testSuite SuiteID) error {
req, err := http.NewRequest(http.MethodDelete, fmt.Sprintf("%s/testsuite/%d", sim.url, testSuite), nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// StartTest starts a new test case, returning the testcase id as a context identifier.
func (sim *Simulation) StartTest(testSuite SuiteID, name string, description string) (TestID, error) {
vals := make(url.Values)
vals.Add("name", name)
vals.Add("description", description)
idstring, err := wrapHTTPErrorsPost(fmt.Sprintf("%s/testsuite/%d/test", sim.url, testSuite), vals)
if err != nil {
return 0, err
}
testID, err := strconv.Atoi(idstring)
if err != nil {
return 0, err
}
return TestID(testID), nil
}
// ClientMetadata is part of the ClientDefinition and lists metadata
type ClientMetadata struct {
Roles []string `yaml:"roles" json:"roles"`
}
// ClientDefinition is served by the /clients API endpoint to list the available clients
type ClientDefinition struct {
Name string `json:"name"`
Version string `json:"version"`
Meta ClientMetadata `json:"meta"`
}
func (m *ClientDefinition) HasRole(role string) bool {
for _, m := range m.Meta.Roles {
if m == role {
return true
}
}
return false
}
// 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() (availableClients []*ClientDefinition, err error) {
resp, err := http.Get(fmt.Sprintf("%s/clients?metadata=1", sim.url))
if err != nil {
return nil, err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &availableClients)
if err != nil {
return nil, err
}
return
}
// 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) {
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) {
setup := &clientSetup{
parameters: make(map[string]string),
files: make(map[string]func() (io.ReadCloser, error)),
}
setup.parameters["CLIENT"] = clientType
for _, opt := range options {
opt.Apply(setup)
}
data, err := setup.postWithFiles(fmt.Sprintf("%s/testsuite/%d/test/%d/node", sim.url, testSuite, test))
if err != nil {
return "", nil, err
}
if idip := strings.Split(data, "@"); len(idip) >= 1 {
return idip[0], net.ParseIP(idip[1]), nil
}
return data, net.IP{}, fmt.Errorf("no ip address returned: %v", data)
}
// StopClient signals to the host that the node is no longer required.
func (sim *Simulation) StopClient(testSuite SuiteID, test TestID, nodeid string) error {
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
}
// ClientEnodeURL returns the enode URL of a running client.
func (sim *Simulation) ClientEnodeURL(testSuite SuiteID, test TestID, node string) (string, error) {
resp, err := http.Get(fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s", sim.url, testSuite, test, node))
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
res := strings.TrimRight(string(body), "\r\n")
return res, nil
}
// ClientExec runs a command in a running client.
func (sim *Simulation) ClientExec(testSuite SuiteID, test TestID, nodeid string, cmd []string) (*ExecInfo, error) {
type execRequest struct {
Command []string `json:"command"`
}
enc, _ := json.Marshal(&execRequest{cmd})
p := fmt.Sprintf("%s/testsuite/%d/test/%d/node/%s/exec", sim.url, testSuite, test, nodeid)
req, err := http.NewRequest(http.MethodPost, p, bytes.NewReader(enc))
if err != nil {
return nil, err
}
req.Header.Set("content-type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if resp.Body == nil {
return nil, errors.New("unexpected empty response body")
}
dec := json.NewDecoder(resp.Body)
var res ExecInfo
if err := dec.Decode(&res); err != nil {
return nil, err
}
return &res, 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 {
_, err := http.Post(fmt.Sprintf("%s/testsuite/%d/network/%s", sim.url, testSuite, networkName), "application/json", nil)
return err
}
// RemoveNetwork sends a request to the hive server to remove the given network.
func (sim *Simulation) RemoveNetwork(testSuite SuiteID, network string) error {
endpoint := fmt.Sprintf("%s/testsuite/%d/network/%s", sim.url, testSuite, network)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// 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 {
endpoint := fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID)
_, err := http.Post(endpoint, "application/json", nil)
return err
}
// 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 {
endpoint := fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID)
req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
if err != nil {
return err
}
_, err = http.DefaultClient.Do(req)
return err
}
// 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) {
resp, err := http.Get(fmt.Sprintf("%s/testsuite/%d/network/%s/%s", sim.url, testSuite, network, containerID))
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
func (setup *clientSetup) postWithFiles(url string) (string, error) {
var err error
// make a dictionary of readers
formValues := make(map[string]io.Reader)
for key, s := range setup.parameters {
formValues[key] = strings.NewReader(s)
}
for key, src := range setup.files {
filereader, err := src()
if err != nil {
return "", err
}
formValues[key] = filereader
}
// send them
var b bytes.Buffer
w := multipart.NewWriter(&b)
for key, r := range formValues {
var fw io.Writer
if x, ok := r.(io.Closer); ok {
defer x.Close()
}
if _, ok := setup.files[key]; ok {
if fw, err = w.CreateFormFile(key, filepath.Base(key)); err != nil {
return "", err
}
} else {
if fw, err = w.CreateFormField(key); err != nil {
return "", err
}
}
if _, err = io.Copy(fw, r); err != nil {
return "", err
}
}
// this must be closed or the request will be missing the terminating boundary
w.Close()
// Can't use http.PostForm because we need to change the content header
req, err := http.NewRequest("POST", url, &b)
if err != nil {
return "", err
}
// Set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
// Submit the request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode >= 200 && resp.StatusCode <= 300 {
return string(body), nil
}
return "", fmt.Errorf("request failed (%d): %v", resp.StatusCode, string(body))
}
// wrapHttpErrorsPost wraps http.PostForm to convert responses that are not 200 OK into errors
func wrapHTTPErrorsPost(url string, data url.Values) (string, error) {
resp, err := http.PostForm(url, data)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode >= 200 && resp.StatusCode <= 300 {
return string(body), nil
}
return "", fmt.Errorf("request failed (%d): %v", resp.StatusCode, string(body))
}