Repository navigation
Expand file tree
/
Copy pathcontainer_run_test.go
More file actions
297 lines (245 loc) · 10.6 KB
/
Copy pathcontainer_run_test.go
File metadata and controls
297 lines (245 loc) · 10.6 KB
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
// Copyright 2024 Harald Albrecht.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package morbyd
import (
"context"
"errors"
"io"
"strings"
"time"
"github.com/containerd/errdefs"
"github.com/moby/moby/client"
"github.com/thediveo/safe"
mock "go.uber.org/mock/gomock"
"github.com/thediveo/morbyd/v2/internal/ensure"
"github.com/thediveo/morbyd/v2/run"
"github.com/thediveo/morbyd/v2/session"
"github.com/thediveo/morbyd/v2/timestamper"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/thediveo/success"
)
func withoutLabel(label string) run.Opt {
return func(o *run.Options) error {
ensure.Value(&o.Opts.Config)
ensure.Map(&o.Opts.Config.Labels)
delete(o.Opts.Config.Labels, label)
return nil
}
}
var _ = Describe("run container", Ordered, func() {
var sess *Session
BeforeAll(func(ctx context.Context) {
sess = Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container.run")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
})
When("failing", func() {
It("reports failing options", func(ctx context.Context) {
failopt := func(*run.Options) error { return errors.New("error IJK305I") }
Expect(sess.Run(ctx, "", failopt)).Error().To(HaveOccurred())
})
It("reports failing image checks", func(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
cancel()
Expect(sess.Run(ctx, "busybox")).Error().To(MatchError(ContainSubstring("cannot run image")))
})
It("reports failing image pulls", func(ctx context.Context) {
ctrl := mock.NewController(GinkgoT())
sess := Successful(NewSession(ctx,
WithMockController(ctrl, "ImageInspect", "ImagePull")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
rec := sess.Client().(*MockClient).EXPECT()
rec.ImageInspect(Any, Any).Return(client.ImageInspectResult{}, errdefs.ErrNotFound)
rec.ImagePull(Any, Any, Any).Return(nil, errors.New("error IJK305I"))
Expect(sess.Run(ctx, "busybox")).Error().To(MatchError(ContainSubstring("cannot pull image")))
})
It("reports creation failure", func(ctx context.Context) {
ctrl := mock.NewController(GinkgoT())
sess := Successful(NewSession(ctx,
WithMockController(ctrl, "ContainerCreate")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
rec := sess.Client().(*MockClient).EXPECT()
rec.ContainerCreate(Any, Any).Return(client.ContainerCreateResult{}, errors.New("error IJK305I"))
Expect(sess.Run(ctx, "busybox")).Error().To(MatchError(ContainSubstring("cannot create container")))
})
It("reports attachment failure and cleans up", func(ctx context.Context) {
const canaryName = "morbyd-canary-container"
ctrl := mock.NewController(GinkgoT())
sess := Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container-run"),
WithMockController(ctrl, "ContainerAttach")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
rec := sess.Client().(*MockClient).EXPECT()
rec.ContainerAttach(Any, Any, Any).Return(client.ContainerAttachResult{}, errors.New("error IJK305I"))
Expect(sess.Run(ctx, "busybox", run.WithName(canaryName))).Error().To(MatchError(ContainSubstring("cannot attach to container")))
Expect(sess.Container(ctx, canaryName)).Error().To(HaveOccurred())
})
It("reports start failure and cleans up", func(ctx context.Context) {
const canaryName = "morbyd-canary-container"
ctrl := mock.NewController(GinkgoT())
sess := Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container-run"),
WithMockController(ctrl, "ContainerStart")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
rec := sess.Client().(*MockClient).EXPECT()
rec.ContainerStart(Any, Any, Any).Return(client.ContainerStartResult{}, errors.New("error IJK305I"))
Expect(sess.Run(ctx, "busybox", run.WithName(canaryName))).Error().To(MatchError(ContainSubstring("cannot start container")))
Expect(sess.Container(ctx, canaryName)).Error().To(HaveOccurred())
})
It("reports update failure after start, and cleans up", func(ctx context.Context) {
const canaryName = "morbyd-canary-container"
ctrl := mock.NewController(GinkgoT())
sess := Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container-run"),
WithMockController(ctrl, "ContainerInspect")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
rec := sess.Client().(*MockClient).EXPECT()
rec.ContainerInspect(Any, Any, Any).Return(client.ContainerInspectResult{}, errors.New("error IJK305I"))
Expect(sess.Run(ctx, "busybox", run.WithName(canaryName))).Error().To(MatchError(ContainSubstring("cannot inspect newly started container")))
})
It("reports a container name squatter", func(ctx context.Context) {
const contentedName = "morbyd-contented-name-container"
sess := Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container-run-name-contention")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
squattercreator := caller(0, 1)
squatter := Successful(sess.Run(ctx, "busybox:latest",
run.WithName(contentedName),
run.WithCommand("/bin/sh", "-c", "while true; do sleep 1; done"),
run.WithCombinedOutput(GinkgoWriter)))
Expect(squatter.PID(ctx)).Error().ToNot(HaveOccurred())
wl, err := sess.Run(ctx, "busybox:latest",
run.WithName(contentedName),
run.WithCommand("/bin/sh", "-c", "while true; do sleep 1; done"),
run.WithCombinedOutput(GinkgoWriter))
Expect(err).To(MatchError(ContainSubstring(
"cannot create container: name already taken by " + squattercreator)))
Expect(wl).To(BeNil())
})
It("reports correctly when no container creator name available", func(ctx context.Context) {
const contentedName = "morbyd-contented-name-container"
sess := Successful(NewSession(ctx,
session.WithAutoCleaning("test.morbyd=container-run-name-contention")))
DeferCleanup(func(ctx context.Context) {
sess.Close(ctx)
})
squatter := Successful(sess.Run(ctx, "busybox:latest",
withoutLabel(ContainerRunnerLabelName),
run.WithName(contentedName),
run.WithCommand("/bin/sh", "-c", "while true; do sleep 1; done"),
run.WithCombinedOutput(GinkgoWriter)))
Expect(squatter.PID(ctx)).Error().ToNot(HaveOccurred())
wl, err := sess.Run(ctx, "busybox:latest",
run.WithName(contentedName),
run.WithCommand("/bin/sh", "-c", "while true; do sleep 1; done"),
run.WithCombinedOutput(GinkgoWriter))
Expect(err).To(MatchError(ContainSubstring(
"Conflict. The container name \"/morbyd-contented-name-container\" is already in use by container")))
Expect(wl).To(BeNil())
})
})
When("capturing output of a container", func() {
It("captures stdout and stderr separately", func(ctx context.Context) {
msg := "D'OH!"
errmsg := "D'OOOOHOOO!!"
By("running a test container")
var buff safe.Buffer
var errbuf safe.Buffer
// Providing an already primed input stream to the container results in
// the script happily slurping in this data as soon as the container has
// started. In turn, the script would already be finished and the
// container already wound done by the time we want to inspect it for
// its PID, causing spurious test failures. We thus send the script in
// idle sleep that it'll be leaving only upon SIGTERM, where we control
// when we send this SIGTERM.
input := strings.NewReader(msg + "\n")
cntr := Successful(sess.Run(ctx, "busybox",
run.WithCommand("/bin/sh", "-c",
"trap \"exit\" SIGTERM; "+
"IFS= read -r -s msg; echo \">>$msg<<\"; echo \""+errmsg+"\" 1>&2; "+
"while true; do sleep 1s; done"),
run.WithAutoRemove(),
run.WithInput(input),
// Using a timestamper io.Writer helps with diagnosing potential test
// issues, as we can relate the container's output to the test steps
// as when these are happening.
run.WithDemuxedOutput(io.MultiWriter(timestamper.New(GinkgoWriter), &buff),
io.MultiWriter(timestamper.New(GinkgoWriter), &errbuf)),
))
Expect(cntr).NotTo(BeNil())
By("retrieving the container's PID")
Expect(cntr.PID(ctx)).NotTo(BeZero())
By("talking to the container and receiving its answer")
// Expect the correct, demux'ed output on stdout and stderr.
Eventually(buff.String).Within(2 * time.Second).ProbeEvery(100 * time.Second).
Should(Equal(">>" + msg + "<<\n"))
Eventually(errbuf.String).Should(Equal(errmsg + "\n"))
By("stopping the container")
cntr.Stop(ctx)
})
It("captures combined TTY output", func(ctx context.Context) {
msg := "D'OH!"
errmsg := "D'OOOOHOOO!!"
By("running a test container")
var buff safe.Buffer
// Providing an already primed input stream to the container results in
// the script happily slurping in this data as soon as the container has
// started. In turn, the script would already be finished and the
// container already wound done by the time we want to inspect it for
// its PID, causing spurious test failures. We thus send the script in
// idle sleep that it'll be leaving only upon SIGTERM, where we control
// when we send this SIGTERM.
input := strings.NewReader(msg + "\n")
cntr := Successful(sess.Run(ctx, "busybox",
run.WithCommand("/bin/sh", "-c",
"trap \"exit\" SIGTERM; "+
"IFS= read -r -s msg; echo \">>$msg<<\"; echo \""+errmsg+"\" 1>&2; "+
"while true; do sleep 1s; done"),
run.WithAutoRemove(),
run.WithInput(input),
// Using a timestamper io.Writer helps with diagnosing potential test
// issues, as we can relate the container's output to the test steps
// as when these are happening.
run.WithTTY(),
run.WithCombinedOutput(io.MultiWriter(timestamper.New(GinkgoWriter), &buff)),
))
Expect(cntr).NotTo(BeNil())
By("retrieving the container's PID")
Expect(cntr.PID(ctx)).NotTo(BeZero())
By("talking to the container and receiving its answer")
// Expect the correct, demux'ed output on stdout and stderr.
Eventually(buff.String).Within(2 * time.Second).ProbeEvery(100 * time.Second).
Should(Equal(msg + "\r\n" +
">>" + msg + "<<\r\n" +
errmsg + "\r\n"))
By("stopping the container")
cntr.Stop(ctx)
})
})
})