-
Notifications
You must be signed in to change notification settings - Fork 141
/
Copy pathtest.go
405 lines (359 loc) · 9.54 KB
/
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
package util
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/mndrix/tap-go"
"github.com/mrunalp/fileutils"
rspec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/runtime-tools/specerror"
"github.com/satori/go.uuid"
)
var (
// RuntimeCommand is the default runtime command.
RuntimeCommand = "runc"
)
// LifecycleAction defines the phases will be called.
type LifecycleAction int
const (
// LifecycleActionNone does nothing
LifecycleActionNone = 0
// LifecycleActionCreate creates a container
LifecycleActionCreate = 1 << iota
// LifecycleActionStart starts a container
LifecycleActionStart
// LifecycleActionDelete deletes a container
LifecycleActionDelete
)
// LifecycleStatus follows https://github.com/opencontainers/runtime-spec/blob/master/runtime.md#state
type LifecycleStatus int
const (
// LifecycleStatusCreating "creating"
LifecycleStatusCreating = 1 << iota
// LifecycleStatusCreated "created"
LifecycleStatusCreated
// LifecycleStatusRunning "running"
LifecycleStatusRunning
// LifecycleStatusStopped "stopped"
LifecycleStatusStopped
)
var lifecycleStatusMap = map[rspec.ContainerState]LifecycleStatus{
rspec.StateCreating: LifecycleStatusCreating,
rspec.StateCreated: LifecycleStatusCreated,
rspec.StateRunning: LifecycleStatusRunning,
rspec.StateStopped: LifecycleStatusStopped,
}
// LifecycleConfig includes
// 1. Config to set the 'config.json'
// 2. BundleDir to set the bundle directory
// 3. Actions to define the default running lifecycles
// 4. Four phases for user to add his/her own operations
type LifecycleConfig struct {
Config *generate.Generator
BundleDir string
Actions LifecycleAction
PreCreate func(runtime *Runtime) error
PostCreate func(runtime *Runtime) error
PreDelete func(runtime *Runtime) error
PostDelete func(runtime *Runtime) error
}
// PreFunc initializes the test environment after preparing the bundle
// but before creating the container.
type PreFunc func(string) error
// AfterFunc validate container's outside environment after created
type AfterFunc func(config *rspec.Spec, t *tap.T, state *rspec.State) error
func init() {
runtimeInEnv := os.Getenv("RUNTIME")
if runtimeInEnv != "" {
RuntimeCommand = runtimeInEnv
}
}
// Fatal prints a warning to stderr and exits.
func Fatal(err error) {
fmt.Fprintf(os.Stderr, "%+v\n", err)
os.Exit(1)
}
// Skip skips a full TAP suite.
func Skip(message string, diagnostic interface{}) {
t := tap.New()
t.Header(1)
t.Skip(1, message)
if diagnostic != nil {
t.YAML(diagnostic)
}
}
// SpecErrorOK generates TAP output indicating whether a spec code test passed or failed.
func SpecErrorOK(t *tap.T, expected bool, specErr error, detailedErr error) {
t.Ok(expected, specErr.(*specerror.Error).Err.Err.Error())
diagnostic := map[string]string{
"reference": specErr.(*specerror.Error).Err.Reference,
}
if detailedErr != nil {
diagnostic["error"] = detailedErr.Error()
if e, ok := detailedErr.(*exec.ExitError); ok {
if len(e.Stderr) > 0 {
diagnostic["stderr"] = string(e.Stderr)
}
}
}
t.YAML(diagnostic)
}
// PrepareBundle creates a test bundle in a temporary directory.
func PrepareBundle() (string, error) {
bundleDir, err := ioutil.TempDir("", "ocitest")
if err != nil {
return "", err
}
// Untar the root fs
untarCmd := exec.Command("tar", "-xf", fmt.Sprintf("rootfs-%s.tar.gz", runtime.GOARCH), "-C", bundleDir)
output, err := untarCmd.CombinedOutput()
if err != nil {
os.Stderr.Write(output)
os.RemoveAll(bundleDir)
return "", err
}
return bundleDir, nil
}
// GetDefaultGenerator creates a default configuration generator.
func GetDefaultGenerator() (*generate.Generator, error) {
g, err := generate.New(runtime.GOOS)
if err != nil {
return nil, err
}
g.SetRootPath(".")
g.SetProcessArgs([]string{"/runtimetest", "--path=/"})
return &g, err
}
// WaitingForStatus waits an expected runtime status, return error if
// 1. fail to query the status
// 2. timeout
func WaitingForStatus(r Runtime, status LifecycleStatus, retryTimeout time.Duration, pollInterval time.Duration) error {
for start := time.Now(); time.Since(start) < retryTimeout; time.Sleep(pollInterval) {
state, err := r.State()
if err != nil {
return err
}
if v, ok := lifecycleStatusMap[state.Status]; ok {
if status&v != 0 {
return nil
}
} else {
// In spec, it says 'Additional values MAY be defined by the runtime'.
continue
}
}
return errors.New("timeout in waiting for the container status")
}
var runtimeInsideValidateCalled bool
// RuntimeInsideValidate runs runtimetest inside a container.
func RuntimeInsideValidate(g *generate.Generator, t *tap.T, f PreFunc) (err error) {
bundleDir, err := PrepareBundle()
if err != nil {
return err
}
if f != nil {
if err := f(bundleDir); err != nil {
return err
}
}
r, err := NewRuntime(RuntimeCommand, bundleDir)
if err != nil {
os.RemoveAll(bundleDir)
return err
}
defer r.Clean(true, true)
err = r.SetConfig(g)
if err != nil {
return err
}
err = fileutils.CopyFile("runtimetest", filepath.Join(r.BundleDir, "runtimetest"))
if err != nil {
return err
}
r.SetID(uuid.NewV4().String())
err = r.Create()
if err != nil {
os.Stderr.WriteString("failed to create the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
err = r.Start()
if err != nil {
os.Stderr.WriteString("failed to start the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
err = WaitingForStatus(r, LifecycleStatusStopped, 10*time.Second, 1*time.Second)
if err != nil {
return err
}
stdout, stderr, err := r.ReadStandardStreams()
if err != nil {
if len(stderr) == 0 {
stderr = stdout
}
os.Stderr.WriteString("failed to read standard streams\n")
os.Stderr.Write(stderr)
return err
}
// Write stdout in the outter TAP
if t != nil {
diagnostic := map[string]string{
"stdout": string(stdout),
"stderr": string(stderr),
}
if err != nil {
diagnostic["error"] = fmt.Sprintf("%v", err)
}
t.YAML(diagnostic)
t.Ok(err == nil && !strings.Contains(string(stdout), "not ok"), g.Config.Annotations["TestName"])
} else {
if runtimeInsideValidateCalled {
Fatal(errors.New("RuntimeInsideValidate called several times in the same test without passing TAP"))
}
runtimeInsideValidateCalled = true
os.Stdout.Write(stdout)
}
return nil
}
// RuntimeOutsideValidate validate runtime outside a container.
func RuntimeOutsideValidate(g *generate.Generator, t *tap.T, f AfterFunc) error {
bundleDir, err := PrepareBundle()
if err != nil {
return err
}
r, err := NewRuntime(RuntimeCommand, bundleDir)
if err != nil {
os.RemoveAll(bundleDir)
return err
}
defer r.Clean(true, true)
err = r.SetConfig(g)
if err != nil {
return err
}
err = fileutils.CopyFile("runtimetest", filepath.Join(r.BundleDir, "runtimetest"))
if err != nil {
return err
}
r.SetID(uuid.NewV4().String())
err = r.Create()
if err != nil {
os.Stderr.WriteString("failed to create the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
if f != nil {
state, err := r.State()
if err != nil {
return err
}
if err := f(g.Spec(), t, &state); err != nil {
return err
}
}
return nil
}
// RuntimeLifecycleValidate validates runtime lifecycle.
func RuntimeLifecycleValidate(config LifecycleConfig) error {
var bundleDir string
var err error
if config.BundleDir == "" {
bundleDir, err = PrepareBundle()
if err != nil {
return err
}
defer os.RemoveAll(bundleDir)
} else {
bundleDir = config.BundleDir
}
r, err := NewRuntime(RuntimeCommand, bundleDir)
if err != nil {
return err
}
if config.Config != nil {
if err := r.SetConfig(config.Config); err != nil {
return err
}
}
if config.PreCreate != nil {
if err := config.PreCreate(&r); err != nil {
return err
}
}
if config.Actions&LifecycleActionCreate != 0 {
err := r.Create()
if err != nil {
os.Stderr.WriteString("failed to create the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
if config.Actions&LifecycleActionDelete != 0 {
defer func() {
// runtime error or the container is already deleted
if _, err := r.State(); err != nil {
return
}
r.Kill("KILL")
err := WaitingForStatus(r, LifecycleStatusStopped, time.Second*10, time.Second*1)
if err == nil {
r.Delete()
} else {
os.Stderr.WriteString("failed to delete the container\n")
os.Stderr.WriteString(err.Error())
}
}()
}
}
if config.PostCreate != nil {
if err := config.PostCreate(&r); err != nil {
return err
}
}
if config.Actions&LifecycleActionStart != 0 {
err := r.Start()
if err != nil {
os.Stderr.WriteString("failed to start the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
}
if config.PreDelete != nil {
if err := config.PreDelete(&r); err != nil {
return err
}
}
if config.Actions&LifecycleActionDelete != 0 {
err := r.Delete()
if err != nil {
os.Stderr.WriteString("failed to delete the container\n")
if e, ok := err.(*exec.ExitError); ok && len(e.Stderr) > 0 {
os.Stderr.Write(e.Stderr)
}
return err
}
}
if config.PostDelete != nil {
if err := config.PostDelete(&r); err != nil {
return err
}
}
return nil
}