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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
|
// Copyright 2018 The gVisor Authors.
//
// 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 container
import (
"fmt"
"io/ioutil"
"math"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/cenkalti/backoff"
specs "github.com/opencontainers/runtime-spec/specs-go"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/cleanup"
"gvisor.dev/gvisor/pkg/sentry/control"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sync"
"gvisor.dev/gvisor/pkg/test/testutil"
"gvisor.dev/gvisor/runsc/boot"
"gvisor.dev/gvisor/runsc/config"
"gvisor.dev/gvisor/runsc/specutils"
)
func createSpecs(cmds ...[]string) ([]*specs.Spec, []string) {
var specs []*specs.Spec
var ids []string
rootID := testutil.RandomContainerID()
for i, cmd := range cmds {
spec := testutil.NewSpecWithArgs(cmd...)
if i == 0 {
spec.Annotations = map[string]string{
specutils.ContainerdContainerTypeAnnotation: specutils.ContainerdContainerTypeSandbox,
}
ids = append(ids, rootID)
} else {
spec.Annotations = map[string]string{
specutils.ContainerdContainerTypeAnnotation: specutils.ContainerdContainerTypeContainer,
specutils.ContainerdSandboxIDAnnotation: rootID,
}
ids = append(ids, testutil.RandomContainerID())
}
specs = append(specs, spec)
}
return specs, ids
}
func startContainers(conf *config.Config, specs []*specs.Spec, ids []string) ([]*Container, func(), error) {
if len(conf.RootDir) == 0 {
panic("conf.RootDir not set. Call testutil.SetupRootDir() to set.")
}
cu := cleanup.Cleanup{}
defer cu.Clean()
var containers []*Container
for i, spec := range specs {
bundleDir, cleanup, err := testutil.SetupBundleDir(spec)
if err != nil {
return nil, nil, fmt.Errorf("error setting up container: %v", err)
}
cu.Add(cleanup)
args := Args{
ID: ids[i],
Spec: spec,
BundleDir: bundleDir,
}
cont, err := New(conf, args)
if err != nil {
return nil, nil, fmt.Errorf("error creating container: %v", err)
}
cu.Add(func() { cont.Destroy() })
containers = append(containers, cont)
if err := cont.Start(conf); err != nil {
return nil, nil, fmt.Errorf("error starting container: %v", err)
}
}
return containers, cu.Release(), nil
}
type execDesc struct {
c *Container
cmd []string
want int
name string
}
func execMany(t *testing.T, conf *config.Config, execs []execDesc) {
for _, exec := range execs {
t.Run(exec.name, func(t *testing.T) {
args := &control.ExecArgs{Argv: exec.cmd}
if ws, err := exec.c.executeSync(conf, args); err != nil {
t.Errorf("error executing %+v: %v", args, err)
} else if ws.ExitStatus() != exec.want {
t.Errorf("%q: exec %q got exit status: %d, want: %d", exec.name, exec.cmd, ws.ExitStatus(), exec.want)
}
})
}
}
func createSharedMount(mount specs.Mount, name string, pod ...*specs.Spec) {
for _, spec := range pod {
spec.Annotations[boot.MountPrefix+name+".source"] = mount.Source
spec.Annotations[boot.MountPrefix+name+".type"] = mount.Type
spec.Annotations[boot.MountPrefix+name+".share"] = "pod"
if len(mount.Options) > 0 {
spec.Annotations[boot.MountPrefix+name+".options"] = strings.Join(mount.Options, ",")
}
}
}
// TestMultiContainerSanity checks that it is possible to run 2 dead-simple
// containers in the same sandbox.
func TestMultiContainerSanity(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
specs, ids := createSpecs(sleep, sleep)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check via ps that multiple processes are running.
expectedPL := []*control.Process{
newProcessBuilder().PID(1).PPID(0).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
expectedPL = []*control.Process{
newProcessBuilder().PID(2).PPID(0).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
})
}
}
// TestMultiPIDNS checks that it is possible to run 2 dead-simple containers in
// the same sandbox with different pidns.
func TestMultiPIDNS(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
testSpecs, ids := createSpecs(sleep, sleep)
testSpecs[1].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{
{
Type: "pid",
},
},
}
containers, cleanup, err := startContainers(conf, testSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check via ps that multiple processes are running.
expectedPL := []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
expectedPL = []*control.Process{
newProcessBuilder().PID(2).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Root container runs in the root PID namespace and can see all
// processes.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
newProcessBuilder().PID(2).Cmd("sleep").Process(),
newProcessBuilder().Cmd("ps").Process(),
}
got, err := execPS(conf, containers[0])
if err != nil {
t.Fatal(err)
}
if !procListsEqual(got, expectedPL) {
t.Errorf("container got process list: %s, want: %s", procListToString(got), procListToString(expectedPL))
}
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
newProcessBuilder().Cmd("ps").Process(),
}
got, err = execPS(conf, containers[1])
if err != nil {
t.Fatal(err)
}
if !procListsEqual(got, expectedPL) {
t.Errorf("container got process list: %s, want: %s", procListToString(got), procListToString(expectedPL))
}
})
}
}
// TestMultiPIDNSPath checks the pidns path.
func TestMultiPIDNSPath(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
testSpecs, ids := createSpecs(sleep, sleep, sleep)
testSpecs[0].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{
{
Type: "pid",
Path: "/proc/1/ns/pid",
},
},
}
testSpecs[1].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{
{
Type: "pid",
Path: "/proc/1/ns/pid",
},
},
}
testSpecs[2].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{
{
Type: "pid",
Path: "/proc/2/ns/pid",
},
},
}
containers, cleanup, err := startContainers(conf, testSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check via ps that multiple processes are running.
expectedPL := []*control.Process{
newProcessBuilder().PID(1).PPID(0).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
expectedPL = []*control.Process{
newProcessBuilder().PID(2).PPID(0).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
expectedPL = []*control.Process{
newProcessBuilder().PID(3).PPID(0).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[2], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Root container runs in the root PID namespace and can see all
// processes.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
newProcessBuilder().PID(2).Cmd("sleep").Process(),
newProcessBuilder().PID(3).Cmd("sleep").Process(),
newProcessBuilder().Cmd("ps").Process(),
}
got, err := execPS(conf, containers[0])
if err != nil {
t.Fatal(err)
}
if !procListsEqual(got, expectedPL) {
t.Errorf("container got process list: %s, want: %s", procListToString(got), procListToString(expectedPL))
}
// Container 1 runs in the same PID namespace as the root container.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
newProcessBuilder().PID(2).Cmd("sleep").Process(),
newProcessBuilder().PID(3).Cmd("sleep").Process(),
newProcessBuilder().Cmd("ps").Process(),
}
got, err = execPS(conf, containers[1])
if err != nil {
t.Fatal(err)
}
if !procListsEqual(got, expectedPL) {
t.Errorf("container got process list: %s, want: %s", procListToString(got), procListToString(expectedPL))
}
// Container 2 runs on its own namespace.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
newProcessBuilder().Cmd("ps").Process(),
}
got, err = execPS(conf, containers[2])
if err != nil {
t.Fatal(err)
}
if !procListsEqual(got, expectedPL) {
t.Errorf("container got process list: %s, want: %s", procListToString(got), procListToString(expectedPL))
}
})
}
}
// TestMultiPIDNSKill kills processes using PID when containers are using
// different PID namespaces to ensure PID is taken from the root namespace.
func TestMultiPIDNSKill(t *testing.T) {
app, err := testutil.FindFile("test/cmd/test_app/test_app")
if err != nil {
t.Fatal("error finding test_app:", err)
}
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
cmd := []string{app, "task-tree", "--depth=1", "--width=2", "--pause=true"}
const processes = 3
testSpecs, ids := createSpecs(cmd, cmd)
testSpecs[1].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{
{
Type: "pid",
},
},
}
containers, cleanup, err := startContainers(conf, testSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Wait until all processes are created.
for _, c := range containers {
if err := waitForProcessCount(c, processes); err != nil {
t.Fatalf("error waitting for processes: %v", err)
}
}
for i, c := range containers {
// First, kill a process that belongs to the container.
procs, err := c.Processes()
if err != nil {
t.Fatalf("container.Processes(): %v", err)
}
t.Logf("Container %q procs: %s", c.ID, procListToString(procs))
pidToKill := procs[processes-1].PID
t.Logf("PID to kill: %d", pidToKill)
if err := c.SignalProcess(unix.SIGKILL, int32(pidToKill)); err != nil {
t.Errorf("container.SignalProcess: %v", err)
}
// Wait for the process to get killed.
if err := waitForProcessCount(c, processes-1); err != nil {
t.Fatalf("error waitting for processes: %v", err)
}
procs, err = c.Processes()
if err != nil {
t.Fatalf("container.Processes(): %v", err)
}
t.Logf("Container %q procs after kill: %s", c.ID, procListToString(procs))
for _, proc := range procs {
if proc.PID == pidToKill {
t.Errorf("process %d not killed: %+v", pidToKill, proc)
}
}
// Next, attempt to kill a process from another container and check that
// it fails.
other := containers[(i+1)%len(containers)]
procs, err = other.Processes()
if err != nil {
t.Fatalf("container.Processes(): %v", err)
}
t.Logf("Other container %q procs: %s", other.ID, procListToString(procs))
pidToKill = procs[len(procs)-1].PID
t.Logf("PID that should not be killed: %d", pidToKill)
err = c.SignalProcess(unix.SIGKILL, int32(pidToKill))
if err == nil {
t.Fatalf("killing another container's process should fail")
}
if !strings.Contains(err.Error(), "belongs to a different container") {
t.Errorf("wrong error message from killing another container's: %v", err)
}
}
})
}
}
func TestMultiContainerWait(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// The first container should run the entire duration of the test.
cmd1 := []string{"sleep", "100"}
// We'll wait on the second container, which is much shorter lived.
cmd2 := []string{"sleep", "1"}
specs, ids := createSpecs(cmd1, cmd2)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check that we can wait for the sub-container.
c := containers[1]
if ws, err := c.Wait(); err != nil {
t.Errorf("failed to wait for process %s: %v", c.Spec.Process.Args, err)
} else if es := ws.ExitStatus(); es != 0 {
t.Errorf("process %s exited with non-zero status %d", c.Spec.Process.Args, es)
}
if _, err := c.Wait(); err != nil {
t.Errorf("wait for stopped container %s shouldn't fail: %v", c.Spec.Process.Args, err)
}
// After Wait returns, ensure that the root container is running and
// the child has finished.
expectedPL := []*control.Process{
newProcessBuilder().Cmd("sleep").PID(1).Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for %q to start: %v", strings.Join(containers[0].Spec.Process.Args, " "), err)
}
}
// TestExecWait ensures what we can wait on containers and individual processes
// in the sandbox that have already exited.
func TestExecWait(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// The first container should run the entire duration of the test.
cmd1 := []string{"sleep", "100"}
// We'll wait on the second container, which is much shorter lived.
cmd2 := []string{"sleep", "1"}
specs, ids := createSpecs(cmd1, cmd2)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check via ps that process is running.
expectedPL := []*control.Process{
newProcessBuilder().Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Fatalf("failed to wait for sleep to start: %v", err)
}
// Wait for the second container to finish.
if err := waitForProcessCount(containers[1], 0); err != nil {
t.Fatalf("failed to wait for second container to stop: %v", err)
}
// Get the second container exit status.
if ws, err := containers[1].Wait(); err != nil {
t.Fatalf("failed to wait for process %s: %v", containers[1].Spec.Process.Args, err)
} else if es := ws.ExitStatus(); es != 0 {
t.Fatalf("process %s exited with non-zero status %d", containers[1].Spec.Process.Args, es)
}
if _, err := containers[1].Wait(); err != nil {
t.Fatalf("wait for stopped container %s shouldn't fail: %v", containers[1].Spec.Process.Args, err)
}
// Execute another process in the first container.
args := &control.ExecArgs{
Filename: "/bin/sleep",
Argv: []string{"/bin/sleep", "1"},
WorkingDirectory: "/",
KUID: 0,
}
pid, err := containers[0].Execute(conf, args)
if err != nil {
t.Fatalf("error executing: %v", err)
}
// Wait for the exec'd process to exit.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Fatalf("failed to wait for second container to stop: %v", err)
}
// Get the exit status from the exec'd process.
if ws, err := containers[0].WaitPID(pid); err != nil {
t.Fatalf("failed to wait for process %+v with pid %d: %v", args, pid, err)
} else if es := ws.ExitStatus(); es != 0 {
t.Fatalf("process %+v exited with non-zero status %d", args, es)
}
if _, err := containers[0].WaitPID(pid); err == nil {
t.Fatalf("wait for stopped process %+v should fail", args)
}
}
// TestMultiContainerMount tests that bind mounts can be used with multiple
// containers.
func TestMultiContainerMount(t *testing.T) {
cmd1 := []string{"sleep", "100"}
// 'src != dst' ensures that 'dst' doesn't exist in the host and must be
// properly mapped inside the container to work.
src, err := ioutil.TempDir(testutil.TmpDir(), "container")
if err != nil {
t.Fatal("ioutil.TempDir failed:", err)
}
dst := src + ".dst"
cmd2 := []string{"touch", filepath.Join(dst, "file")}
sps, ids := createSpecs(cmd1, cmd2)
sps[1].Mounts = append(sps[1].Mounts, specs.Mount{
Source: src,
Destination: dst,
Type: "bind",
})
// Setup the containers.
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
containers, cleanup, err := startContainers(conf, sps, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
ws, err := containers[1].Wait()
if err != nil {
t.Error("error waiting on container:", err)
}
if !ws.Exited() || ws.ExitStatus() != 0 {
t.Error("container failed, waitStatus:", ws)
}
}
// TestMultiContainerSignal checks that it is possible to signal individual
// containers without killing the entire sandbox.
func TestMultiContainerSignal(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
specs, ids := createSpecs(sleep, sleep)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check via ps that container 1 process is running.
expectedPL := []*control.Process{
newProcessBuilder().Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Kill process 2.
if err := containers[1].SignalContainer(unix.SIGKILL, false); err != nil {
t.Errorf("failed to kill process 2: %v", err)
}
// Make sure process 1 is still running.
expectedPL = []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// goferPid is reset when container is destroyed.
goferPid := containers[1].GoferPid
// Destroy container and ensure container's gofer process has exited.
if err := containers[1].Destroy(); err != nil {
t.Errorf("failed to destroy container: %v", err)
}
_, _, err = specutils.RetryEintr(func() (uintptr, uintptr, error) {
cpid, err := unix.Wait4(goferPid, nil, 0, nil)
return uintptr(cpid), 0, err
})
if err != unix.ECHILD {
t.Errorf("error waiting for gofer to exit: %v", err)
}
// Make sure process 1 is still running.
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Now that process 2 is gone, ensure we get an error trying to
// signal it again.
if err := containers[1].SignalContainer(unix.SIGKILL, false); err == nil {
t.Errorf("container %q shouldn't exist, but we were able to signal it", containers[1].ID)
}
// Kill process 1.
if err := containers[0].SignalContainer(unix.SIGKILL, false); err != nil {
t.Errorf("failed to kill process 1: %v", err)
}
// Ensure that container's gofer and sandbox process are no more.
err = blockUntilWaitable(containers[0].GoferPid)
if err != nil && err != unix.ECHILD {
t.Errorf("error waiting for gofer to exit: %v", err)
}
err = blockUntilWaitable(containers[0].Sandbox.Pid)
if err != nil && err != unix.ECHILD {
t.Errorf("error waiting for sandbox to exit: %v", err)
}
// The sentry should be gone, so signaling should yield an error.
if err := containers[0].SignalContainer(unix.SIGKILL, false); err == nil {
t.Errorf("sandbox %q shouldn't exist, but we were able to signal it", containers[0].Sandbox.ID)
}
if err := containers[0].Destroy(); err != nil {
t.Errorf("failed to destroy container: %v", err)
}
})
}
}
// TestMultiContainerDestroy checks that container are properly cleaned-up when
// they are destroyed.
func TestMultiContainerDestroy(t *testing.T) {
app, err := testutil.FindFile("test/cmd/test_app/test_app")
if err != nil {
t.Fatal("error finding test_app:", err)
}
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// First container will remain intact while the second container is killed.
podSpecs, ids := createSpecs(
[]string{"sleep", "100"},
[]string{app, "fork-bomb"})
// Run the fork bomb in a PID namespace to prevent processes to be
// re-parented to PID=1 in the root container.
podSpecs[1].Linux = &specs.Linux{
Namespaces: []specs.LinuxNamespace{{Type: "pid"}},
}
containers, cleanup, err := startContainers(conf, podSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Exec more processes to ensure signal all works for exec'd processes too.
args := &control.ExecArgs{
Filename: app,
Argv: []string{app, "fork-bomb"},
}
if _, err := containers[1].Execute(conf, args); err != nil {
t.Fatalf("error exec'ing: %v", err)
}
// Let it brew...
time.Sleep(500 * time.Millisecond)
if err := containers[1].Destroy(); err != nil {
t.Fatalf("error destroying container: %v", err)
}
// Check that destroy killed all processes belonging to the container and
// waited for them to exit before returning.
pss, err := containers[0].Sandbox.Processes("")
if err != nil {
t.Fatalf("error getting process data from sandbox: %v", err)
}
expectedPL := []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
}
if !procListsEqual(pss, expectedPL) {
t.Errorf("container got process list: %s, want: %s: error: %v",
procListToString(pss), procListToString(expectedPL), err)
}
// Check that cont.Destroy is safe to call multiple times.
if err := containers[1].Destroy(); err != nil {
t.Errorf("error destroying container: %v", err)
}
})
}
}
func TestMultiContainerProcesses(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// Note: use curly braces to keep 'sh' process around. Otherwise, shell
// will just execve into 'sleep' and both containers will look the
// same.
specs, ids := createSpecs(
[]string{"sleep", "100"},
[]string{"sh", "-c", "{ sleep 100; }"})
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Check root's container process list doesn't include other containers.
expectedPL0 := []*control.Process{
newProcessBuilder().PID(1).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL0); err != nil {
t.Errorf("failed to wait for process to start: %v", err)
}
// Same for the other container.
expectedPL1 := []*control.Process{
newProcessBuilder().PID(2).Cmd("sh").Process(),
newProcessBuilder().PID(3).PPID(2).Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[1], expectedPL1); err != nil {
t.Errorf("failed to wait for process to start: %v", err)
}
// Now exec into the second container and verify it shows up in the container.
args := &control.ExecArgs{
Filename: "/bin/sleep",
Argv: []string{"/bin/sleep", "100"},
}
if _, err := containers[1].Execute(conf, args); err != nil {
t.Fatalf("error exec'ing: %v", err)
}
expectedPL1 = append(expectedPL1, newProcessBuilder().PID(4).Cmd("sleep").Process())
if err := waitForProcessList(containers[1], expectedPL1); err != nil {
t.Errorf("failed to wait for process to start: %v", err)
}
// Root container should remain unchanged.
if err := waitForProcessList(containers[0], expectedPL0); err != nil {
t.Errorf("failed to wait for process to start: %v", err)
}
}
// TestMultiContainerKillAll checks that all process that belong to a container
// are killed when SIGKILL is sent to *all* processes in that container.
func TestMultiContainerKillAll(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
for _, tc := range []struct {
killContainer bool
}{
{killContainer: true},
{killContainer: false},
} {
app, err := testutil.FindFile("test/cmd/test_app/test_app")
if err != nil {
t.Fatal("error finding test_app:", err)
}
// First container will remain intact while the second container is killed.
specs, ids := createSpecs(
[]string{app, "task-tree", "--depth=2", "--width=2"},
[]string{app, "task-tree", "--depth=4", "--width=2"})
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Wait until all processes are created.
rootProcCount := int(math.Pow(2, 3) - 1)
if err := waitForProcessCount(containers[0], rootProcCount); err != nil {
t.Fatalf("error waitting for processes: %v", err)
}
procCount := int(math.Pow(2, 5) - 1)
if err := waitForProcessCount(containers[1], procCount); err != nil {
t.Fatalf("error waiting for processes: %v", err)
}
// Exec more processes to ensure signal works for exec'd processes too.
args := &control.ExecArgs{
Filename: app,
Argv: []string{app, "task-tree", "--depth=2", "--width=2"},
}
if _, err := containers[1].Execute(conf, args); err != nil {
t.Fatalf("error exec'ing: %v", err)
}
// Wait for these new processes to start.
procCount += int(math.Pow(2, 3) - 1)
if err := waitForProcessCount(containers[1], procCount); err != nil {
t.Fatalf("error waiting for processes: %v", err)
}
if tc.killContainer {
// First kill the init process to make the container be stopped with
// processes still running inside.
if err := containers[1].SignalContainer(unix.SIGKILL, false); err != nil {
t.Fatalf("SignalContainer(): %v", err)
}
op := func() error {
c, err := Load(conf.RootDir, FullID{ContainerID: ids[1]}, LoadOpts{})
if err != nil {
return err
}
if c.Status != Stopped {
return fmt.Errorf("container is not stopped")
}
return nil
}
if err := testutil.Poll(op, 5*time.Second); err != nil {
t.Fatalf("container did not stop %q: %v", containers[1].ID, err)
}
}
c, err := Load(conf.RootDir, FullID{ContainerID: ids[1]}, LoadOpts{})
if err != nil {
t.Fatalf("failed to load child container %q: %v", ids[1], err)
}
// Kill'Em All
if err := c.SignalContainer(unix.SIGKILL, true); err != nil {
t.Fatalf("failed to send SIGKILL to container %q: %v", c.ID, err)
}
// Check that all processes are gone.
if err := waitForProcessCount(containers[1], 0); err != nil {
t.Fatalf("error waiting for processes: %v", err)
}
// Check that root container was not affected.
if err := waitForProcessCount(containers[0], rootProcCount); err != nil {
t.Fatalf("error waiting for processes: %v", err)
}
}
}
func TestMultiContainerDestroyNotStarted(t *testing.T) {
specs, ids := createSpecs(
[]string{"/bin/sleep", "100"},
[]string{"/bin/sleep", "100"})
conf := testutil.TestConfig(t)
_, bundleDir, cleanup, err := testutil.SetupContainer(specs[0], conf)
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanup()
rootArgs := Args{
ID: ids[0],
Spec: specs[0],
BundleDir: bundleDir,
}
root, err := New(conf, rootArgs)
if err != nil {
t.Fatalf("error creating root container: %v", err)
}
defer root.Destroy()
if err := root.Start(conf); err != nil {
t.Fatalf("error starting root container: %v", err)
}
// Create and destroy sub-container.
bundleDir, cleanupSub, err := testutil.SetupBundleDir(specs[1])
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanupSub()
args := Args{
ID: ids[1],
Spec: specs[1],
BundleDir: bundleDir,
}
cont, err := New(conf, args)
if err != nil {
t.Fatalf("error creating container: %v", err)
}
// Check that container can be destroyed.
if err := cont.Destroy(); err != nil {
t.Fatalf("deleting non-started container failed: %v", err)
}
}
// TestMultiContainerDestroyStarting attempts to force a race between start
// and destroy.
func TestMultiContainerDestroyStarting(t *testing.T) {
cmds := make([][]string, 10)
for i := range cmds {
cmds[i] = []string{"/bin/sleep", "100"}
}
specs, ids := createSpecs(cmds...)
conf := testutil.TestConfig(t)
rootDir, bundleDir, cleanup, err := testutil.SetupContainer(specs[0], conf)
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanup()
rootArgs := Args{
ID: ids[0],
Spec: specs[0],
BundleDir: bundleDir,
}
root, err := New(conf, rootArgs)
if err != nil {
t.Fatalf("error creating root container: %v", err)
}
defer root.Destroy()
if err := root.Start(conf); err != nil {
t.Fatalf("error starting root container: %v", err)
}
wg := sync.WaitGroup{}
for i := range cmds {
if i == 0 {
continue // skip root container
}
bundleDir, cleanup, err := testutil.SetupBundleDir(specs[i])
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanup()
rootArgs := Args{
ID: ids[i],
Spec: specs[i],
BundleDir: bundleDir,
}
cont, err := New(conf, rootArgs)
if err != nil {
t.Fatalf("error creating container: %v", err)
}
// Container is not thread safe, so load another instance to run in
// concurrently.
startCont, err := Load(rootDir, FullID{ContainerID: ids[i]}, LoadOpts{})
if err != nil {
t.Fatalf("error loading container: %v", err)
}
wg.Add(1)
go func() {
defer wg.Done()
// Ignore failures, start can fail if destroy runs first.
_ = startCont.Start(conf)
}()
wg.Add(1)
go func() {
defer wg.Done()
if err := cont.Destroy(); err != nil {
t.Errorf("deleting non-started container failed: %v", err)
}
}()
}
wg.Wait()
}
// TestMultiContainerDifferentFilesystems tests that different containers have
// different root filesystems.
func TestMultiContainerDifferentFilesystems(t *testing.T) {
filename := "/foo"
// Root container will create file and then sleep.
cmdRoot := []string{"sh", "-c", fmt.Sprintf("touch %q && sleep 100", filename)}
// Child containers will assert that the file does not exist, and will
// then create it.
script := fmt.Sprintf("if [ -f %q ]; then exit 1; else touch %q; fi", filename, filename)
cmd := []string{"sh", "-c", script}
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// Make sure overlay is enabled, and none of the root filesystems are
// read-only, otherwise we won't be able to create the file.
conf.Overlay = true
specs, ids := createSpecs(cmdRoot, cmd, cmd)
for _, s := range specs {
s.Root.Readonly = false
}
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Both child containers should exit successfully.
for i, c := range containers {
if i == 0 {
// Don't wait on the root.
continue
}
if ws, err := c.Wait(); err != nil {
t.Errorf("failed to wait for process %s: %v", c.Spec.Process.Args, err)
} else if es := ws.ExitStatus(); es != 0 {
t.Errorf("process %s exited with non-zero status %d", c.Spec.Process.Args, es)
}
}
}
// TestMultiContainerContainerDestroyStress tests that IO operations continue
// to work after containers have been stopped and gofers killed.
func TestMultiContainerContainerDestroyStress(t *testing.T) {
app, err := testutil.FindFile("test/cmd/test_app/test_app")
if err != nil {
t.Fatal("error finding test_app:", err)
}
// Setup containers. Root container just reaps children, while the others
// perform some IOs. Children are executed in 3 batches of 10. Within the
// batch there is overlap between containers starting and being destroyed. In
// between batches all containers stop before starting another batch.
cmds := [][]string{{app, "reaper"}}
const batchSize = 10
for i := 0; i < 3*batchSize; i++ {
dir, err := ioutil.TempDir(testutil.TmpDir(), "gofer-stop-test")
if err != nil {
t.Fatal("ioutil.TempDir failed:", err)
}
defer os.RemoveAll(dir)
cmd := "find /bin -type f | head | xargs -I SRC cp SRC " + dir
cmds = append(cmds, []string{"sh", "-c", cmd})
}
allSpecs, allIDs := createSpecs(cmds...)
// Split up the specs and IDs.
rootSpec := allSpecs[0]
rootID := allIDs[0]
childrenSpecs := allSpecs[1:]
childrenIDs := allIDs[1:]
conf := testutil.TestConfig(t)
_, bundleDir, cleanup, err := testutil.SetupContainer(rootSpec, conf)
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanup()
// Start root container.
rootArgs := Args{
ID: rootID,
Spec: rootSpec,
BundleDir: bundleDir,
}
root, err := New(conf, rootArgs)
if err != nil {
t.Fatalf("error creating root container: %v", err)
}
if err := root.Start(conf); err != nil {
t.Fatalf("error starting root container: %v", err)
}
defer root.Destroy()
// Run batches. Each batch starts containers in parallel, then wait and
// destroy them before starting another batch.
for i := 0; i < len(childrenSpecs); i += batchSize {
t.Logf("Starting batch from %d to %d", i, i+batchSize)
specs := childrenSpecs[i : i+batchSize]
ids := childrenIDs[i : i+batchSize]
var children []*Container
for j, spec := range specs {
bundleDir, cleanup, err := testutil.SetupBundleDir(spec)
if err != nil {
t.Fatalf("error setting up container: %v", err)
}
defer cleanup()
args := Args{
ID: ids[j],
Spec: spec,
BundleDir: bundleDir,
}
child, err := New(conf, args)
if err != nil {
t.Fatalf("error creating container: %v", err)
}
children = append(children, child)
if err := child.Start(conf); err != nil {
t.Fatalf("error starting container: %v", err)
}
// Give a small gap between containers.
time.Sleep(50 * time.Millisecond)
}
for _, child := range children {
ws, err := child.Wait()
if err != nil {
t.Fatalf("waiting for container: %v", err)
}
if !ws.Exited() || ws.ExitStatus() != 0 {
t.Fatalf("container failed, waitStatus: %x (%d)", ws, ws.ExitStatus())
}
if err := child.Destroy(); err != nil {
t.Fatalf("error destroying container: %v", err)
}
}
}
}
// Test that pod shared mounts are properly mounted in 2 containers and that
// changes from one container is reflected in the other.
func TestMultiContainerSharedMount(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
podSpec, ids := createSpecs(sleep, sleep)
mnt0 := specs.Mount{
Destination: "/mydir/test",
Source: "/some/dir",
Type: "tmpfs",
Options: nil,
}
podSpec[0].Mounts = append(podSpec[0].Mounts, mnt0)
mnt1 := mnt0
mnt1.Destination = "/mydir2/test2"
podSpec[1].Mounts = append(podSpec[1].Mounts, mnt1)
createSharedMount(mnt0, "test-mount", podSpec...)
containers, cleanup, err := startContainers(conf, podSpec, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
file0 := path.Join(mnt0.Destination, "abc")
file1 := path.Join(mnt1.Destination, "abc")
execs := []execDesc{
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-d", mnt0.Destination},
name: "directory is mounted in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-d", mnt1.Destination},
name: "directory is mounted in container1",
},
{
c: containers[0],
cmd: []string{"/bin/touch", file0},
name: "create file in container0",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-f", file0},
name: "file appears in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-f", file1},
name: "file appears in container1",
},
{
c: containers[1],
cmd: []string{"/bin/rm", file1},
name: "remove file from container1",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "!", "-f", file0},
name: "file removed from container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "!", "-f", file1},
name: "file removed from container1",
},
{
c: containers[1],
cmd: []string{"/bin/mkdir", file1},
name: "create directory in container1",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-d", file0},
name: "dir appears in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-d", file1},
name: "dir appears in container1",
},
{
c: containers[0],
cmd: []string{"/bin/rmdir", file0},
name: "remove directory from container0",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "!", "-d", file0},
name: "dir removed from container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "!", "-d", file1},
name: "dir removed from container1",
},
}
execMany(t, conf, execs)
})
}
}
// Test that pod mounts are mounted as readonly when requested.
func TestMultiContainerSharedMountReadonly(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
podSpec, ids := createSpecs(sleep, sleep)
mnt0 := specs.Mount{
Destination: "/mydir/test",
Source: "/some/dir",
Type: "tmpfs",
Options: []string{"ro"},
}
podSpec[0].Mounts = append(podSpec[0].Mounts, mnt0)
mnt1 := mnt0
mnt1.Destination = "/mydir2/test2"
podSpec[1].Mounts = append(podSpec[1].Mounts, mnt1)
createSharedMount(mnt0, "test-mount", podSpec...)
containers, cleanup, err := startContainers(conf, podSpec, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
file0 := path.Join(mnt0.Destination, "abc")
file1 := path.Join(mnt1.Destination, "abc")
execs := []execDesc{
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-d", mnt0.Destination},
name: "directory is mounted in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-d", mnt1.Destination},
name: "directory is mounted in container1",
},
{
c: containers[0],
cmd: []string{"/bin/touch", file0},
want: 1,
name: "fails to write to container0",
},
{
c: containers[1],
cmd: []string{"/bin/touch", file1},
want: 1,
name: "fails to write to container1",
},
}
execMany(t, conf, execs)
})
}
}
// Test that shared pod mounts continue to work after container is restarted.
func TestMultiContainerSharedMountRestart(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"sleep", "100"}
podSpec, ids := createSpecs(sleep, sleep)
mnt0 := specs.Mount{
Destination: "/mydir/test",
Source: "/some/dir",
Type: "tmpfs",
Options: nil,
}
podSpec[0].Mounts = append(podSpec[0].Mounts, mnt0)
mnt1 := mnt0
mnt1.Destination = "/mydir2/test2"
podSpec[1].Mounts = append(podSpec[1].Mounts, mnt1)
createSharedMount(mnt0, "test-mount", podSpec...)
containers, cleanup, err := startContainers(conf, podSpec, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
file0 := path.Join(mnt0.Destination, "abc")
file1 := path.Join(mnt1.Destination, "abc")
execs := []execDesc{
{
c: containers[0],
cmd: []string{"/bin/touch", file0},
name: "create file in container0",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-f", file0},
name: "file appears in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-f", file1},
name: "file appears in container1",
},
}
execMany(t, conf, execs)
containers[1].Destroy()
bundleDir, cleanup, err := testutil.SetupBundleDir(podSpec[1])
if err != nil {
t.Fatalf("error restarting container: %v", err)
}
defer cleanup()
args := Args{
ID: ids[1],
Spec: podSpec[1],
BundleDir: bundleDir,
}
containers[1], err = New(conf, args)
if err != nil {
t.Fatalf("error creating container: %v", err)
}
if err := containers[1].Start(conf); err != nil {
t.Fatalf("error starting container: %v", err)
}
execs = []execDesc{
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-f", file0},
name: "file is still in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-f", file1},
name: "file is still in container1",
},
{
c: containers[1],
cmd: []string{"/bin/rm", file1},
name: "file removed from container1",
},
{
c: containers[0],
cmd: []string{"/usr/bin/test", "!", "-f", file0},
name: "file removed from container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "!", "-f", file1},
name: "file removed from container1",
},
}
execMany(t, conf, execs)
})
}
}
// Test that unsupported pod mounts options are ignored when matching master and
// replica mounts.
func TestMultiContainerSharedMountUnsupportedOptions(t *testing.T) {
for name, conf := range configs(t, all...) {
t.Run(name, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"/bin/sleep", "100"}
podSpec, ids := createSpecs(sleep, sleep)
mnt0 := specs.Mount{
Destination: "/mydir/test",
Source: "/some/dir",
Type: "tmpfs",
Options: []string{"rw", "relatime"},
}
podSpec[0].Mounts = append(podSpec[0].Mounts, mnt0)
mnt1 := mnt0
mnt1.Destination = "/mydir2/test2"
mnt1.Options = []string{"rw", "nosuid"}
podSpec[1].Mounts = append(podSpec[1].Mounts, mnt1)
createSharedMount(mnt0, "test-mount", podSpec...)
containers, cleanup, err := startContainers(conf, podSpec, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
execs := []execDesc{
{
c: containers[0],
cmd: []string{"/usr/bin/test", "-d", mnt0.Destination},
name: "directory is mounted in container0",
},
{
c: containers[1],
cmd: []string{"/usr/bin/test", "-d", mnt1.Destination},
name: "directory is mounted in container1",
},
}
execMany(t, conf, execs)
})
}
}
// Test that one container can send an FD to another container, even though
// they have distinct MountNamespaces.
func TestMultiContainerMultiRootCanHandleFDs(t *testing.T) {
app, err := testutil.FindFile("test/cmd/test_app/test_app")
if err != nil {
t.Fatal("error finding test_app:", err)
}
// We set up two containers with one shared mount that is used for a
// shared socket. The first container will send an FD over the socket
// to the second container. The FD corresponds to a file in the first
// container's mount namespace that is not part of the second
// container's mount namespace. However, the second container still
// should be able to read the FD.
// Create a shared mount where we will put the socket.
sharedMnt := specs.Mount{
Destination: "/mydir/test",
Type: "tmpfs",
// Shared mounts need a Source, even for tmpfs. It is only used
// to match up different shared mounts inside the pod.
Source: "/some/dir",
}
socketPath := filepath.Join(sharedMnt.Destination, "socket")
// Create a writeable tmpfs mount where the FD sender app will create
// files to send. This will only be mounted in the FD sender.
writeableMnt := specs.Mount{
Destination: "/tmp",
Type: "tmpfs",
}
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// Create the specs.
specs, ids := createSpecs(
[]string{"sleep", "1000"},
[]string{app, "fd_sender", "--socket", socketPath},
[]string{app, "fd_receiver", "--socket", socketPath},
)
createSharedMount(sharedMnt, "shared-mount", specs...)
specs[1].Mounts = append(specs[2].Mounts, sharedMnt, writeableMnt)
specs[2].Mounts = append(specs[1].Mounts, sharedMnt)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Both containers should exit successfully.
for _, c := range containers[1:] {
if ws, err := c.Wait(); err != nil {
t.Errorf("failed to wait for process %s: %v", c.Spec.Process.Args, err)
} else if es := ws.ExitStatus(); es != 0 {
t.Errorf("process %s exited with non-zero status %d", c.Spec.Process.Args, es)
}
}
}
// Test that container is destroyed when Gofer is killed.
func TestMultiContainerGoferKilled(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.VFS2 = true
conf.RootDir = rootDir
sleep := []string{"sleep", "100"}
specs, ids := createSpecs(sleep, sleep, sleep)
containers, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Ensure container is running
c := containers[2]
expectedPL := []*control.Process{
newProcessBuilder().PID(3).Cmd("sleep").Process(),
}
if err := waitForProcessList(c, expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Kill container's gofer.
if err := unix.Kill(c.GoferPid, unix.SIGKILL); err != nil {
t.Fatalf("unix.Kill(%d, SIGKILL)=%v", c.GoferPid, err)
}
// Wait until container stops.
if err := waitForProcessList(c, nil); err != nil {
t.Errorf("Container %q was not stopped after gofer death: %v", c.ID, err)
}
// Check that container isn't running anymore.
if _, err := execute(conf, c, "/bin/true"); err == nil {
t.Fatalf("Container %q was not stopped after gofer death", c.ID)
}
// Check that other containers are unaffected.
for i, c := range containers {
if i == 2 {
continue // container[2] has been killed.
}
pl := []*control.Process{
newProcessBuilder().PID(kernel.ThreadID(i + 1)).Cmd("sleep").Process(),
}
if err := waitForProcessList(c, pl); err != nil {
t.Errorf("Container %q was affected by another container: %v", c.ID, err)
}
if _, err := execute(conf, c, "/bin/true"); err != nil {
t.Fatalf("Container %q was affected by another container: %v", c.ID, err)
}
}
// Kill root container's gofer to bring entire sandbox down.
c = containers[0]
if err := unix.Kill(c.GoferPid, unix.SIGKILL); err != nil {
t.Fatalf("unix.Kill(%d, SIGKILL)=%v", c.GoferPid, err)
}
// Wait until sandbox stops. waitForProcessList will loop until sandbox exits
// and RPC errors out.
impossiblePL := []*control.Process{
newProcessBuilder().Cmd("non-existent-process").Process(),
}
if err := waitForProcessList(c, impossiblePL); err == nil {
t.Fatalf("Sandbox was not killed after gofer death")
}
// Check that entire sandbox isn't running anymore.
for _, c := range containers {
if _, err := execute(conf, c, "/bin/true"); err == nil {
t.Fatalf("Container %q was not stopped after gofer death", c.ID)
}
}
}
func TestMultiContainerLoadSandbox(t *testing.T) {
sleep := []string{"sleep", "100"}
specs, ids := createSpecs(sleep, sleep, sleep)
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
// Create containers for the sandbox.
wants, cleanup, err := startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Then create unrelated containers.
for i := 0; i < 3; i++ {
specs, ids = createSpecs(sleep, sleep, sleep)
_, cleanup, err = startContainers(conf, specs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
}
// Create an unrelated directory under root.
dir := filepath.Join(conf.RootDir, "not-a-container")
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatalf("os.MkdirAll(%q)=%v", dir, err)
}
// Create a valid but empty container directory.
randomCID := testutil.RandomContainerID()
dir = filepath.Join(conf.RootDir, randomCID)
if err := os.MkdirAll(dir, 0755); err != nil {
t.Fatalf("os.MkdirAll(%q)=%v", dir, err)
}
// Load the sandbox and check that the correct containers were returned.
id := wants[0].Sandbox.ID
gots, err := loadSandbox(conf.RootDir, id)
if err != nil {
t.Fatalf("loadSandbox()=%v", err)
}
wantIDs := make(map[string]struct{})
for _, want := range wants {
wantIDs[want.ID] = struct{}{}
}
for _, got := range gots {
if got.Sandbox.ID != id {
t.Errorf("wrong sandbox ID, got: %v, want: %v", got.Sandbox.ID, id)
}
if _, ok := wantIDs[got.ID]; !ok {
t.Errorf("wrong container ID, got: %v, wants: %v", got.ID, wantIDs)
}
delete(wantIDs, got.ID)
}
if len(wantIDs) != 0 {
t.Errorf("containers not found: %v", wantIDs)
}
}
// TestMultiContainerRunNonRoot checks that child container can be configured
// when running as non-privileged user.
func TestMultiContainerRunNonRoot(t *testing.T) {
cmdRoot := []string{"/bin/sleep", "100"}
cmdSub := []string{"/bin/true"}
podSpecs, ids := createSpecs(cmdRoot, cmdSub)
// User running inside container can't list '$TMP/blocked' and would fail to
// mount it.
blocked, err := ioutil.TempDir(testutil.TmpDir(), "blocked")
if err != nil {
t.Fatalf("ioutil.TempDir() failed: %v", err)
}
if err := os.Chmod(blocked, 0700); err != nil {
t.Fatalf("os.MkDir(%q) failed: %v", blocked, err)
}
dir := path.Join(blocked, "test")
if err := os.Mkdir(dir, 0755); err != nil {
t.Fatalf("os.MkDir(%q) failed: %v", dir, err)
}
src, err := ioutil.TempDir(testutil.TmpDir(), "src")
if err != nil {
t.Fatalf("ioutil.TempDir() failed: %v", err)
}
// Set a random user/group with no access to "blocked" dir.
podSpecs[1].Process.User.UID = 343
podSpecs[1].Process.User.GID = 2401
podSpecs[1].Process.Capabilities = nil
podSpecs[1].Mounts = append(podSpecs[1].Mounts, specs.Mount{
Destination: dir,
Source: src,
Type: "bind",
})
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf := testutil.TestConfig(t)
conf.RootDir = rootDir
pod, cleanup, err := startContainers(conf, podSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Once all containers are started, wait for the child container to exit.
// This means that the volume was mounted properly.
ws, err := pod[1].Wait()
if err != nil {
t.Fatalf("running child container: %v", err)
}
if !ws.Exited() || ws.ExitStatus() != 0 {
t.Fatalf("child container failed, waitStatus: %v", ws)
}
}
// TestMultiContainerHomeEnvDir tests that the HOME environment variable is set
// for root containers, sub-containers, and exec'ed processes.
func TestMultiContainerHomeEnvDir(t *testing.T) {
// NOTE: Don't use overlay since we need changes to persist to the temp dir
// outside the sandbox.
for testName, conf := range configs(t, noOverlay...) {
t.Run(testName, func(t *testing.T) {
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Create temp files we can write the value of $HOME to.
homeDirs := map[string]*os.File{}
for _, name := range []string{"root", "sub", "exec"} {
homeFile, err := ioutil.TempFile(testutil.TmpDir(), name)
if err != nil {
t.Fatalf("creating temp file: %v", err)
}
homeDirs[name] = homeFile
}
// We will sleep in the root container in order to ensure that the root
//container doesn't terminate before sub containers can be created.
rootCmd := []string{"/bin/sh", "-c", fmt.Sprintf(`printf "$HOME" > %s; sleep 1000`, homeDirs["root"].Name())}
subCmd := []string{"/bin/sh", "-c", fmt.Sprintf(`printf "$HOME" > %s`, homeDirs["sub"].Name())}
execCmd := fmt.Sprintf(`printf "$HOME" > %s`, homeDirs["exec"].Name())
// Setup the containers, a root container and sub container.
specConfig, ids := createSpecs(rootCmd, subCmd)
containers, cleanup, err := startContainers(conf, specConfig, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Exec into the root container synchronously.
if _, err := execute(conf, containers[0], "/bin/sh", "-c", execCmd); err != nil {
t.Errorf("error executing %+v: %v", execCmd, err)
}
// Wait for the subcontainer to finish.
_, err = containers[1].Wait()
if err != nil {
t.Errorf("wait on child container: %v", err)
}
// Wait until after `env` has executed.
expectedProc := newProcessBuilder().Cmd("sleep").Process()
if err := waitForProcess(containers[0], expectedProc); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
// Check the written files.
for name, tmpFile := range homeDirs {
dirBytes, err := ioutil.ReadAll(tmpFile)
if err != nil {
t.Fatalf("reading %s temp file: %v", name, err)
}
got := string(dirBytes)
want := "/"
if got != want {
t.Errorf("%s $HOME incorrect: got: %q, want: %q", name, got, want)
}
}
})
}
}
func TestMultiContainerEvent(t *testing.T) {
conf := testutil.TestConfig(t)
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Setup the containers.
sleep := []string{"/bin/sleep", "100"}
busy := []string{"/bin/bash", "-c", "i=0 ; while true ; do (( i += 1 )) ; done"}
quick := []string{"/bin/true"}
podSpec, ids := createSpecs(sleep, busy, quick)
containers, cleanup, err := startContainers(conf, podSpec, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
t.Logf("Running container sleep %s", containers[0].ID)
t.Logf("Running container busy %s", containers[1].ID)
t.Logf("Running container quick %s", containers[2].ID)
// Wait for last container to stabilize the process count that is
// checked further below.
if ws, err := containers[2].Wait(); err != nil || ws != 0 {
t.Fatalf("Container.Wait, status: %v, err: %v", ws, err)
}
expectedPL := []*control.Process{
newProcessBuilder().Cmd("sleep").Process(),
}
if err := waitForProcessList(containers[0], expectedPL); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
expectedPL = []*control.Process{
newProcessBuilder().Cmd("bash").Process(),
}
if err := waitForProcessList(containers[1], expectedPL); err != nil {
t.Errorf("failed to wait for bash to start: %v", err)
}
// Check events for running containers.
for _, cont := range containers[:2] {
ret, err := cont.Event()
if err != nil {
t.Errorf("Container.Event(%q): %v", cont.ID, err)
}
evt := ret.Event
if want := "stats"; evt.Type != want {
t.Errorf("Wrong event type, cid: %q, want: %s, got: %s", cont.ID, want, evt.Type)
}
if cont.ID != evt.ID {
t.Errorf("Wrong container ID, want: %s, got: %s", cont.ID, evt.ID)
}
// One process per remaining container.
if got, want := evt.Data.Pids.Current, uint64(2); got != want {
t.Errorf("Wrong number of PIDs, cid: %q, want: %d, got: %d", cont.ID, want, got)
}
// The exited container should always have a usage of zero.
if exited := ret.ContainerUsage[containers[2].ID]; exited != 0 {
t.Errorf("Exited container should report 0 CPU usage, got: %d", exited)
}
}
// Check that CPU reported by busy container is higher than sleep.
cb := func() error {
sleepEvt, err := containers[0].Event()
if err != nil {
return &backoff.PermanentError{Err: err}
}
sleepUsage := sleepEvt.Event.Data.CPU.Usage.Total
busyEvt, err := containers[1].Event()
if err != nil {
return &backoff.PermanentError{Err: err}
}
busyUsage := busyEvt.Event.Data.CPU.Usage.Total
if busyUsage <= sleepUsage {
t.Logf("Busy container usage lower than sleep (busy: %d, sleep: %d), retrying...", busyUsage, sleepUsage)
return fmt.Errorf("busy container should have higher usage than sleep, busy: %d, sleep: %d", busyUsage, sleepUsage)
}
return nil
}
// Give time for busy container to run and use more CPU than sleep.
if err := testutil.Poll(cb, 10*time.Second); err != nil {
t.Fatal(err)
}
// Check that stopped and destroyed containers return error.
if err := containers[1].Destroy(); err != nil {
t.Fatalf("container.Destroy: %v", err)
}
for _, cont := range containers[1:] {
if _, err := cont.Event(); err == nil {
t.Errorf("Container.Event() should have failed, cid: %q, state: %v", cont.ID, cont.Status)
}
}
}
// Tests that duplicate variables in the spec are merged into a single one.
func TestDuplicateEnvVariable(t *testing.T) {
conf := testutil.TestConfig(t)
rootDir, cleanup, err := testutil.SetupRootDir()
if err != nil {
t.Fatalf("error creating root dir: %v", err)
}
defer cleanup()
conf.RootDir = rootDir
// Create files to dump `env` output.
files := [3]*os.File{}
for i := 0; i < len(files); i++ {
var err error
files[i], err = ioutil.TempFile(testutil.TmpDir(), "env-var-test")
if err != nil {
t.Fatalf("creating temp file: %v", err)
}
defer files[i].Close()
defer os.Remove(files[i].Name())
}
// Setup the containers. Use root container to test exec too.
cmd1 := fmt.Sprintf("env > %q; sleep 1000", files[0].Name())
cmd2 := fmt.Sprintf("env > %q", files[1].Name())
cmdExec := fmt.Sprintf("env > %q", files[2].Name())
testSpecs, ids := createSpecs([]string{"/bin/sh", "-c", cmd1}, []string{"/bin/sh", "-c", cmd2})
testSpecs[0].Process.Env = append(testSpecs[0].Process.Env, "VAR=foo", "VAR=bar")
testSpecs[1].Process.Env = append(testSpecs[1].Process.Env, "VAR=foo", "VAR=bar")
containers, cleanup, err := startContainers(conf, testSpecs, ids)
if err != nil {
t.Fatalf("error starting containers: %v", err)
}
defer cleanup()
// Wait until after `env` has executed.
expectedProc := newProcessBuilder().Cmd("sleep").Process()
if err := waitForProcess(containers[0], expectedProc); err != nil {
t.Errorf("failed to wait for sleep to start: %v", err)
}
if ws, err := containers[1].Wait(); err != nil {
t.Errorf("failed to wait container 1: %v", err)
} else if es := ws.ExitStatus(); es != 0 {
t.Errorf("container %s exited with non-zero status: %v", containers[1].ID, es)
}
execArgs := &control.ExecArgs{
Filename: "/bin/sh",
Argv: []string{"/bin/sh", "-c", cmdExec},
Envv: []string{"VAR=foo", "VAR=bar"},
}
if ws, err := containers[0].executeSync(conf, execArgs); err != nil || ws.ExitStatus() != 0 {
t.Fatalf("exec failed, ws: %v, err: %v", ws, err)
}
// Now read and check that none of the env has repeated values.
for _, file := range files {
out, err := ioutil.ReadAll(file)
if err != nil {
t.Fatal(err)
}
t.Logf("Checking env %q:\n%s", file.Name(), out)
envs := make(map[string]string)
for _, line := range strings.Split(string(out), "\n") {
if len(line) == 0 {
continue
}
envVar := strings.SplitN(line, "=", 2)
if len(envVar) != 2 {
t.Fatalf("invalid env variable: %s", line)
}
key := envVar[0]
if val, ok := envs[key]; ok {
t.Errorf("env variable %q is duplicated: %q and %q", key, val, envVar[1])
}
envs[key] = envVar[1]
}
if _, ok := envs["VAR"]; !ok {
t.Errorf("variable VAR missing: %v", envs)
}
}
}
|