-
-
Notifications
You must be signed in to change notification settings - Fork 511
/
reaper_test.go
627 lines (540 loc) · 19.4 KB
/
reaper_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
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package testcontainers
import (
"context"
"errors"
"os"
"sync"
"testing"
"time"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go/internal/config"
"github.com/testcontainers/testcontainers-go/internal/core"
"github.com/testcontainers/testcontainers-go/wait"
)
// testSessionID the tests need to create a reaper in a different session, so that it does not interfere with other tests
const testSessionID = "this-is-a-different-session-id"
type mockReaperProvider struct {
req ContainerRequest
hostConfig *container.HostConfig
enpointSettings map[string]*network.EndpointSettings
config TestcontainersConfig
initialReaper *Reaper
initialReaperOnce sync.Once
t *testing.T
}
func newMockReaperProvider(t *testing.T) *mockReaperProvider {
m := &mockReaperProvider{
config: TestcontainersConfig{
Config: config.Config{},
},
t: t,
initialReaper: reaperInstance,
//nolint:govet
initialReaperOnce: reaperOnce,
}
// explicitly reset the reaperInstance to nil to start from a fresh state
reaperInstance = nil
reaperOnce = sync.Once{}
return m
}
var errExpected = errors.New("expected")
func (m *mockReaperProvider) RestoreReaperState() {
m.t.Cleanup(func() {
reaperInstance = m.initialReaper
//nolint:govet
reaperOnce = m.initialReaperOnce
})
}
func (m *mockReaperProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error) {
m.req = req
m.hostConfig = &container.HostConfig{}
m.enpointSettings = map[string]*network.EndpointSettings{}
if req.HostConfigModifier == nil {
req.HostConfigModifier = defaultHostConfigModifier(req)
}
req.HostConfigModifier(m.hostConfig)
if req.EnpointSettingsModifier != nil {
req.EnpointSettingsModifier(m.enpointSettings)
}
// we're only interested in the request, so instead of mocking the Docker client
// we'll error out here
return nil, errExpected
}
func (m *mockReaperProvider) Config() TestcontainersConfig {
return m.config
}
// createContainerRequest creates the expected request and allows for customization
func createContainerRequest(customize func(ContainerRequest) ContainerRequest) ContainerRequest {
req := ContainerRequest{
Image: config.ReaperDefaultImage,
ExposedPorts: []string{"8080/tcp"},
Labels: core.DefaultLabels(testSessionID),
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.Binds = []string{core.ExtractDockerSocket(context.Background()) + ":/var/run/docker.sock"}
},
WaitingFor: wait.ForListeningPort(nat.Port("8080/tcp")),
Env: map[string]string{
"RYUK_CONNECTION_TIMEOUT": "1m0s",
"RYUK_RECONNECTION_TIMEOUT": "10s",
},
}
req.Labels[core.LabelReaper] = "true"
req.Labels[core.LabelRyuk] = "true"
if customize == nil {
return req
}
return customize(req)
}
func TestContainerStartsWithoutTheReaper(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if !tcConfig.RyukDisabled {
t.Skip("Ryuk is enabled, skipping test")
}
ctx := context.Background()
container, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, container)
sessionID := core.SessionID()
reaperContainer, err := lookUpReaperContainer(ctx, sessionID)
if err != nil {
t.Fatal(err, "expected reaper container not found.")
}
if reaperContainer != nil {
t.Fatal("expected zero reaper running.")
}
}
func TestContainerStartsWithTheReaper(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
ctx := context.Background()
c, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
if err != nil {
t.Fatal(err)
}
terminateContainerOnEnd(t, ctx, c)
sessionID := core.SessionID()
reaperContainer, err := lookUpReaperContainer(ctx, sessionID)
if err != nil {
t.Fatal(err, "expected reaper container running.")
}
if reaperContainer == nil {
t.Fatal("expected one reaper to be running.")
}
}
func TestContainerStopWithReaper(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
ctx := context.Background()
nginxA, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, nginxA)
state, err := nginxA.State(ctx)
if err != nil {
t.Fatal(err)
}
if state.Running != true {
t.Fatal("The container shoud be in running state")
}
stopTimeout := 10 * time.Second
err = nginxA.Stop(ctx, &stopTimeout)
if err != nil {
t.Fatal(err)
}
state, err = nginxA.State(ctx)
if err != nil {
t.Fatal(err)
}
if state.Running != false {
t.Fatal("The container shoud not be running")
}
if state.Status != "exited" {
t.Fatal("The container shoud be in exited state")
}
}
func TestContainerTerminationWithReaper(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
ctx := context.Background()
nginxA, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
if err != nil {
t.Fatal(err)
}
state, err := nginxA.State(ctx)
if err != nil {
t.Fatal(err)
}
if state.Running != true {
t.Fatal("The container shoud be in running state")
}
err = nginxA.Terminate(ctx)
if err != nil {
t.Fatal(err)
}
_, err = nginxA.State(ctx)
if err == nil {
t.Fatal("expected error from container inspect.")
}
}
func TestContainerTerminationWithoutReaper(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if !tcConfig.RyukDisabled {
t.Skip("Ryuk is enabled, skipping test")
}
ctx := context.Background()
nginxA, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Image: nginxAlpineImage,
ExposedPorts: []string{
nginxDefaultPort,
},
},
Started: true,
})
if err != nil {
t.Fatal(err)
}
state, err := nginxA.State(ctx)
if err != nil {
t.Fatal(err)
}
if state.Running != true {
t.Fatal("The container shoud be in running state")
}
err = nginxA.Terminate(ctx)
if err != nil {
t.Fatal(err)
}
_, err = nginxA.State(ctx)
if err == nil {
t.Fatal("expected error from container inspect.")
}
}
func Test_NewReaper(t *testing.T) {
type cases struct {
name string
req ContainerRequest
config TestcontainersConfig
ctx context.Context
env map[string]string
}
tests := []cases{
{
name: "non-privileged",
req: createContainerRequest(nil),
config: TestcontainersConfig{Config: config.Config{
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Second,
}},
},
{
name: "privileged",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.Privileged = true
return req
}),
config: TestcontainersConfig{Config: config.Config{
RyukPrivileged: true,
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Second,
}},
},
{
name: "configured non-default timeouts",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.Env = map[string]string{
"RYUK_CONNECTION_TIMEOUT": "1m0s",
"RYUK_RECONNECTION_TIMEOUT": "10m0s",
}
return req
}),
config: TestcontainersConfig{Config: config.Config{
RyukPrivileged: true,
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Minute,
}},
},
{
name: "configured verbose mode",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.Env = map[string]string{
"RYUK_VERBOSE": "true",
}
return req
}),
config: TestcontainersConfig{Config: config.Config{
RyukPrivileged: true,
RyukVerbose: true,
}},
},
{
name: "docker-host in context",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.HostConfigModifier = func(hostConfig *container.HostConfig) {
hostConfig.Binds = []string{core.ExtractDockerSocket(context.Background()) + ":/var/run/docker.sock"}
}
return req
}),
config: TestcontainersConfig{Config: config.Config{
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Second,
}},
ctx: context.WithValue(context.TODO(), core.DockerHostContextKey, core.DockerSocketPathWithSchema),
},
{
name: "Reaper including custom Hub prefix",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.Image = config.ReaperDefaultImage
req.Privileged = true
return req
}),
config: TestcontainersConfig{Config: config.Config{
HubImageNamePrefix: "registry.mycompany.com/mirror",
RyukPrivileged: true,
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Second,
}},
},
{
name: "Reaper including custom Hub prefix as env var",
req: createContainerRequest(func(req ContainerRequest) ContainerRequest {
req.Image = config.ReaperDefaultImage
req.Privileged = true
return req
}),
config: TestcontainersConfig{Config: config.Config{
RyukPrivileged: true,
RyukConnectionTimeout: time.Minute,
RyukReconnectionTimeout: 10 * time.Second,
}},
env: map[string]string{
"TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX": "registry.mycompany.com/mirror",
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.env != nil {
config.Reset() // reset the config using the internal method to avoid the sync.Once
for k, v := range test.env {
t.Setenv(k, v)
}
}
if prefix := os.Getenv("TESTCONTAINERS_HUB_IMAGE_NAME_PREFIX"); prefix != "" {
test.config.Config.HubImageNamePrefix = prefix
}
provider := newMockReaperProvider(t)
provider.config = test.config
t.Cleanup(provider.RestoreReaperState)
if test.ctx == nil {
test.ctx = context.TODO()
}
_, err := reuseOrCreateReaper(test.ctx, testSessionID, provider)
// we should have errored out see mockReaperProvider.RunContainer
require.EqualError(t, err, "expected")
assert.Equal(t, test.req.Image, provider.req.Image, "expected image doesn't match the submitted request")
assert.Equal(t, test.req.ExposedPorts, provider.req.ExposedPorts, "expected exposed ports don't match the submitted request")
assert.Equal(t, test.req.Labels, provider.req.Labels, "expected labels don't match the submitted request")
assert.Equal(t, test.req.Mounts, provider.req.Mounts, "expected mounts don't match the submitted request")
assert.Equal(t, test.req.WaitingFor, provider.req.WaitingFor, "expected waitingFor don't match the submitted request")
assert.Equal(t, test.req.Env, provider.req.Env, "expected env doesn't match the submitted request")
// checks for reaper's preCreationCallback fields
assert.Equal(t, container.NetworkMode(Bridge), provider.hostConfig.NetworkMode, "expected networkMode doesn't match the submitted request")
assert.True(t, provider.hostConfig.AutoRemove, "expected networkMode doesn't match the submitted request")
})
}
}
func Test_ReaperReusedIfHealthy(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
testProvider := newMockReaperProvider(t)
t.Cleanup(testProvider.RestoreReaperState)
SkipIfProviderIsNotHealthy(&testing.T{})
ctx := context.Background()
// As other integration tests run with the (shared) Reaper as well, re-use the instance to not interrupt other tests
wasReaperRunning := reaperInstance != nil
provider, _ := ProviderDocker.GetProvider()
reaper, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "creating the Reaper should not error")
reaperReused, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "reusing the Reaper should not error")
// assert that the internal state of both reaper instances is the same
assert.Equal(t, reaper.SessionID, reaperReused.SessionID, "expecting the same SessionID")
assert.Equal(t, reaper.Endpoint, reaperReused.Endpoint, "expecting the same reaper endpoint")
assert.Equal(t, reaper.Provider, reaperReused.Provider, "expecting the same container provider")
assert.Equal(t, reaper.container.GetContainerID(), reaperReused.container.GetContainerID(), "expecting the same container ID")
assert.Equal(t, reaper.container.SessionID(), reaperReused.container.SessionID(), "expecting the same session ID")
terminate, err := reaper.Connect()
defer func(term chan bool) {
term <- true
}(terminate)
require.NoError(t, err, "connecting to Reaper should be successful")
if !wasReaperRunning {
terminateContainerOnEnd(t, ctx, reaper.container)
}
}
func Test_RecreateReaperIfTerminated(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
mockProvider := newMockReaperProvider(t)
t.Cleanup(mockProvider.RestoreReaperState)
SkipIfProviderIsNotHealthy(&testing.T{})
provider, _ := ProviderDocker.GetProvider()
ctx := context.Background()
reaper, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "creating the Reaper should not error")
terminate, err := reaper.Connect()
require.NoError(t, err, "connecting to Reaper should be successful")
terminate <- true
// Wait for ryuk's default timeout (10s) + 1s to allow for a graceful shutdown/cleanup of the container.
time.Sleep(11 * time.Second)
recreatedReaper, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "creating the Reaper should not error")
assert.NotEqual(t, reaper.container.GetContainerID(), recreatedReaper.container.GetContainerID(), "expected different container ID")
terminate, err = recreatedReaper.Connect()
defer func(term chan bool) {
term <- true
}(terminate)
require.NoError(t, err, "connecting to Reaper should be successful")
terminateContainerOnEnd(t, ctx, recreatedReaper.container)
}
func TestReaper_reuseItFromOtherTestProgramUsingDocker(t *testing.T) {
config.Reset() // reset the config using the internal method to avoid the sync.Once
tcConfig := config.Read()
if tcConfig.RyukDisabled {
t.Skip("Ryuk is disabled, skipping test")
}
mockProvider := &mockReaperProvider{
initialReaper: reaperInstance,
//nolint:govet
initialReaperOnce: reaperOnce,
t: t,
}
t.Cleanup(mockProvider.RestoreReaperState)
// explicitly set the reaperInstance to nil to simulate another test program in the same session accessing the same reaper
reaperInstance = nil
reaperOnce = sync.Once{}
SkipIfProviderIsNotHealthy(&testing.T{})
ctx := context.Background()
// As other integration tests run with the (shared) Reaper as well, re-use the instance to not interrupt other tests
wasReaperRunning := reaperInstance != nil
provider, _ := ProviderDocker.GetProvider()
reaper, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "creating the Reaper should not error")
// explicitly reset the reaperInstance to nil to simulate another test program in the same session accessing the same reaper
reaperInstance = nil
reaperOnce = sync.Once{}
reaperReused, err := reuseOrCreateReaper(context.WithValue(ctx, core.DockerHostContextKey, provider.(*DockerProvider).host), testSessionID, provider)
require.NoError(t, err, "reusing the Reaper should not error")
// assert that the internal state of both reaper instances is the same
assert.Equal(t, reaper.SessionID, reaperReused.SessionID, "expecting the same SessionID")
assert.Equal(t, reaper.Endpoint, reaperReused.Endpoint, "expecting the same reaper endpoint")
assert.Equal(t, reaper.Provider, reaperReused.Provider, "expecting the same container provider")
assert.Equal(t, reaper.container.GetContainerID(), reaperReused.container.GetContainerID(), "expecting the same container ID")
assert.Equal(t, reaper.container.SessionID(), reaperReused.container.SessionID(), "expecting the same session ID")
terminate, err := reaper.Connect()
defer func(term chan bool) {
term <- true
}(terminate)
require.NoError(t, err, "connecting to Reaper should be successful")
if !wasReaperRunning {
terminateContainerOnEnd(t, ctx, reaper.container)
}
}
// TestReaper_ReuseRunning tests whether reusing the reaper if using
// testcontainers from concurrently multiple packages works as expected. In this
// case, global locks are without any effect as Go tests different packages
// isolated. Therefore, this test does not use the same logic with locks on
// purpose. We expect reaper creation to still succeed in case a reaper is
// already running for the same session id by returning its container instance
// instead.
func TestReaper_ReuseRunning(t *testing.T) {
const concurrency = 64
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
sessionID := SessionID()
dockerProvider, err := NewDockerProvider()
require.NoError(t, err, "new docker provider should not fail")
obtainedReaperContainerIDs := make([]string, concurrency)
var wg sync.WaitGroup
for i := 0; i < concurrency; i++ {
i := i
wg.Add(1)
go func() {
defer wg.Done()
reaperContainer, err := lookUpReaperContainer(timeout, sessionID)
if err == nil && reaperContainer != nil {
// Found.
obtainedReaperContainerIDs[i] = reaperContainer.GetContainerID()
return
}
// Not found -> create.
createdReaper, err := newReaper(timeout, sessionID, dockerProvider)
require.NoError(t, err, "new reaper should not fail")
obtainedReaperContainerIDs[i] = createdReaper.container.GetContainerID()
}()
}
wg.Wait()
// Assure that all calls returned the same container.
firstContainerID := obtainedReaperContainerIDs[0]
for i, containerID := range obtainedReaperContainerIDs {
assert.Equal(t, firstContainerID, containerID, "call %d should have returned same container id", i)
}
}