/
garden_integration_tests_suite_test.go
340 lines (284 loc) · 8.47 KB
/
garden_integration_tests_suite_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
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
package garden_integration_tests_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"testing"
"time"
"code.cloudfoundry.org/garden"
"code.cloudfoundry.org/garden-integration-tests/testhelpers"
"code.cloudfoundry.org/garden/client"
"code.cloudfoundry.org/garden/client/connection"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"github.com/onsi/gomega/gbytes"
"github.com/onsi/gomega/gexec"
)
var (
gardenHost string
gardenPort string
gardenDebugPort string
gardenRootfs string
gardenClient garden.Client
container garden.Container
containerStartUsage uint64
containerCreateErr error
assertContainerCreate bool
handle string
imageRef garden.ImageRef
networkSpec string
privilegedContainer bool
properties garden.Properties
limits garden.Limits
env []string
consumeBin string
limitsTestURI string
limitsTestContainerImageSize uint64 // Obtained by summing the values in <groot-image-store>\layers\<layer-id>\size
)
var _ = SynchronizedBeforeSuite(func() []byte {
host := os.Getenv("GDN_BIND_IP")
if host == "" {
host = "10.244.0.2"
}
rootfs, exists := os.LookupEnv("GARDEN_TEST_ROOTFS")
ExpectWithOffset(1, exists).To(BeTrue(), "Set GARDEN_TEST_ROOTFS Env variable")
binary := ""
if runtime.GOOS == "windows" {
var err error
binary, err = gexec.Build("code.cloudfoundry.org/garden-integration-tests/plugins/consume-mem")
Expect(err).ToNot(HaveOccurred())
}
limitsURI, exists := os.LookupEnv("LIMITS_TEST_URI")
ExpectWithOffset(1, exists).To(BeTrue(), "Set LIMITS_TEST_URI Env variable")
testData := make(map[string]interface{})
testData["gardenHost"] = host
testData["gardenRootfs"] = rootfs
testData["consumeBin"] = binary
testData["limitsTestUri"] = limitsURI
json, err := json.Marshal(testData)
Expect(err).NotTo(HaveOccurred())
return json
}, func(jsonBytes []byte) {
testData := make(map[string]interface{})
Expect(json.Unmarshal(jsonBytes, &testData)).To(Succeed())
gardenHost = testData["gardenHost"].(string)
gardenRootfs = testData["gardenRootfs"].(string)
consumeBin = testData["consumeBin"].(string)
limitsTestURI = testData["limitsTestUri"].(string)
limitsTestContainerImageSize = 4562899158 //Used only in windows tests
})
func TestGardenIntegrationTests(t *testing.T) {
RegisterFailHandler(Fail)
SetDefaultEventuallyTimeout(15 * time.Second)
AfterSuite(func() {
gexec.CleanupBuildArtifacts()
})
BeforeEach(func() {
assertContainerCreate = true
handle = ""
imageRef = garden.ImageRef{}
networkSpec = ""
privilegedContainer = false
properties = garden.Properties{}
limits = garden.Limits{}
env = []string{}
gardenPort = os.Getenv("GDN_BIND_PORT")
if gardenPort == "" {
gardenPort = "7777"
}
gardenDebugPort = os.Getenv("GDN_DEBUG_PORT")
if gardenDebugPort == "" {
gardenDebugPort = "17013"
}
retryingConnection := testhelpers.RetryingConnection{Connection: connection.New("tcp", fmt.Sprintf("%s:%s", gardenHost, gardenPort))}
gardenClient = client.New(&retryingConnection)
})
JustBeforeEach(func() {
container, containerCreateErr = gardenClient.Create(garden.ContainerSpec{
Handle: handle,
Image: imageRef,
Privileged: privilegedContainer,
Properties: properties,
Env: env,
Limits: limits,
Network: networkSpec,
})
if container != nil {
containerStartUsage = getContainerUsage(container.Handle())
fmt.Fprintf(GinkgoWriter, "Container handle: %s\n", container.Handle())
}
if assertContainerCreate {
Expect(containerCreateErr).ToNot(HaveOccurred())
}
})
AfterEach(func() {
if container != nil {
Expect(destroyContainer(container)).To(Succeed())
}
})
RunSpecs(t, "GardenIntegrationTests Suite")
}
func destroyContainer(c garden.Container) error {
// ignoring the error since it can return unknown handle error
theContainer, _ := gardenClient.Lookup(c.Handle())
if theContainer != nil {
return gardenClient.Destroy(theContainer.Handle())
}
return nil
}
func getContainerHandles() []string {
containers, err := gardenClient.Containers(nil)
Expect(err).ToNot(HaveOccurred())
handles := make([]string, len(containers))
for i, c := range containers {
handles[i] = c.Handle()
}
return handles
}
func createUser(container garden.Container, username string) {
if container == nil {
return
}
var spec garden.ProcessSpec
if runtime.GOOS == "windows" {
spec = garden.ProcessSpec{
User: "",
Path: "cmd.exe",
Args: []string{"/c", fmt.Sprintf("net user %s /ADD /passwordreq:no && runas /user:%s whoami", username, username)},
}
} else {
spec = garden.ProcessSpec{
User: "root",
Path: "sh",
Args: []string{"-c", fmt.Sprintf("id -u %s || adduser -D %s", username, username)},
}
}
process, err := container.Run(spec, garden.ProcessIO{
Stdout: GinkgoWriter,
Stderr: GinkgoWriter,
})
Expect(err).ToNot(HaveOccurred())
Expect(process.Wait()).To(Equal(0))
}
func getKernelVersion() (int, int) {
ctr, err := gardenClient.Create(garden.ContainerSpec{})
Expect(err).NotTo(HaveOccurred())
defer gardenClient.Destroy(ctr.Handle())
var outBytes bytes.Buffer
process, err := ctr.Run(garden.ProcessSpec{
User: "root",
Path: "uname",
Args: []string{"-r"},
}, garden.ProcessIO{
Stdout: &outBytes,
})
Expect(err).ToNot(HaveOccurred())
Expect(process.Wait()).To(Equal(0))
vSplit := strings.Split(outBytes.String(), ".")
major, err := strconv.Atoi(vSplit[0])
Expect(err).NotTo(HaveOccurred())
minor, err := strconv.Atoi(vSplit[1])
Expect(err).NotTo(HaveOccurred())
return major, minor
}
func skipIfWoot(reason string) {
if woot() {
Skip("Skipping this test because I am WOOT: " + reason)
}
}
func woot() bool {
return os.Getenv("WOOT") != ""
}
func skipIfShed() {
if shed() {
Skip("Skipping this test - not applicable to shed")
}
}
func shed() bool {
return os.Getenv("SHED") != ""
}
func skipIfContainerdForProcesses() {
if isContainerdForProcesses() {
Skip("Skipping because containerd support for processes is enabled")
}
}
func isContainerdForProcesses() bool {
return os.Getenv("CONTAINERD_FOR_PROCESSES_ENABLED") != "false"
}
func setPrivileged() {
privilegedContainer = true
}
func runProcessWithIO(container garden.Container, processSpec garden.ProcessSpec, pio garden.ProcessIO) int {
proc, err := container.Run(processSpec, pio)
Expect(err).NotTo(HaveOccurred())
processExitCode, err := proc.Wait()
Expect(err).NotTo(HaveOccurred())
return processExitCode
}
func runProcess(container garden.Container, processSpec garden.ProcessSpec) (exitCode int, stdout, stderr *gbytes.Buffer) {
stdout, stderr = gbytes.NewBuffer(), gbytes.NewBuffer()
pio := garden.ProcessIO{
Stdout: io.MultiWriter(stdout, GinkgoWriter),
Stderr: io.MultiWriter(stderr, GinkgoWriter),
}
exitCode = runProcessWithIO(container, processSpec, pio)
return
}
func runForStdout(container garden.Container, processSpec garden.ProcessSpec) (stdout *gbytes.Buffer) {
exitCode, stdout, _ := runProcess(container, processSpec)
Expect(exitCode).To(Equal(0))
return stdout
}
func getContainerUsage(handle string) uint64 {
if runtime.GOOS != "windows" {
return 0
}
// Get the volume path
winc_binary, exists := os.LookupEnv("WINC_BINARY")
ExpectWithOffset(1, exists).To(BeTrue(), "Set WINC_BINARY Env variable")
cmd := exec.Command(winc_binary, "state", handle)
cmdOut := new(bytes.Buffer)
cmd.Stdout = cmdOut
err := cmd.Run()
ExpectWithOffset(1, err).ToNot(HaveOccurred())
// Get the pid
type containerState struct {
Pid int `json:"pid"`
}
var cs containerState
err = json.Unmarshal(cmdOut.Bytes(), &cs)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
// Get the amount of disk in use
path := fmt.Sprintf("C:\\proc\\%d\\root", cs.Pid)
cmd = exec.Command("powershell", fmt.Sprintf("(Get-FSRMQuota %s).Usage", path))
cmdOut = new(bytes.Buffer)
cmd.Stdout = cmdOut
err = cmd.Run()
ExpectWithOffset(1, err).ToNot(HaveOccurred())
usage := strings.TrimSpace(cmdOut.String())
if usage == "" {
usage = "0"
}
uintUsage, err := strconv.ParseUint(usage, 10, 64)
ExpectWithOffset(1, err).ToNot(HaveOccurred())
return uintUsage
}
func httpGet(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
}
return string(body), nil
}