github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/integration-cli/docker_cli_create_test.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"fmt"
     7  	"os"
     8  	"reflect"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/Prakhar-Agarwal-byte/moby/integration-cli/cli"
    13  	"github.com/Prakhar-Agarwal-byte/moby/integration-cli/cli/build"
    14  	"github.com/Prakhar-Agarwal-byte/moby/pkg/stringid"
    15  	"github.com/Prakhar-Agarwal-byte/moby/testutil/fakecontext"
    16  	"github.com/docker/go-connections/nat"
    17  	"gotest.tools/v3/assert"
    18  	is "gotest.tools/v3/assert/cmp"
    19  )
    20  
    21  type DockerCLICreateSuite struct {
    22  	ds *DockerSuite
    23  }
    24  
    25  func (s *DockerCLICreateSuite) TearDownTest(ctx context.Context, c *testing.T) {
    26  	s.ds.TearDownTest(ctx, c)
    27  }
    28  
    29  func (s *DockerCLICreateSuite) OnTimeout(c *testing.T) {
    30  	s.ds.OnTimeout(c)
    31  }
    32  
    33  // Make sure we can create a simple container with some args
    34  func (s *DockerCLICreateSuite) TestCreateArgs(c *testing.T) {
    35  	// Intentionally clear entrypoint, as the Windows busybox image needs an entrypoint, which breaks this test
    36  	containerID := cli.DockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags").Stdout()
    37  	containerID = strings.TrimSpace(containerID)
    38  
    39  	out := cli.DockerCmd(c, "inspect", containerID).Combined()
    40  
    41  	var containers []struct {
    42  		Path string
    43  		Args []string
    44  	}
    45  
    46  	err := json.Unmarshal([]byte(out), &containers)
    47  	assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
    48  	assert.Equal(c, len(containers), 1)
    49  
    50  	cont := containers[0]
    51  	assert.Equal(c, cont.Path, "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path))
    52  
    53  	b := false
    54  	expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
    55  	for i, arg := range expected {
    56  		if arg != cont.Args[i] {
    57  			b = true
    58  			break
    59  		}
    60  	}
    61  	if len(cont.Args) != len(expected) || b {
    62  		c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
    63  	}
    64  }
    65  
    66  // Make sure we can set hostconfig options too
    67  func (s *DockerCLICreateSuite) TestCreateHostConfig(c *testing.T) {
    68  	containerID := cli.DockerCmd(c, "create", "-P", "busybox", "echo").Stdout()
    69  	containerID = strings.TrimSpace(containerID)
    70  
    71  	out := cli.DockerCmd(c, "inspect", containerID).Stdout()
    72  
    73  	var containers []struct {
    74  		HostConfig *struct {
    75  			PublishAllPorts bool
    76  		}
    77  	}
    78  
    79  	err := json.Unmarshal([]byte(out), &containers)
    80  	assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
    81  	assert.Equal(c, len(containers), 1)
    82  
    83  	cont := containers[0]
    84  	assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
    85  	assert.Assert(c, cont.HostConfig.PublishAllPorts, "Expected PublishAllPorts, got false")
    86  }
    87  
    88  func (s *DockerCLICreateSuite) TestCreateWithPortRange(c *testing.T) {
    89  	containerID := cli.DockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo").Stdout()
    90  	containerID = strings.TrimSpace(containerID)
    91  
    92  	out := cli.DockerCmd(c, "inspect", containerID).Stdout()
    93  
    94  	var containers []struct {
    95  		HostConfig *struct {
    96  			PortBindings map[nat.Port][]nat.PortBinding
    97  		}
    98  	}
    99  	err := json.Unmarshal([]byte(out), &containers)
   100  	assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
   101  	assert.Equal(c, len(containers), 1)
   102  
   103  	cont := containers[0]
   104  
   105  	assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
   106  	assert.Equal(c, len(cont.HostConfig.PortBindings), 4, fmt.Sprintf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))
   107  
   108  	for k, v := range cont.HostConfig.PortBindings {
   109  		assert.Equal(c, len(v), 1, fmt.Sprintf("Expected 1 ports binding, for the port  %s but found %s", k, v))
   110  		assert.Equal(c, k.Port(), v[0].HostPort, fmt.Sprintf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
   111  	}
   112  }
   113  
   114  func (s *DockerCLICreateSuite) TestCreateWithLargePortRange(c *testing.T) {
   115  	containerID := cli.DockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo").Stdout()
   116  	containerID = strings.TrimSpace(containerID)
   117  
   118  	out := cli.DockerCmd(c, "inspect", containerID).Stdout()
   119  
   120  	var containers []struct {
   121  		HostConfig *struct {
   122  			PortBindings map[nat.Port][]nat.PortBinding
   123  		}
   124  	}
   125  
   126  	err := json.Unmarshal([]byte(out), &containers)
   127  	assert.Assert(c, err == nil, "Error inspecting the container: %s", err)
   128  	assert.Equal(c, len(containers), 1)
   129  
   130  	cont := containers[0]
   131  	assert.Assert(c, cont.HostConfig != nil, "Expected HostConfig, got none")
   132  	assert.Equal(c, len(cont.HostConfig.PortBindings), 65535)
   133  
   134  	for k, v := range cont.HostConfig.PortBindings {
   135  		assert.Equal(c, len(v), 1)
   136  		assert.Equal(c, k.Port(), v[0].HostPort, fmt.Sprintf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
   137  	}
   138  }
   139  
   140  // "test123" should be printed by docker create + start
   141  func (s *DockerCLICreateSuite) TestCreateEchoStdout(c *testing.T) {
   142  	containerID := cli.DockerCmd(c, "create", "busybox", "echo", "test123").Stdout()
   143  	containerID = strings.TrimSpace(containerID)
   144  
   145  	out := cli.DockerCmd(c, "start", "-ai", containerID).Combined()
   146  	assert.Equal(c, out, "test123\n", "container should've printed 'test123', got %q", out)
   147  }
   148  
   149  func (s *DockerCLICreateSuite) TestCreateVolumesCreated(c *testing.T) {
   150  	testRequires(c, testEnv.IsLocalDaemon)
   151  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
   152  
   153  	const name = "test_create_volume"
   154  	cli.DockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox")
   155  
   156  	dir, err := inspectMountSourceField(name, prefix+slash+"foo")
   157  	assert.Assert(c, err == nil, "Error getting volume host path: %q", err)
   158  
   159  	if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
   160  		c.Fatalf("Volume was not created")
   161  	}
   162  	if err != nil {
   163  		c.Fatalf("Error statting volume host path: %q", err)
   164  	}
   165  }
   166  
   167  func (s *DockerCLICreateSuite) TestCreateLabels(c *testing.T) {
   168  	const name = "test_create_labels"
   169  	expected := map[string]string{"k1": "v1", "k2": "v2"}
   170  	cli.DockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
   171  
   172  	actual := make(map[string]string)
   173  	inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
   174  
   175  	if !reflect.DeepEqual(expected, actual) {
   176  		c.Fatalf("Expected %s got %s", expected, actual)
   177  	}
   178  }
   179  
   180  func (s *DockerCLICreateSuite) TestCreateLabelFromImage(c *testing.T) {
   181  	imageName := "testcreatebuildlabel"
   182  	buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
   183  		LABEL k1=v1 k2=v2`))
   184  
   185  	const name = "test_create_labels_from_image"
   186  	expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
   187  	cli.DockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
   188  
   189  	actual := make(map[string]string)
   190  	inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
   191  
   192  	if !reflect.DeepEqual(expected, actual) {
   193  		c.Fatalf("Expected %s got %s", expected, actual)
   194  	}
   195  }
   196  
   197  func (s *DockerCLICreateSuite) TestCreateHostnameWithNumber(c *testing.T) {
   198  	image := "busybox"
   199  	// Busybox on Windows does not implement hostname command
   200  	if testEnv.DaemonInfo.OSType == "windows" {
   201  		image = testEnv.PlatformDefaults.BaseImage
   202  	}
   203  	out := cli.DockerCmd(c, "run", "-h", "web.0", image, "hostname").Combined()
   204  	assert.Equal(c, strings.TrimSpace(out), "web.0", "hostname not set, expected `web.0`, got: %s", out)
   205  }
   206  
   207  func (s *DockerCLICreateSuite) TestCreateRM(c *testing.T) {
   208  	// Test to make sure we can 'rm' a new container that is in
   209  	// "Created" state, and has ever been run. Test "rm -f" too.
   210  
   211  	// create a container
   212  	cID := cli.DockerCmd(c, "create", "busybox").Stdout()
   213  	cID = strings.TrimSpace(cID)
   214  	cli.DockerCmd(c, "rm", cID)
   215  
   216  	// Now do it again so we can "rm -f" this time
   217  	cID = cli.DockerCmd(c, "create", "busybox").Stdout()
   218  	cID = strings.TrimSpace(cID)
   219  	cli.DockerCmd(c, "rm", "-f", cID)
   220  }
   221  
   222  func (s *DockerCLICreateSuite) TestCreateModeIpcContainer(c *testing.T) {
   223  	// Uses Linux specific functionality (--ipc)
   224  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
   225  
   226  	id := cli.DockerCmd(c, "create", "busybox").Stdout()
   227  	id = strings.TrimSpace(id)
   228  
   229  	cli.DockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
   230  }
   231  
   232  func (s *DockerCLICreateSuite) TestCreateByImageID(c *testing.T) {
   233  	imageName := "testcreatebyimageid"
   234  	buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
   235  		MAINTAINER dockerio`))
   236  	imageID := getIDByName(c, imageName)
   237  	truncatedImageID := stringid.TruncateID(imageID)
   238  
   239  	cli.DockerCmd(c, "create", imageID)
   240  	cli.DockerCmd(c, "create", truncatedImageID)
   241  
   242  	// Ensure this fails
   243  	out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
   244  	if exit == 0 {
   245  		c.Fatalf("expected non-zero exit code; received %d", exit)
   246  	}
   247  
   248  	if expected := "invalid reference format"; !strings.Contains(out, expected) {
   249  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
   250  	}
   251  
   252  	if i := strings.IndexRune(imageID, ':'); i >= 0 {
   253  		imageID = imageID[i+1:]
   254  	}
   255  	out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", imageID))
   256  	if exit == 0 {
   257  		c.Fatalf("expected non-zero exit code; received %d", exit)
   258  	}
   259  
   260  	if expected := "Unable to find image"; !strings.Contains(out, expected) {
   261  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
   262  	}
   263  }
   264  
   265  func (s *DockerCLICreateSuite) TestCreateStopSignal(c *testing.T) {
   266  	const name = "test_create_stop_signal"
   267  	cli.DockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
   268  
   269  	res := inspectFieldJSON(c, name, "Config.StopSignal")
   270  	assert.Assert(c, strings.Contains(res, "9"))
   271  }
   272  
   273  func (s *DockerCLICreateSuite) TestCreateWithWorkdir(c *testing.T) {
   274  	const name = "foo"
   275  
   276  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
   277  	dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
   278  
   279  	cli.DockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
   280  	// Windows does not create the workdir until the container is started
   281  	if testEnv.DaemonInfo.OSType == "windows" {
   282  		cli.DockerCmd(c, "start", name)
   283  		if testEnv.DaemonInfo.Isolation.IsHyperV() {
   284  			// Hyper-V isolated containers do not allow file-operations on a
   285  			// running container. This test currently uses `docker cp` to verify
   286  			// that the WORKDIR was automatically created, which cannot be done
   287  			// while the container is running.
   288  			cli.DockerCmd(c, "stop", name)
   289  		}
   290  	}
   291  	// TODO: rewrite this test to not use `docker cp` for verifying that the WORKDIR was created
   292  	cli.DockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
   293  }
   294  
   295  func (s *DockerCLICreateSuite) TestCreateWithInvalidLogOpts(c *testing.T) {
   296  	const name = "test-invalidate-log-opts"
   297  	out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
   298  	assert.ErrorContains(c, err, "")
   299  	assert.Assert(c, strings.Contains(out, "unknown log opt"))
   300  	assert.Assert(c, is.Contains(out, "unknown log opt"))
   301  
   302  	out = cli.DockerCmd(c, "ps", "-a").Stdout()
   303  	assert.Assert(c, !strings.Contains(out, name))
   304  }
   305  
   306  // #20972
   307  func (s *DockerCLICreateSuite) TestCreate64ByteHexID(c *testing.T) {
   308  	out := inspectField(c, "busybox", "Id")
   309  	imageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:")
   310  
   311  	cli.DockerCmd(c, "create", imageID)
   312  }
   313  
   314  // Test case for #23498
   315  func (s *DockerCLICreateSuite) TestCreateUnsetEntrypoint(c *testing.T) {
   316  	const name = "test-entrypoint"
   317  	dockerfile := `FROM busybox
   318  ADD entrypoint.sh /entrypoint.sh
   319  RUN chmod 755 /entrypoint.sh
   320  ENTRYPOINT ["/entrypoint.sh"]
   321  CMD echo foobar`
   322  
   323  	ctx := fakecontext.New(c, "",
   324  		fakecontext.WithDockerfile(dockerfile),
   325  		fakecontext.WithFiles(map[string]string{
   326  			"entrypoint.sh": `#!/bin/sh
   327  echo "I am an entrypoint"
   328  exec "$@"`,
   329  		}))
   330  	defer ctx.Close()
   331  
   332  	cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
   333  
   334  	out := cli.DockerCmd(c, "create", "--entrypoint=", name, "echo", "foo").Combined()
   335  	id := strings.TrimSpace(out)
   336  	assert.Assert(c, id != "")
   337  	out = cli.DockerCmd(c, "start", "-a", id).Combined()
   338  	assert.Equal(c, strings.TrimSpace(out), "foo")
   339  }
   340  
   341  // #22471
   342  func (s *DockerCLICreateSuite) TestCreateStopTimeout(c *testing.T) {
   343  	name1 := "test_create_stop_timeout_1"
   344  	cli.DockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
   345  
   346  	res := inspectFieldJSON(c, name1, "Config.StopTimeout")
   347  	assert.Assert(c, strings.Contains(res, "15"))
   348  	name2 := "test_create_stop_timeout_2"
   349  	cli.DockerCmd(c, "create", "--name", name2, "busybox")
   350  
   351  	res = inspectFieldJSON(c, name2, "Config.StopTimeout")
   352  	assert.Assert(c, strings.Contains(res, "null"))
   353  }