-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_test.go
191 lines (165 loc) · 4.81 KB
/
api_test.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
package mdocker_test
import (
"bytes"
"compress/gzip"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os/exec"
"time"
log "github.com/Sirupsen/logrus"
"github.com/fsouza/go-dockerclient"
"github.com/mistifyio/mistify-agent-docker"
"github.com/mistifyio/mistify-agent/client"
"github.com/mistifyio/mistify-agent/rpc"
logx "github.com/mistifyio/mistify-logrus-ext"
"github.com/pborman/uuid"
"github.com/stretchr/testify/suite"
"github.com/tylerb/graceful"
)
var dockerImageData []byte
type APITestSuite struct {
suite.Suite
Port int
Client *rpc.Client
MDocker *mdocker.MDocker
ImageServer *httptest.Server
ImageService string
ImageID string
ImageData []byte
Docker *docker.Client
ContainerIDs []string
Server *graceful.Server
Bridge string
}
func (s *APITestSuite) SetupSuite() {
log.SetLevel(log.FatalLevel)
// Define ovs bridge
// This will get created when ports are added for a container.
s.Bridge = "mistify-agent-docker-test"
// Set up client to interact with API
s.Port = 54321
s.Client, _ = rpc.NewClient(uint(s.Port), "")
s.Docker, _ = docker.NewClient("unix:///var/run/docker.sock")
// Set up image
s.ImageData = dockerImageData
s.ImageID = uuid.New()
// Set up a fake ImageService to fetch images from
s.ImageServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == fmt.Sprintf("/images/%s/download", s.ImageID) {
if _, err := w.Write(s.ImageData); err != nil {
log.WithField("error", err).Error("Failed to write mock image data to response")
}
return
}
if r.URL.Path == "/images/gzipID/download" {
gzipWriter := gzip.NewWriter(w)
defer logx.LogReturnedErr(gzipWriter.Close, nil, "failed to close gzip writer")
if _, err := gzipWriter.Write(s.ImageData); err != nil {
log.WithField("error", err).Error("Failed to write mock image data to response")
}
return
}
http.NotFound(w, r)
return
}))
imageURL, _ := url.Parse(s.ImageServer.URL)
s.ImageService = imageURL.Host
// Run the MDocker
s.MDocker, _ = mdocker.New("unix:///var/run/docker.sock", s.ImageService, "")
s.Server, _ = s.MDocker.RunHTTP(uint(s.Port))
// Sleep to give the server time to start listening
time.Sleep(200 * time.Millisecond)
}
func (s *APITestSuite) SetupTest() {}
func (s *APITestSuite) TearDownTest() {}
func (s *APITestSuite) TearDownSuite() {
// Stop the image store
stopChan := s.Server.StopChan()
s.Server.Stop(5 * time.Second)
<-stopChan
// Clean up ovs
if output, err := exec.Command("ovs-vsctl", "del-br", s.Bridge).CombinedOutput(); err != nil {
log.WithFields(log.Fields{
"error": err,
"output": string(output),
}).Error("failed to remove ovs bridge")
}
// Any docker cleanup is handled on a per-suite basis
}
func (s *APITestSuite) loadImage() *rpc.Image {
response := &rpc.ImageResponse{}
request := &rpc.ImageRequest{
ID: s.ImageID,
}
s.NoError(s.Client.Do("MDocker.LoadImage", request, response))
return response.Images[0]
}
func (s *APITestSuite) createContainer() *client.Guest {
response := &rpc.GuestResponse{}
request := &rpc.GuestRequest{
Guest: &client.Guest{
ID: uuid.New(),
Image: s.ImageID,
Memory: 10,
Nics: []client.Nic{
{
Name: "test",
Network: s.Bridge,
Mac: "13:7D:DA:F2:ED:63",
VLANs: []int{1, 2, 3},
},
},
},
}
_ = s.Client.Do("MDocker.CreateContainer", request, response)
// Keep track of the ID for easier cleanup later
s.ContainerIDs = append(s.ContainerIDs, response.Guest.ID)
return response.Guest
}
func testMsgFunc(prefix string) func(...interface{}) string {
return func(val ...interface{}) string {
if len(val) == 0 {
return prefix
}
msgPrefix := prefix + " : "
if len(val) == 1 {
return msgPrefix + val[0].(string)
} else {
return msgPrefix + fmt.Sprintf(val[0].(string), val[1:]...)
}
}
}
func init() {
d, err := docker.NewClient("unix:///var/run/docker.sock")
if err != nil {
log.WithField("error", err).Fatal("could not create docker client")
}
if err := d.Ping(); err != nil {
log.WithField("error", err).Fatal("could not ping docker server")
}
// Get the docker image to serve
imgName := "tauzero/test-loop"
// Pull
pullOpts := docker.PullImageOptions{
Repository: imgName,
}
if err := d.PullImage(pullOpts, docker.AuthConfiguration{}); err != nil {
log.WithField("error", err).Fatal("failed to pull docker image")
}
// Export
output := new(bytes.Buffer)
exportOpts := docker.ExportImageOptions{
Name: imgName,
OutputStream: output,
}
if err := d.ExportImage(exportOpts); err != nil {
log.WithField("error", err).Fatal("failed to export docker image")
}
dockerImageData = output.Bytes()
// Remove
if err := d.RemoveImage(imgName); err != nil {
log.WithField("error", err).Fatal("failed to remove docker image")
}
}