-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
exec_test.go
1827 lines (1546 loc) · 45.7 KB
/
exec_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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package integration
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strconv"
"strings"
"syscall"
"testing"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/cgroups/systemd"
"github.com/opencontainers/runc/libcontainer/configs"
"github.com/opencontainers/runc/libcontainer/internal/userns"
"github.com/opencontainers/runc/libcontainer/utils"
"github.com/opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
)
func TestExecPS(t *testing.T) {
testExecPS(t, false)
}
func TestUsernsExecPS(t *testing.T) {
if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) {
t.Skip("Test requires userns.")
}
testExecPS(t, true)
}
func testExecPS(t *testing.T, userns bool) {
if testing.Short() {
return
}
config := newTemplateConfig(t, &tParam{userns: userns})
buffers := runContainerOk(t, config, "ps", "-o", "pid,user,comm")
lines := strings.Split(buffers.Stdout.String(), "\n")
if len(lines) < 2 {
t.Fatalf("more than one process running for output %q", buffers.Stdout.String())
}
expected := `1 root ps`
actual := strings.Trim(lines[1], "\n ")
if actual != expected {
t.Fatalf("expected output %q but received %q", expected, actual)
}
}
func TestIPCPrivate(t *testing.T) {
if testing.Short() {
return
}
l, err := os.Readlink("/proc/1/ns/ipc")
ok(t, err)
config := newTemplateConfig(t, nil)
buffers := runContainerOk(t, config, "readlink", "/proc/self/ns/ipc")
if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual == l {
t.Fatalf("ipc link should be private to the container but equals host %q %q", actual, l)
}
}
func TestIPCHost(t *testing.T) {
if testing.Short() {
return
}
l, err := os.Readlink("/proc/1/ns/ipc")
ok(t, err)
config := newTemplateConfig(t, nil)
config.Namespaces.Remove(configs.NEWIPC)
buffers := runContainerOk(t, config, "readlink", "/proc/self/ns/ipc")
if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l {
t.Fatalf("ipc link not equal to host link %q %q", actual, l)
}
}
func TestIPCJoinPath(t *testing.T) {
if testing.Short() {
return
}
l, err := os.Readlink("/proc/1/ns/ipc")
ok(t, err)
config := newTemplateConfig(t, nil)
config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipc")
buffers := runContainerOk(t, config, "readlink", "/proc/self/ns/ipc")
if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l {
t.Fatalf("ipc link not equal to host link %q %q", actual, l)
}
}
func TestIPCBadPath(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipcc")
if _, _, err := runContainer(t, config, "true"); err == nil {
t.Fatal("container succeeded with bad ipc path")
}
}
func TestRlimit(t *testing.T) {
testRlimit(t, false)
}
func TestUsernsRlimit(t *testing.T) {
if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) {
t.Skip("Test requires userns.")
}
testRlimit(t, true)
}
func testRlimit(t *testing.T, userns bool) {
if testing.Short() {
return
}
config := newTemplateConfig(t, &tParam{userns: userns})
// Ensure limit is lower than what the config requests to test that in a user namespace
// the Setrlimit call happens early enough that we still have permissions to raise the limit.
// Do not change the Cur value to be equal to the Max value, please see:
// https://github.com/opencontainers/runc/pull/4265#discussion_r1589666444
ok(t, unix.Setrlimit(unix.RLIMIT_NOFILE, &unix.Rlimit{
Max: 1024,
Cur: 512,
}))
out := runContainerOk(t, config, "/bin/sh", "-c", "ulimit -n")
if limit := strings.TrimSpace(out.Stdout.String()); limit != "1025" {
t.Fatalf("expected rlimit to be 1025, got %s", limit)
}
}
func TestEnter(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
// Execute a first process in the container
stdinR, stdinW, err := os.Pipe()
ok(t, err)
var stdout, stdout2 bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"},
Env: standardEnvironment,
Stdin: stdinR,
Stdout: &stdout,
Init: true,
}
err = container.Run(&pconfig)
_ = stdinR.Close()
defer stdinW.Close() //nolint: errcheck
ok(t, err)
pid, err := pconfig.Pid()
ok(t, err)
// Execute another process in the container
stdinR2, stdinW2, err := os.Pipe()
ok(t, err)
pconfig2 := libcontainer.Process{
Cwd: "/",
Env: standardEnvironment,
}
pconfig2.Args = []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"}
pconfig2.Stdin = stdinR2
pconfig2.Stdout = &stdout2
err = container.Run(&pconfig2)
_ = stdinR2.Close()
defer stdinW2.Close() //nolint: errcheck
ok(t, err)
pid2, err := pconfig2.Pid()
ok(t, err)
processes, err := container.Processes()
ok(t, err)
n := 0
for i := range processes {
if processes[i] == pid || processes[i] == pid2 {
n++
}
}
if n != 2 {
t.Fatal("unexpected number of processes", processes, pid, pid2)
}
// Wait processes
_ = stdinW2.Close()
waitProcess(&pconfig2, t)
_ = stdinW.Close()
waitProcess(&pconfig, t)
// Check that both processes live in the same pidns
pidns := stdout.String()
ok(t, err)
pidns2 := stdout2.String()
ok(t, err)
if pidns != pidns2 {
t.Fatal("The second process isn't in the required pid namespace", pidns, pidns2)
}
}
func TestProcessEnv(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "env"},
Env: []string{
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"HOSTNAME=integration",
"TERM=xterm",
"FOO=BAR",
},
Stdin: nil,
Stdout: &stdout,
Init: true,
}
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
outputEnv := stdout.String()
// Check that the environment has the key/value pair we added
if !strings.Contains(outputEnv, "FOO=BAR") {
t.Fatal("Environment doesn't have the expected FOO=BAR key/value pair: ", outputEnv)
}
// Make sure that HOME is set
if !strings.Contains(outputEnv, "HOME=/root") {
t.Fatal("Environment doesn't have HOME set: ", outputEnv)
}
}
func TestProcessEmptyCaps(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
config.Capabilities = nil
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "cat /proc/self/status"},
Env: standardEnvironment,
Stdin: nil,
Stdout: &stdout,
Init: true,
}
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
outputStatus := stdout.String()
lines := strings.Split(outputStatus, "\n")
effectiveCapsLine := ""
for _, l := range lines {
line := strings.TrimSpace(l)
if strings.Contains(line, "CapEff:") {
effectiveCapsLine = line
break
}
}
if effectiveCapsLine == "" {
t.Fatal("Couldn't find effective caps: ", outputStatus)
}
}
func TestProcessCaps(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "cat /proc/self/status"},
Env: standardEnvironment,
Stdin: nil,
Stdout: &stdout,
Capabilities: &configs.Capabilities{},
Init: true,
}
pconfig.Capabilities.Bounding = append(config.Capabilities.Bounding, "CAP_NET_ADMIN")
pconfig.Capabilities.Permitted = append(config.Capabilities.Permitted, "CAP_NET_ADMIN")
pconfig.Capabilities.Effective = append(config.Capabilities.Effective, "CAP_NET_ADMIN")
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
outputStatus := stdout.String()
lines := strings.Split(outputStatus, "\n")
effectiveCapsLine := ""
for _, l := range lines {
line := strings.TrimSpace(l)
if strings.Contains(line, "CapEff:") {
effectiveCapsLine = line
break
}
}
if effectiveCapsLine == "" {
t.Fatal("Couldn't find effective caps: ", outputStatus)
}
parts := strings.Split(effectiveCapsLine, ":")
effectiveCapsStr := strings.TrimSpace(parts[1])
effectiveCaps, err := strconv.ParseUint(effectiveCapsStr, 16, 64)
if err != nil {
t.Fatal("Could not parse effective caps", err)
}
const netAdminMask = 1 << unix.CAP_NET_ADMIN
if effectiveCaps&netAdminMask != netAdminMask {
t.Fatal("CAP_NET_ADMIN is not set as expected")
}
}
func TestAdditionalGroups(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "id", "-Gn"},
Env: standardEnvironment,
Stdin: nil,
Stdout: &stdout,
AdditionalGroups: []string{"plugdev", "audio"},
Init: true,
}
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
outputGroups := stdout.String()
// Check that the groups output has the groups that we specified
if !strings.Contains(outputGroups, "audio") {
t.Fatalf("Listed groups do not contain the audio group as expected: %v", outputGroups)
}
if !strings.Contains(outputGroups, "plugdev") {
t.Fatalf("Listed groups do not contain the plugdev group as expected: %v", outputGroups)
}
}
func TestFreeze(t *testing.T) {
for _, systemd := range []bool{true, false} {
for _, set := range []bool{true, false} {
name := ""
if systemd {
name += "Systemd"
} else {
name += "FS"
}
if set {
name += "ViaSet"
} else {
name += "ViaPauseResume"
}
t.Run(name, func(t *testing.T) {
testFreeze(t, systemd, set)
})
}
}
}
func testFreeze(t *testing.T, withSystemd bool, useSet bool) {
if testing.Short() {
return
}
if withSystemd && !systemd.IsRunningSystemd() {
t.Skip("Test requires systemd.")
}
config := newTemplateConfig(t, &tParam{systemd: withSystemd})
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
stdinR, stdinW, err := os.Pipe()
ok(t, err)
pconfig := &libcontainer.Process{
Cwd: "/",
Args: []string{"cat"},
Env: standardEnvironment,
Stdin: stdinR,
Init: true,
}
err = container.Run(pconfig)
_ = stdinR.Close()
defer stdinW.Close() //nolint: errcheck
ok(t, err)
if !useSet {
err = container.Pause()
} else {
config.Cgroups.Resources.Freezer = cgroups.Frozen
err = container.Set(*config)
}
ok(t, err)
state, err := container.Status()
ok(t, err)
if state != libcontainer.Paused {
t.Fatal("Unexpected state: ", state)
}
if !useSet {
err = container.Resume()
} else {
config.Cgroups.Resources.Freezer = cgroups.Thawed
err = container.Set(*config)
}
ok(t, err)
_ = stdinW.Close()
waitProcess(pconfig, t)
}
func TestCpuShares(t *testing.T) {
testCpuShares(t, false)
}
func TestCpuSharesSystemd(t *testing.T) {
if !systemd.IsRunningSystemd() {
t.Skip("Test requires systemd.")
}
testCpuShares(t, true)
}
func testCpuShares(t *testing.T, systemd bool) {
if testing.Short() {
return
}
if cgroups.IsCgroup2UnifiedMode() {
t.Skip("cgroup v2 does not support CpuShares")
}
config := newTemplateConfig(t, &tParam{systemd: systemd})
config.Cgroups.Resources.CpuShares = 1
if _, _, err := runContainer(t, config, "ps"); err == nil {
t.Fatal("runContainer should fail with invalid CpuShares")
}
}
func TestPids(t *testing.T) {
testPids(t, false)
}
func TestPidsSystemd(t *testing.T) {
if !systemd.IsRunningSystemd() {
t.Skip("Test requires systemd.")
}
testPids(t, true)
}
func testPids(t *testing.T, systemd bool) {
if testing.Short() {
return
}
config := newTemplateConfig(t, &tParam{systemd: systemd})
config.Cgroups.Resources.PidsLimit = -1
// Running multiple processes, expecting it to succeed with no pids limit.
_ = runContainerOk(t, config, "/bin/sh", "-c", "/bin/true | /bin/true | /bin/true | /bin/true")
// Enforce a permissive limit. This needs to be fairly hand-wavey due to the
// issues with running Go binaries with pids restrictions (see below).
config.Cgroups.Resources.PidsLimit = 64
_ = runContainerOk(t, config, "/bin/sh", "-c", `
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true`)
// Enforce a restrictive limit. 64 * /bin/true + 1 * shell should cause
// this to fail reliably.
config.Cgroups.Resources.PidsLimit = 64
out, _, err := runContainer(t, config, "/bin/sh", "-c", `
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true |
/bin/true | /bin/true | /bin/true | /bin/true | /bin/true | /bin/true | bin/true | /bin/true`)
if err != nil && !strings.Contains(out.String(), "sh: can't fork") {
t.Fatal(err)
}
if err == nil {
t.Fatal("expected fork() to fail with restrictive pids limit")
}
// Minimal restrictions are not really supported, due to quirks in using Go
// due to the fact that it spawns random processes. While we do our best with
// late setting cgroup values, it's just too unreliable with very small pids.max.
// As such, we don't test that case. YMMV.
}
func TestCgroupResourcesUnifiedErrorOnV1(t *testing.T) {
testCgroupResourcesUnifiedErrorOnV1(t, false)
}
func TestCgroupResourcesUnifiedErrorOnV1Systemd(t *testing.T) {
if !systemd.IsRunningSystemd() {
t.Skip("Test requires systemd.")
}
testCgroupResourcesUnifiedErrorOnV1(t, true)
}
func testCgroupResourcesUnifiedErrorOnV1(t *testing.T, systemd bool) {
if testing.Short() {
return
}
if cgroups.IsCgroup2UnifiedMode() {
t.Skip("requires cgroup v1")
}
config := newTemplateConfig(t, &tParam{systemd: systemd})
config.Cgroups.Resources.Unified = map[string]string{
"memory.min": "10240",
}
_, _, err := runContainer(t, config, "true")
if !strings.Contains(err.Error(), cgroups.ErrV1NoUnified.Error()) {
t.Fatalf("expected error to contain %v, got %v", cgroups.ErrV1NoUnified, err)
}
}
func TestCgroupResourcesUnified(t *testing.T) {
testCgroupResourcesUnified(t, false)
}
func TestCgroupResourcesUnifiedSystemd(t *testing.T) {
if !systemd.IsRunningSystemd() {
t.Skip("Test requires systemd.")
}
testCgroupResourcesUnified(t, true)
}
func testCgroupResourcesUnified(t *testing.T, systemd bool) {
if testing.Short() {
return
}
if !cgroups.IsCgroup2UnifiedMode() {
t.Skip("requires cgroup v2")
}
config := newTemplateConfig(t, &tParam{systemd: systemd})
config.Cgroups.Resources.Memory = 536870912 // 512M
config.Cgroups.Resources.MemorySwap = 536870912 // 512M, i.e. no swap
config.Namespaces.Add(configs.NEWCGROUP, "")
testCases := []struct {
name string
cfg map[string]string
expError string
cmd []string
exp string
}{
{
name: "dummy",
cmd: []string{"true"},
exp: "",
},
{
name: "set memory.min",
cfg: map[string]string{"memory.min": "131072"},
cmd: []string{"cat", "/sys/fs/cgroup/memory.min"},
exp: "131072\n",
},
{
name: "check memory.max",
cmd: []string{"cat", "/sys/fs/cgroup/memory.max"},
exp: strconv.Itoa(int(config.Cgroups.Resources.Memory)) + "\n",
},
{
name: "overwrite memory.max",
cfg: map[string]string{"memory.max": "268435456"},
cmd: []string{"cat", "/sys/fs/cgroup/memory.max"},
exp: "268435456\n",
},
{
name: "no such controller error",
cfg: map[string]string{"privet.vsem": "vam"},
expError: "controller \"privet\" not available",
},
{
name: "slash in key error",
cfg: map[string]string{"bad/key": "val"},
expError: "must be a file name (no slashes)",
},
{
name: "no dot in key error",
cfg: map[string]string{"badkey": "val"},
expError: "must be in the form CONTROLLER.PARAMETER",
},
{
name: "read-only parameter",
cfg: map[string]string{"pids.current": "42"},
expError: "failed to write",
},
}
for _, tc := range testCases {
config.Cgroups.Resources.Unified = tc.cfg
buffers, ret, err := runContainer(t, config, tc.cmd...)
if tc.expError != "" {
if err == nil {
t.Errorf("case %q failed: expected error, got nil", tc.name)
continue
}
if !strings.Contains(err.Error(), tc.expError) {
t.Errorf("case %q failed: expected error to contain %q, got %q", tc.name, tc.expError, err)
}
continue
}
if err != nil {
t.Errorf("case %q failed: expected no error, got %v (command: %v, status: %d, stderr: %q)",
tc.name, err, tc.cmd, ret, buffers.Stderr.String())
continue
}
if tc.exp != "" {
out := buffers.Stdout.String()
if out != tc.exp {
t.Errorf("expected %q, got %q", tc.exp, out)
}
}
}
}
func TestContainerState(t *testing.T) {
if testing.Short() {
return
}
l, err := os.Readlink("/proc/1/ns/ipc")
ok(t, err)
config := newTemplateConfig(t, nil)
config.Namespaces = configs.Namespaces([]configs.Namespace{
{Type: configs.NEWNS},
{Type: configs.NEWUTS},
// host for IPC
// {Type: configs.NEWIPC},
{Type: configs.NEWPID},
{Type: configs.NEWNET},
})
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
stdinR, stdinW, err := os.Pipe()
ok(t, err)
p := &libcontainer.Process{
Cwd: "/",
Args: []string{"cat"},
Env: standardEnvironment,
Stdin: stdinR,
Init: true,
}
err = container.Run(p)
ok(t, err)
_ = stdinR.Close()
defer stdinW.Close() //nolint: errcheck
st, err := container.State()
ok(t, err)
l1, err := os.Readlink(st.NamespacePaths[configs.NEWIPC])
ok(t, err)
if l1 != l {
t.Fatal("Container using non-host ipc namespace")
}
_ = stdinW.Close()
waitProcess(p, t)
}
func TestPassExtraFiles(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pipeout1, pipein1, err := os.Pipe()
ok(t, err)
pipeout2, pipein2, err := os.Pipe()
ok(t, err)
process := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"},
Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},
ExtraFiles: []*os.File{pipein1, pipein2},
Stdin: nil,
Stdout: &stdout,
Init: true,
}
err = container.Run(&process)
ok(t, err)
waitProcess(&process, t)
out := stdout.String()
// fd 5 is the directory handle for /proc/$$/fd
if out != "0 1 2 3 4 5" {
t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out)
}
buf := []byte{0}
_, err = pipeout1.Read(buf)
ok(t, err)
out1 := string(buf)
if out1 != "1" {
t.Fatalf("expected first pipe to receive '1', got '%s'", out1)
}
_, err = pipeout2.Read(buf)
ok(t, err)
out2 := string(buf)
if out2 != "2" {
t.Fatalf("expected second pipe to receive '2', got '%s'", out2)
}
}
func TestSysctl(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
config.Sysctl = map[string]string{
"kernel.shmmni": "8192",
"kernel/shmmax": "4194304",
}
const (
cmd = "cat shmmni shmmax"
exp = "8192\n4194304\n"
)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/proc/sys/kernel",
Args: []string{"sh", "-c", cmd},
Env: standardEnvironment,
Stdin: nil,
Stdout: &stdout,
Init: true,
}
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
out := stdout.String()
if out != exp {
t.Fatalf("expected %s, got %s", exp, out)
}
}
func TestMountCgroupRO(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
buffers := runContainerOk(t, config, "mount")
mountInfo := buffers.Stdout.String()
lines := strings.Split(mountInfo, "\n")
for _, l := range lines {
if strings.HasPrefix(l, "tmpfs on /sys/fs/cgroup") {
if !strings.Contains(l, "ro") ||
!strings.Contains(l, "nosuid") ||
!strings.Contains(l, "nodev") ||
!strings.Contains(l, "noexec") {
t.Fatalf("Mode expected to contain 'ro,nosuid,nodev,noexec': %s", l)
}
if !strings.Contains(l, "mode=755") {
t.Fatalf("Mode expected to contain 'mode=755': %s", l)
}
continue
}
if !strings.HasPrefix(l, "cgroup") {
continue
}
if !strings.Contains(l, "ro") ||
!strings.Contains(l, "nosuid") ||
!strings.Contains(l, "nodev") ||
!strings.Contains(l, "noexec") {
t.Fatalf("Mode expected to contain 'ro,nosuid,nodev,noexec': %s", l)
}
}
}
func TestMountCgroupRW(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
// clear the RO flag from cgroup mount
for _, m := range config.Mounts {
if m.Device == "cgroup" {
m.Flags = defaultMountFlags
break
}
}
buffers := runContainerOk(t, config, "mount")
mountInfo := buffers.Stdout.String()
lines := strings.Split(mountInfo, "\n")
for _, l := range lines {
if strings.HasPrefix(l, "tmpfs on /sys/fs/cgroup") {
if !strings.Contains(l, "rw") ||
!strings.Contains(l, "nosuid") ||
!strings.Contains(l, "nodev") ||
!strings.Contains(l, "noexec") {
t.Fatalf("Mode expected to contain 'rw,nosuid,nodev,noexec': %s", l)
}
if !strings.Contains(l, "mode=755") {
t.Fatalf("Mode expected to contain 'mode=755': %s", l)
}
continue
}
if !strings.HasPrefix(l, "cgroup") {
continue
}
if !strings.Contains(l, "rw") ||
!strings.Contains(l, "nosuid") ||
!strings.Contains(l, "nodev") ||
!strings.Contains(l, "noexec") {
t.Fatalf("Mode expected to contain 'rw,nosuid,nodev,noexec': %s", l)
}
}
}
func TestOomScoreAdj(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
config.OomScoreAdj = ptrInt(200)
container, err := newContainer(t, config)
ok(t, err)
defer destroyContainer(container)
var stdout bytes.Buffer
pconfig := libcontainer.Process{
Cwd: "/",
Args: []string{"sh", "-c", "cat /proc/self/oom_score_adj"},
Env: standardEnvironment,
Stdin: nil,
Stdout: &stdout,
Init: true,
}
err = container.Run(&pconfig)
ok(t, err)
// Wait for process
waitProcess(&pconfig, t)
outputOomScoreAdj := strings.TrimSpace(stdout.String())
// Check that the oom_score_adj matches the value that was set as part of config.
if outputOomScoreAdj != strconv.Itoa(*config.OomScoreAdj) {
t.Fatalf("Expected oom_score_adj %d; got %q", *config.OomScoreAdj, outputOomScoreAdj)
}
}
func TestHook(t *testing.T) {
if testing.Short() {
return
}
config := newTemplateConfig(t, nil)
expectedBundle := t.TempDir()
config.Labels = append(config.Labels, "bundle="+expectedBundle)
getRootfsFromBundle := func(bundle string) (string, error) {
f, err := os.Open(filepath.Join(bundle, "config.json"))
if err != nil {
return "", err
}
var config configs.Config
if err = json.NewDecoder(f).Decode(&config); err != nil {
return "", err
}
return config.Rootfs, nil
}
createFileFromBundle := func(filename, bundle string) error {
root, err := getRootfsFromBundle(bundle)
if err != nil {
return err
}
f, err := os.Create(filepath.Join(root, filename))
if err != nil {
return err
}
return f.Close()
}
// Note FunctionHooks can't be serialized to json this means they won't be passed down to the container
// For CreateContainer and StartContainer which run in the container namespace, this means we need to pass Command Hooks.
hookFiles := map[configs.HookName]string{
configs.Prestart: "prestart",