forked from moby/moby
-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_api_containers_test.go
2068 lines (1761 loc) · 62 KB
/
docker_api_containers_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 main
import (
"archive/tar"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"testing"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
dconfig "github.com/docker/docker/daemon/config"
"github.com/docker/docker/errdefs"
"github.com/docker/docker/integration-cli/cli"
"github.com/docker/docker/integration-cli/cli/build"
"github.com/docker/docker/pkg/stringid"
"github.com/docker/docker/testutil"
"github.com/docker/docker/testutil/request"
"github.com/docker/docker/volume"
"github.com/docker/go-connections/nat"
"gotest.tools/v3/assert"
is "gotest.tools/v3/assert/cmp"
"gotest.tools/v3/poll"
)
func (s *DockerAPISuite) TestContainerAPIGetAll(c *testing.T) {
startCount := getContainerCount(c)
const name = "getall"
cli.DockerCmd(c, "run", "--name", name, "busybox", "true")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
ctx := testutil.GetContext(c)
containers, err := apiClient.ContainerList(ctx, container.ListOptions{
All: true,
})
assert.NilError(c, err)
assert.Equal(c, len(containers), startCount+1)
actual := containers[0].Names[0]
assert.Equal(c, actual, "/"+name)
}
// regression test for empty json field being omitted #13691
func (s *DockerAPISuite) TestContainerAPIGetJSONNoFieldsOmitted(c *testing.T) {
startCount := getContainerCount(c)
cli.DockerCmd(c, "run", "busybox", "true")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
options := container.ListOptions{
All: true,
}
ctx := testutil.GetContext(c)
containers, err := apiClient.ContainerList(ctx, options)
assert.NilError(c, err)
assert.Equal(c, len(containers), startCount+1)
actual := fmt.Sprintf("%+v", containers[0])
// empty Labels field triggered this bug, make sense to check for everything
// cause even Ports for instance can trigger this bug
// better safe than sorry..
fields := []string{
"ID",
"Names",
"Image",
"Command",
"Created",
"Ports",
"Labels",
"Status",
"NetworkSettings",
}
// decoding into types.Container do not work since it eventually unmarshal
// and empty field to an empty go map, so we just check for a string
for _, f := range fields {
if !strings.Contains(actual, f) {
c.Fatalf("Field %s is missing and it shouldn't", f)
}
}
}
func (s *DockerAPISuite) TestContainerAPIGetExport(c *testing.T) {
// Not supported on Windows as Windows does not support docker export
testRequires(c, DaemonIsLinux)
const name = "exportcontainer"
cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
body, err := apiClient.ContainerExport(testutil.GetContext(c), name)
assert.NilError(c, err)
defer body.Close()
found := false
for tarReader := tar.NewReader(body); ; {
h, err := tarReader.Next()
if err != nil && err == io.EOF {
break
}
if h.Name == "test" {
found = true
break
}
}
assert.Assert(c, found, "The created test file has not been found in the exported image")
}
func (s *DockerAPISuite) TestContainerAPIGetChanges(c *testing.T) {
// Not supported on Windows as Windows does not support docker diff (/containers/name/changes)
testRequires(c, DaemonIsLinux)
const name = "changescontainer"
cli.DockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
changes, err := apiClient.ContainerDiff(testutil.GetContext(c), name)
assert.NilError(c, err)
// Check the changelog for removal of /etc/passwd
success := false
for _, elem := range changes {
if elem.Path == "/etc/passwd" && elem.Kind == 2 {
success = true
}
}
assert.Assert(c, success, "/etc/passwd has been removed but is not present in the diff")
}
func (s *DockerAPISuite) TestGetContainerStats(c *testing.T) {
const name = "statscontainer"
runSleepingContainer(c, "--name", name)
type b struct {
stats types.ContainerStats
err error
}
bc := make(chan b, 1)
go func() {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
stats, err := apiClient.ContainerStats(testutil.GetContext(c), name, true)
assert.NilError(c, err)
bc <- b{stats, err}
}()
// allow some time to stream the stats from the container
time.Sleep(4 * time.Second)
cli.DockerCmd(c, "rm", "-f", name)
// collect the results from the stats stream or timeout and fail
// if the stream was not disconnected.
select {
case <-time.After(2 * time.Second):
c.Fatal("stream was not closed after container was removed")
case sr := <-bc:
dec := json.NewDecoder(sr.stats.Body)
defer sr.stats.Body.Close()
var s *types.Stats
// decode only one object from the stream
assert.NilError(c, dec.Decode(&s))
}
}
func (s *DockerAPISuite) TestGetContainerStatsRmRunning(c *testing.T) {
id := runSleepingContainer(c)
buf := &ChannelBuffer{C: make(chan []byte, 1)}
defer buf.Close()
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
stats, err := apiClient.ContainerStats(testutil.GetContext(c), id, true)
assert.NilError(c, err)
defer stats.Body.Close()
chErr := make(chan error, 1)
go func() {
_, err = io.Copy(buf, stats.Body)
chErr <- err
}()
b := make([]byte, 32)
// make sure we've got some stats
_, err = buf.ReadTimeout(b, 2*time.Second)
assert.NilError(c, err)
// Now remove without `-f` and make sure we are still pulling stats
_, _, err = dockerCmdWithError("rm", id)
assert.Assert(c, err != nil, "rm should have failed but didn't")
_, err = buf.ReadTimeout(b, 2*time.Second)
assert.NilError(c, err)
cli.DockerCmd(c, "rm", "-f", id)
assert.Assert(c, <-chErr == nil)
}
// ChannelBuffer holds a chan of byte array that can be populate in a goroutine.
type ChannelBuffer struct {
C chan []byte
}
// Write implements Writer.
func (c *ChannelBuffer) Write(b []byte) (int, error) {
c.C <- b
return len(b), nil
}
// Close closes the go channel.
func (c *ChannelBuffer) Close() error {
close(c.C)
return nil
}
// ReadTimeout reads the content of the channel in the specified byte array with
// the specified duration as timeout.
func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) {
select {
case b := <-c.C:
return copy(p[0:], b), nil
case <-time.After(n):
return -1, fmt.Errorf("timeout reading from channel")
}
}
// regression test for gh13421
// previous test was just checking one stat entry so it didn't fail (stats with
// stream false always return one stat)
func (s *DockerAPISuite) TestGetContainerStatsStream(c *testing.T) {
const name = "statscontainer"
runSleepingContainer(c, "--name", name)
type b struct {
stats types.ContainerStats
err error
}
bc := make(chan b, 1)
go func() {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
stats, err := apiClient.ContainerStats(testutil.GetContext(c), name, true)
assert.NilError(c, err)
bc <- b{stats, err}
}()
// allow some time to stream the stats from the container
time.Sleep(4 * time.Second)
cli.DockerCmd(c, "rm", "-f", name)
// collect the results from the stats stream or timeout and fail
// if the stream was not disconnected.
select {
case <-time.After(2 * time.Second):
c.Fatal("stream was not closed after container was removed")
case sr := <-bc:
b, err := io.ReadAll(sr.stats.Body)
defer sr.stats.Body.Close()
assert.NilError(c, err)
s := string(b)
// count occurrences of "read" of types.Stats
if l := strings.Count(s, "read"); l < 2 {
c.Fatalf("Expected more than one stat streamed, got %d", l)
}
}
}
func (s *DockerAPISuite) TestGetContainerStatsNoStream(c *testing.T) {
const name = "statscontainer2"
runSleepingContainer(c, "--name", name)
type b struct {
stats types.ContainerStats
err error
}
bc := make(chan b, 1)
go func() {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
stats, err := apiClient.ContainerStats(testutil.GetContext(c), name, false)
assert.NilError(c, err)
bc <- b{stats, err}
}()
// allow some time to stream the stats from the container
time.Sleep(4 * time.Second)
cli.DockerCmd(c, "rm", "-f", name)
// collect the results from the stats stream or timeout and fail
// if the stream was not disconnected.
select {
case <-time.After(2 * time.Second):
c.Fatal("stream was not closed after container was removed")
case sr := <-bc:
b, err := io.ReadAll(sr.stats.Body)
defer sr.stats.Body.Close()
assert.NilError(c, err)
s := string(b)
// count occurrences of `"read"` of types.Stats
assert.Assert(c, strings.Count(s, `"read"`) == 1, "Expected only one stat streamed, got %d", strings.Count(s, `"read"`))
}
}
func (s *DockerAPISuite) TestGetStoppedContainerStats(c *testing.T) {
const name = "statscontainer3"
cli.DockerCmd(c, "create", "--name", name, "busybox", "ps")
chResp := make(chan error, 1)
// We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine
// below we'll check this on a timeout.
go func() {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
resp, err := apiClient.ContainerStats(testutil.GetContext(c), name, false)
assert.NilError(c, err)
defer resp.Body.Close()
chResp <- err
}()
select {
case err := <-chResp:
assert.NilError(c, err)
case <-time.After(10 * time.Second):
c.Fatal("timeout waiting for stats response for stopped container")
}
}
func (s *DockerAPISuite) TestContainerAPIPause(c *testing.T) {
// Problematic on Windows as Windows does not support pause
testRequires(c, DaemonIsLinux)
getPaused := func(c *testing.T) []string {
return strings.Fields(cli.DockerCmd(c, "ps", "-f", "status=paused", "-q", "-a").Combined())
}
out := cli.DockerCmd(c, "run", "-d", "busybox", "sleep", "30").Combined()
ContainerID := strings.TrimSpace(out)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerPause(testutil.GetContext(c), ContainerID)
assert.NilError(c, err)
pausedContainers := getPaused(c)
if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] {
c.Fatalf("there should be one paused container and not %d", len(pausedContainers))
}
err = apiClient.ContainerUnpause(testutil.GetContext(c), ContainerID)
assert.NilError(c, err)
pausedContainers = getPaused(c)
assert.Equal(c, len(pausedContainers), 0, "There should be no paused container.")
}
func (s *DockerAPISuite) TestContainerAPITop(c *testing.T) {
testRequires(c, DaemonIsLinux)
out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top && true").Stdout()
id := strings.TrimSpace(out)
cli.WaitRun(c, id)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
// sort by comm[andline] to make sure order stays the same in case of PID rollover
top, err := apiClient.ContainerTop(testutil.GetContext(c), id, []string{"aux", "--sort=comm"})
assert.NilError(c, err)
assert.Equal(c, len(top.Titles), 11, fmt.Sprintf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles))
if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" {
c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles)
}
assert.Equal(c, len(top.Processes), 2, fmt.Sprintf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes))
assert.Equal(c, top.Processes[0][10], "/bin/sh -c top && true")
assert.Equal(c, top.Processes[1][10], "top")
}
func (s *DockerAPISuite) TestContainerAPITopWindows(c *testing.T) {
testRequires(c, DaemonIsWindows)
id := runSleepingContainer(c, "-d")
cli.WaitRun(c, id)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
top, err := apiClient.ContainerTop(testutil.GetContext(c), id, nil)
assert.NilError(c, err)
assert.Equal(c, len(top.Titles), 4, "expected 4 titles, found %d: %v", len(top.Titles), top.Titles)
if top.Titles[0] != "Name" || top.Titles[3] != "Private Working Set" {
c.Fatalf("expected `Name` at `Titles[0]` and `Private Working Set` at Titles[3]: %v", top.Titles)
}
assert.Assert(c, len(top.Processes) >= 2, "expected at least 2 processes, found %d: %v", len(top.Processes), top.Processes)
foundProcess := false
expectedProcess := "busybox.exe"
for _, process := range top.Processes {
if process[0] == expectedProcess {
foundProcess = true
break
}
}
assert.Assert(c, foundProcess, "expected to find %s: %v", expectedProcess, top.Processes)
}
func (s *DockerAPISuite) TestContainerAPICommit(c *testing.T) {
const cName = "testapicommit"
cli.DockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
options := container.CommitOptions{
Reference: "testcontainerapicommit:testtag",
}
img, err := apiClient.ContainerCommit(testutil.GetContext(c), cName, options)
assert.NilError(c, err)
cmd := inspectField(c, img.ID, "Config.Cmd")
assert.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("got wrong Cmd from commit: %q", cmd))
// sanity check, make sure the image is what we think it is
cli.DockerCmd(c, "run", img.ID, "ls", "/test")
}
func (s *DockerAPISuite) TestContainerAPICommitWithLabelInConfig(c *testing.T) {
const cName = "testapicommitwithconfig"
cli.DockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
config := container.Config{
Labels: map[string]string{"key1": "value1", "key2": "value2"},
}
options := container.CommitOptions{
Reference: "testcontainerapicommitwithconfig",
Config: &config,
}
img, err := apiClient.ContainerCommit(testutil.GetContext(c), cName, options)
assert.NilError(c, err)
label1 := inspectFieldMap(c, img.ID, "Config.Labels", "key1")
assert.Equal(c, label1, "value1")
label2 := inspectFieldMap(c, img.ID, "Config.Labels", "key2")
assert.Equal(c, label2, "value2")
cmd := inspectField(c, img.ID, "Config.Cmd")
assert.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("got wrong Cmd from commit: %q", cmd))
// sanity check, make sure the image is what we think it is
cli.DockerCmd(c, "run", img.ID, "ls", "/test")
}
func (s *DockerAPISuite) TestContainerAPIBadPort(c *testing.T) {
// TODO Windows to Windows CI - Port this test
testRequires(c, DaemonIsLinux)
config := container.Config{
Image: "busybox",
Cmd: []string{"/bin/sh", "-c", "echo test"},
}
hostConfig := container.HostConfig{
PortBindings: nat.PortMap{
"8080/tcp": []nat.PortBinding{
{
HostIP: "",
HostPort: "aa80",
},
},
},
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
_, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
assert.ErrorContains(c, err, `invalid port specification: "aa80"`)
}
func (s *DockerAPISuite) TestContainerAPICreate(c *testing.T) {
config := container.Config{
Image: "busybox",
Cmd: []string{"/bin/sh", "-c", "touch /test && ls /test"},
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
ctr, err := apiClient.ContainerCreate(testutil.GetContext(c), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
assert.NilError(c, err)
out := cli.DockerCmd(c, "start", "-a", ctr.ID).Stdout()
assert.Equal(c, strings.TrimSpace(out), "/test")
}
func (s *DockerAPISuite) TestContainerAPICreateEmptyConfig(c *testing.T) {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
_, err = apiClient.ContainerCreate(testutil.GetContext(c), &container.Config{}, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "")
assert.ErrorContains(c, err, "no command specified")
}
func (s *DockerAPISuite) TestContainerAPICreateBridgeNetworkMode(c *testing.T) {
// Windows does not support bridge
testRequires(c, DaemonIsLinux)
UtilCreateNetworkMode(c, "bridge")
}
func (s *DockerAPISuite) TestContainerAPICreateOtherNetworkModes(c *testing.T) {
// Windows does not support these network modes
testRequires(c, DaemonIsLinux, NotUserNamespace)
UtilCreateNetworkMode(c, "host")
UtilCreateNetworkMode(c, "container:web1")
}
func UtilCreateNetworkMode(c *testing.T, networkMode container.NetworkMode) {
config := container.Config{
Image: "busybox",
}
hostConfig := container.HostConfig{
NetworkMode: networkMode,
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
ctr, err := apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
assert.NilError(c, err)
containerJSON, err := apiClient.ContainerInspect(testutil.GetContext(c), ctr.ID)
assert.NilError(c, err)
assert.Equal(c, containerJSON.HostConfig.NetworkMode, networkMode, "Mismatched NetworkMode")
}
func (s *DockerAPISuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) {
// TODO Windows to Windows CI. The CpuShares part could be ported.
testRequires(c, DaemonIsLinux)
config := container.Config{
Image: "busybox",
}
hostConfig := container.HostConfig{
Resources: container.Resources{
CPUShares: 512,
CpusetCpus: "0",
},
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
ctr, err := apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
assert.NilError(c, err)
containerJSON, err := apiClient.ContainerInspect(testutil.GetContext(c), ctr.ID)
assert.NilError(c, err)
out := inspectField(c, containerJSON.ID, "HostConfig.CpuShares")
assert.Equal(c, out, "512")
outCpuset := inspectField(c, containerJSON.ID, "HostConfig.CpusetCpus")
assert.Equal(c, outCpuset, "0")
}
func (s *DockerAPISuite) TestContainerAPIVerifyHeader(c *testing.T) {
config := map[string]interface{}{
"Image": "busybox",
}
create := func(ct string) (*http.Response, io.ReadCloser, error) {
jsonData := bytes.NewBuffer(nil)
assert.Assert(c, json.NewEncoder(jsonData).Encode(config) == nil)
return request.Post(testutil.GetContext(c), "/containers/create", request.RawContent(io.NopCloser(jsonData)), request.ContentType(ct))
}
// Try with no content-type
res, body, err := create("")
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
_ = body.Close()
// Try with wrong content-type
res, body, err = create("application/xml")
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
_ = body.Close()
// now application/json
res, body, err = create("application/json")
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusCreated)
_ = body.Close()
}
// Issue 14230. daemon should return 500 for invalid port syntax
func (s *DockerAPISuite) TestContainerAPIInvalidPortSyntax(c *testing.T) {
config := `{
"Image": "busybox",
"HostConfig": {
"NetworkMode": "default",
"PortBindings": {
"19039;1230": [
{}
]
}
}
}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
b, err := request.ReadBody(body)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(string(b[:]), "invalid port"))
}
func (s *DockerAPISuite) TestContainerAPIRestartPolicyInvalidPolicyName(c *testing.T) {
config := `{
"Image": "busybox",
"HostConfig": {
"RestartPolicy": {
"Name": "something",
"MaximumRetryCount": 0
}
}
}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
b, err := request.ReadBody(body)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(string(b[:]), "invalid restart policy"))
}
func (s *DockerAPISuite) TestContainerAPIRestartPolicyRetryMismatch(c *testing.T) {
config := `{
"Image": "busybox",
"HostConfig": {
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 2
}
}
}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
b, err := request.ReadBody(body)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(string(b[:]), "invalid restart policy: maximum retry count can only be used with 'on-failure'"))
}
func (s *DockerAPISuite) TestContainerAPIRestartPolicyNegativeRetryCount(c *testing.T) {
config := `{
"Image": "busybox",
"HostConfig": {
"RestartPolicy": {
"Name": "on-failure",
"MaximumRetryCount": -2
}
}
}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
b, err := request.ReadBody(body)
assert.NilError(c, err)
assert.Assert(c, strings.Contains(string(b[:]), "maximum retry count cannot be negative"))
}
func (s *DockerAPISuite) TestContainerAPIRestartPolicyDefaultRetryCount(c *testing.T) {
config := `{
"Image": "busybox",
"HostConfig": {
"RestartPolicy": {
"Name": "on-failure",
"MaximumRetryCount": 0
}
}
}`
res, _, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusCreated)
}
// Issue 7941 - test to make sure a "null" in JSON is just ignored.
// W/o this fix a null in JSON would be parsed into a string var as "null"
func (s *DockerAPISuite) TestContainerAPIPostCreateNull(c *testing.T) {
config := `{
"Hostname":"",
"Domainname":"",
"Memory":0,
"MemorySwap":0,
"CpuShares":0,
"Cpuset":null,
"AttachStdin":true,
"AttachStdout":true,
"AttachStderr":true,
"ExposedPorts":{},
"Tty":true,
"OpenStdin":true,
"StdinOnce":true,
"Env":[],
"Cmd":"ls",
"Image":"busybox",
"Volumes":{},
"WorkingDir":"",
"Entrypoint":null,
"NetworkDisabled":false,
"OnBuild":null}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusCreated)
b, err := request.ReadBody(body)
assert.NilError(c, err)
type createResp struct {
ID string
}
var ctr createResp
assert.Assert(c, json.Unmarshal(b, &ctr) == nil)
out := inspectField(c, ctr.ID, "HostConfig.CpusetCpus")
assert.Equal(c, out, "")
outMemory := inspectField(c, ctr.ID, "HostConfig.Memory")
assert.Equal(c, outMemory, "0")
outMemorySwap := inspectField(c, ctr.ID, "HostConfig.MemorySwap")
assert.Equal(c, outMemorySwap, "0")
}
func (s *DockerAPISuite) TestCreateWithTooLowMemoryLimit(c *testing.T) {
// TODO Windows: Port once memory is supported
testRequires(c, DaemonIsLinux)
config := `{
"Image": "busybox",
"Cmd": "ls",
"OpenStdin": true,
"CpuShares": 100,
"Memory": 524287
}`
res, body, err := request.Post(testutil.GetContext(c), "/containers/create", request.RawString(config), request.JSON)
assert.NilError(c, err)
b, err2 := request.ReadBody(body)
assert.Assert(c, err2 == nil)
assert.Equal(c, res.StatusCode, http.StatusBadRequest)
assert.Assert(c, strings.Contains(string(b), "Minimum memory limit allowed is 6MB"))
}
func (s *DockerAPISuite) TestContainerAPIRename(c *testing.T) {
out := cli.DockerCmd(c, "run", "--name", "TestContainerAPIRename", "-d", "busybox", "sh").Stdout()
containerID := strings.TrimSpace(out)
const newName = "TestContainerAPIRenameNew"
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerRename(testutil.GetContext(c), containerID, newName)
assert.NilError(c, err)
name := inspectField(c, containerID, "Name")
assert.Equal(c, name, "/"+newName, "Failed to rename container")
}
func (s *DockerAPISuite) TestContainerAPIKill(c *testing.T) {
const name = "test-api-kill"
runSleepingContainer(c, "-i", "--name", name)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerKill(testutil.GetContext(c), name, "SIGKILL")
assert.NilError(c, err)
state := inspectField(c, name, "State.Running")
assert.Equal(c, state, "false", fmt.Sprintf("got wrong State from container %s: %q", name, state))
}
func (s *DockerAPISuite) TestContainerAPIRestart(c *testing.T) {
const name = "test-api-restart"
runSleepingContainer(c, "-di", "--name", name)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
timeout := 1
err = apiClient.ContainerRestart(testutil.GetContext(c), name, container.StopOptions{Timeout: &timeout})
assert.NilError(c, err)
assert.Assert(c, waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) == nil)
}
func (s *DockerAPISuite) TestContainerAPIRestartNotimeoutParam(c *testing.T) {
const name = "test-api-restart-no-timeout-param"
id := runSleepingContainer(c, "-di", "--name", name)
cli.WaitRun(c, id)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerRestart(testutil.GetContext(c), name, container.StopOptions{})
assert.NilError(c, err)
assert.Assert(c, waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) == nil)
}
func (s *DockerAPISuite) TestContainerAPIStart(c *testing.T) {
const name = "testing-start"
config := container.Config{
Image: "busybox",
Cmd: append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...),
OpenStdin: true,
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
_, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, name)
assert.NilError(c, err)
err = apiClient.ContainerStart(testutil.GetContext(c), name, container.StartOptions{})
assert.NilError(c, err)
// second call to start should give 304
// maybe add ContainerStartWithRaw to test it
err = apiClient.ContainerStart(testutil.GetContext(c), name, container.StartOptions{})
assert.NilError(c, err)
// TODO(tibor): figure out why this doesn't work on windows
}
func (s *DockerAPISuite) TestContainerAPIStop(c *testing.T) {
const name = "test-api-stop"
runSleepingContainer(c, "-i", "--name", name)
timeout := 30
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerStop(testutil.GetContext(c), name, container.StopOptions{
Timeout: &timeout,
})
assert.NilError(c, err)
assert.Assert(c, waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second) == nil)
// second call to start should give 304
// maybe add ContainerStartWithRaw to test it
err = apiClient.ContainerStop(testutil.GetContext(c), name, container.StopOptions{
Timeout: &timeout,
})
assert.NilError(c, err)
}
func (s *DockerAPISuite) TestContainerAPIWait(c *testing.T) {
const name = "test-api-wait"
sleepCmd := "/bin/sleep"
if testEnv.DaemonInfo.OSType == "windows" {
sleepCmd = "sleep"
}
cli.DockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2")
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
waitResC, errC := apiClient.ContainerWait(testutil.GetContext(c), name, "")
select {
case err = <-errC:
assert.NilError(c, err)
case waitRes := <-waitResC:
assert.Equal(c, waitRes.StatusCode, int64(0))
}
}
func (s *DockerAPISuite) TestContainerAPICopyNotExistsAnyMore(c *testing.T) {
const name = "test-container-api-copy"
cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt")
postData := types.CopyConfig{
Resource: "/test.txt",
}
// no copy in client/
res, _, err := request.Post(testutil.GetContext(c), "/containers/"+name+"/copy", request.JSONBody(postData))
assert.NilError(c, err)
assert.Equal(c, res.StatusCode, http.StatusNotFound)
}
func (s *DockerAPISuite) TestContainerAPIDelete(c *testing.T) {
id := runSleepingContainer(c)
cli.WaitRun(c, id)
cli.DockerCmd(c, "stop", id)
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerRemove(testutil.GetContext(c), id, container.RemoveOptions{})
assert.NilError(c, err)
}
func (s *DockerAPISuite) TestContainerAPIDeleteNotExist(c *testing.T) {
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerRemove(testutil.GetContext(c), "doesnotexist", container.RemoveOptions{})
assert.ErrorContains(c, err, "No such container: doesnotexist")
}
func (s *DockerAPISuite) TestContainerAPIDeleteForce(c *testing.T) {
id := runSleepingContainer(c)
cli.WaitRun(c, id)
removeOptions := container.RemoveOptions{
Force: true,
}
apiClient, err := client.NewClientWithOpts(client.FromEnv)
assert.NilError(c, err)
defer apiClient.Close()
err = apiClient.ContainerRemove(testutil.GetContext(c), id, removeOptions)
assert.NilError(c, err)
}
func (s *DockerAPISuite) TestContainerAPIDeleteRemoveLinks(c *testing.T) {
// Windows does not support links