github.com/lazyboychen7/engine@v17.12.1-ce-rc2+incompatible/integration-cli/docker_cli_create_test.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  	"reflect"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/docker/docker/integration-cli/checker"
    13  	"github.com/docker/docker/integration-cli/cli"
    14  	"github.com/docker/docker/integration-cli/cli/build"
    15  	"github.com/docker/docker/integration-cli/cli/build/fakecontext"
    16  	"github.com/docker/docker/pkg/stringid"
    17  	"github.com/docker/go-connections/nat"
    18  	"github.com/go-check/check"
    19  	"github.com/gotestyourself/gotestyourself/icmd"
    20  )
    21  
    22  // Make sure we can create a simple container with some args
    23  func (s *DockerSuite) TestCreateArgs(c *check.C) {
    24  	// Intentionally clear entrypoint, as the Windows busybox image needs an entrypoint, which breaks this test
    25  	out, _ := dockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags")
    26  
    27  	cleanedContainerID := strings.TrimSpace(out)
    28  
    29  	out, _ = dockerCmd(c, "inspect", cleanedContainerID)
    30  
    31  	containers := []struct {
    32  		ID      string
    33  		Created time.Time
    34  		Path    string
    35  		Args    []string
    36  		Image   string
    37  	}{}
    38  
    39  	err := json.Unmarshal([]byte(out), &containers)
    40  	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
    41  	c.Assert(containers, checker.HasLen, 1)
    42  
    43  	cont := containers[0]
    44  	c.Assert(string(cont.Path), checker.Equals, "command", check.Commentf("Unexpected container path. Expected command, received: %s", cont.Path))
    45  
    46  	b := false
    47  	expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"}
    48  	for i, arg := range expected {
    49  		if arg != cont.Args[i] {
    50  			b = true
    51  			break
    52  		}
    53  	}
    54  	if len(cont.Args) != len(expected) || b {
    55  		c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args)
    56  	}
    57  
    58  }
    59  
    60  // Make sure we can grow the container's rootfs at creation time.
    61  func (s *DockerSuite) TestCreateGrowRootfs(c *check.C) {
    62  	// Windows and Devicemapper support growing the rootfs
    63  	if testEnv.DaemonPlatform() != "windows" {
    64  		testRequires(c, Devicemapper)
    65  	}
    66  	out, _ := dockerCmd(c, "create", "--storage-opt", "size=120G", "busybox")
    67  
    68  	cleanedContainerID := strings.TrimSpace(out)
    69  
    70  	inspectOut := inspectField(c, cleanedContainerID, "HostConfig.StorageOpt")
    71  	c.Assert(inspectOut, checker.Equals, "map[size:120G]")
    72  }
    73  
    74  // Make sure we cannot shrink the container's rootfs at creation time.
    75  func (s *DockerSuite) TestCreateShrinkRootfs(c *check.C) {
    76  	testRequires(c, Devicemapper)
    77  
    78  	// Ensure this fails because of the defaultBaseFsSize is 10G
    79  	out, _, err := dockerCmdWithError("create", "--storage-opt", "size=5G", "busybox")
    80  	c.Assert(err, check.NotNil, check.Commentf(out))
    81  	c.Assert(out, checker.Contains, "Container size cannot be smaller than")
    82  }
    83  
    84  // Make sure we can set hostconfig options too
    85  func (s *DockerSuite) TestCreateHostConfig(c *check.C) {
    86  	out, _ := dockerCmd(c, "create", "-P", "busybox", "echo")
    87  
    88  	cleanedContainerID := strings.TrimSpace(out)
    89  
    90  	out, _ = dockerCmd(c, "inspect", cleanedContainerID)
    91  
    92  	containers := []struct {
    93  		HostConfig *struct {
    94  			PublishAllPorts bool
    95  		}
    96  	}{}
    97  
    98  	err := json.Unmarshal([]byte(out), &containers)
    99  	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
   100  	c.Assert(containers, checker.HasLen, 1)
   101  
   102  	cont := containers[0]
   103  	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
   104  	c.Assert(cont.HostConfig.PublishAllPorts, check.NotNil, check.Commentf("Expected PublishAllPorts, got false"))
   105  }
   106  
   107  func (s *DockerSuite) TestCreateWithPortRange(c *check.C) {
   108  	out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo")
   109  
   110  	cleanedContainerID := strings.TrimSpace(out)
   111  
   112  	out, _ = dockerCmd(c, "inspect", cleanedContainerID)
   113  
   114  	containers := []struct {
   115  		HostConfig *struct {
   116  			PortBindings map[nat.Port][]nat.PortBinding
   117  		}
   118  	}{}
   119  	err := json.Unmarshal([]byte(out), &containers)
   120  	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
   121  	c.Assert(containers, checker.HasLen, 1)
   122  
   123  	cont := containers[0]
   124  
   125  	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
   126  	c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 4, check.Commentf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)))
   127  
   128  	for k, v := range cont.HostConfig.PortBindings {
   129  		c.Assert(v, checker.HasLen, 1, check.Commentf("Expected 1 ports binding, for the port  %s but found %s", k, v))
   130  		c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
   131  
   132  	}
   133  
   134  }
   135  
   136  func (s *DockerSuite) TestCreateWithLargePortRange(c *check.C) {
   137  	out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo")
   138  
   139  	cleanedContainerID := strings.TrimSpace(out)
   140  
   141  	out, _ = dockerCmd(c, "inspect", cleanedContainerID)
   142  
   143  	containers := []struct {
   144  		HostConfig *struct {
   145  			PortBindings map[nat.Port][]nat.PortBinding
   146  		}
   147  	}{}
   148  
   149  	err := json.Unmarshal([]byte(out), &containers)
   150  	c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err))
   151  	c.Assert(containers, checker.HasLen, 1)
   152  
   153  	cont := containers[0]
   154  	c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none"))
   155  	c.Assert(cont.HostConfig.PortBindings, checker.HasLen, 65535)
   156  
   157  	for k, v := range cont.HostConfig.PortBindings {
   158  		c.Assert(v, checker.HasLen, 1)
   159  		c.Assert(k.Port(), checker.Equals, v[0].HostPort, check.Commentf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort))
   160  	}
   161  
   162  }
   163  
   164  // "test123" should be printed by docker create + start
   165  func (s *DockerSuite) TestCreateEchoStdout(c *check.C) {
   166  	out, _ := dockerCmd(c, "create", "busybox", "echo", "test123")
   167  
   168  	cleanedContainerID := strings.TrimSpace(out)
   169  
   170  	out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID)
   171  	c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out))
   172  
   173  }
   174  
   175  func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) {
   176  	testRequires(c, SameHostDaemon)
   177  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
   178  
   179  	name := "test_create_volume"
   180  	dockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox")
   181  
   182  	dir, err := inspectMountSourceField(name, prefix+slash+"foo")
   183  	c.Assert(err, check.IsNil, check.Commentf("Error getting volume host path: %q", err))
   184  
   185  	if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
   186  		c.Fatalf("Volume was not created")
   187  	}
   188  	if err != nil {
   189  		c.Fatalf("Error statting volume host path: %q", err)
   190  	}
   191  
   192  }
   193  
   194  func (s *DockerSuite) TestCreateLabels(c *check.C) {
   195  	name := "test_create_labels"
   196  	expected := map[string]string{"k1": "v1", "k2": "v2"}
   197  	dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox")
   198  
   199  	actual := make(map[string]string)
   200  	inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
   201  
   202  	if !reflect.DeepEqual(expected, actual) {
   203  		c.Fatalf("Expected %s got %s", expected, actual)
   204  	}
   205  }
   206  
   207  func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) {
   208  	imageName := "testcreatebuildlabel"
   209  	buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
   210  		LABEL k1=v1 k2=v2`))
   211  
   212  	name := "test_create_labels_from_image"
   213  	expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"}
   214  	dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName)
   215  
   216  	actual := make(map[string]string)
   217  	inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual)
   218  
   219  	if !reflect.DeepEqual(expected, actual) {
   220  		c.Fatalf("Expected %s got %s", expected, actual)
   221  	}
   222  }
   223  
   224  func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) {
   225  	image := "busybox"
   226  	// Busybox on Windows does not implement hostname command
   227  	if testEnv.DaemonPlatform() == "windows" {
   228  		image = testEnv.MinimalBaseImage()
   229  	}
   230  	out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname")
   231  	c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out))
   232  
   233  }
   234  
   235  func (s *DockerSuite) TestCreateRM(c *check.C) {
   236  	// Test to make sure we can 'rm' a new container that is in
   237  	// "Created" state, and has ever been run. Test "rm -f" too.
   238  
   239  	// create a container
   240  	out, _ := dockerCmd(c, "create", "busybox")
   241  	cID := strings.TrimSpace(out)
   242  
   243  	dockerCmd(c, "rm", cID)
   244  
   245  	// Now do it again so we can "rm -f" this time
   246  	out, _ = dockerCmd(c, "create", "busybox")
   247  
   248  	cID = strings.TrimSpace(out)
   249  	dockerCmd(c, "rm", "-f", cID)
   250  }
   251  
   252  func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) {
   253  	// Uses Linux specific functionality (--ipc)
   254  	testRequires(c, DaemonIsLinux, SameHostDaemon)
   255  
   256  	out, _ := dockerCmd(c, "create", "busybox")
   257  	id := strings.TrimSpace(out)
   258  
   259  	dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox")
   260  }
   261  
   262  func (s *DockerSuite) TestCreateByImageID(c *check.C) {
   263  	imageName := "testcreatebyimageid"
   264  	buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox
   265  		MAINTAINER dockerio`))
   266  	imageID := getIDByName(c, imageName)
   267  	truncatedImageID := stringid.TruncateID(imageID)
   268  
   269  	dockerCmd(c, "create", imageID)
   270  	dockerCmd(c, "create", truncatedImageID)
   271  
   272  	// Ensure this fails
   273  	out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID))
   274  	if exit == 0 {
   275  		c.Fatalf("expected non-zero exit code; received %d", exit)
   276  	}
   277  
   278  	if expected := "invalid reference format"; !strings.Contains(out, expected) {
   279  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
   280  	}
   281  
   282  	if i := strings.IndexRune(imageID, ':'); i >= 0 {
   283  		imageID = imageID[i+1:]
   284  	}
   285  	out, exit, _ = dockerCmdWithError("create", fmt.Sprintf("%s:%s", "wrongimage", imageID))
   286  	if exit == 0 {
   287  		c.Fatalf("expected non-zero exit code; received %d", exit)
   288  	}
   289  
   290  	if expected := "Unable to find image"; !strings.Contains(out, expected) {
   291  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
   292  	}
   293  }
   294  
   295  func (s *DockerTrustSuite) TestTrustedCreate(c *check.C) {
   296  	repoName := s.setupTrustedImage(c, "trusted-create")
   297  
   298  	// Try create
   299  	cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
   300  	cli.DockerCmd(c, "rmi", repoName)
   301  
   302  	// Try untrusted create to ensure we pushed the tag to the registry
   303  	cli.Docker(cli.Args("create", "--disable-content-trust=true", repoName)).Assert(c, SuccessDownloadedOnStderr)
   304  }
   305  
   306  func (s *DockerTrustSuite) TestUntrustedCreate(c *check.C) {
   307  	repoName := fmt.Sprintf("%v/dockercliuntrusted/createtest", privateRegistryURL)
   308  	withTagName := fmt.Sprintf("%s:latest", repoName)
   309  	// tag the image and upload it to the private registry
   310  	cli.DockerCmd(c, "tag", "busybox", withTagName)
   311  	cli.DockerCmd(c, "push", withTagName)
   312  	cli.DockerCmd(c, "rmi", withTagName)
   313  
   314  	// Try trusted create on untrusted tag
   315  	cli.Docker(cli.Args("create", withTagName), trustedCmd).Assert(c, icmd.Expected{
   316  		ExitCode: 1,
   317  		Err:      fmt.Sprintf("does not have trust data for %s", repoName),
   318  	})
   319  }
   320  
   321  func (s *DockerTrustSuite) TestTrustedIsolatedCreate(c *check.C) {
   322  	repoName := s.setupTrustedImage(c, "trusted-isolated-create")
   323  
   324  	// Try create
   325  	cli.Docker(cli.Args("--config", "/tmp/docker-isolated-create", "create", repoName), trustedCmd).Assert(c, SuccessTagging)
   326  	defer os.RemoveAll("/tmp/docker-isolated-create")
   327  
   328  	cli.DockerCmd(c, "rmi", repoName)
   329  }
   330  
   331  func (s *DockerTrustSuite) TestTrustedCreateFromBadTrustServer(c *check.C) {
   332  	repoName := fmt.Sprintf("%v/dockerclievilcreate/trusted:latest", privateRegistryURL)
   333  	evilLocalConfigDir, err := ioutil.TempDir("", "evilcreate-local-config-dir")
   334  	c.Assert(err, check.IsNil)
   335  
   336  	// tag the image and upload it to the private registry
   337  	cli.DockerCmd(c, "tag", "busybox", repoName)
   338  	cli.Docker(cli.Args("push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
   339  	cli.DockerCmd(c, "rmi", repoName)
   340  
   341  	// Try create
   342  	cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, SuccessTagging)
   343  	cli.DockerCmd(c, "rmi", repoName)
   344  
   345  	// Kill the notary server, start a new "evil" one.
   346  	s.not.Close()
   347  	s.not, err = newTestNotary(c)
   348  	c.Assert(err, check.IsNil)
   349  
   350  	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
   351  	// tag an image and upload it to the private registry
   352  	cli.DockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
   353  
   354  	// Push up to the new server
   355  	cli.Docker(cli.Args("--config", evilLocalConfigDir, "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
   356  
   357  	// Now, try creating with the original client from this new trust server. This should fail because the new root is invalid.
   358  	cli.Docker(cli.Args("create", repoName), trustedCmd).Assert(c, icmd.Expected{
   359  		ExitCode: 1,
   360  		Err:      "could not rotate trust to a new trusted root",
   361  	})
   362  }
   363  
   364  func (s *DockerSuite) TestCreateStopSignal(c *check.C) {
   365  	name := "test_create_stop_signal"
   366  	dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox")
   367  
   368  	res := inspectFieldJSON(c, name, "Config.StopSignal")
   369  	c.Assert(res, checker.Contains, "9")
   370  
   371  }
   372  
   373  func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) {
   374  	name := "foo"
   375  
   376  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
   377  	dir := prefix + slash + "home" + slash + "foo" + slash + "bar"
   378  
   379  	dockerCmd(c, "create", "--name", name, "-w", dir, "busybox")
   380  	// Windows does not create the workdir until the container is started
   381  	if testEnv.DaemonPlatform() == "windows" {
   382  		dockerCmd(c, "start", name)
   383  	}
   384  	dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp")
   385  }
   386  
   387  func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) {
   388  	name := "test-invalidate-log-opts"
   389  	out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox")
   390  	c.Assert(err, checker.NotNil)
   391  	c.Assert(out, checker.Contains, "unknown log opt")
   392  
   393  	out, _ = dockerCmd(c, "ps", "-a")
   394  	c.Assert(out, checker.Not(checker.Contains), name)
   395  }
   396  
   397  // #20972
   398  func (s *DockerSuite) TestCreate64ByteHexID(c *check.C) {
   399  	out := inspectField(c, "busybox", "Id")
   400  	imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:")
   401  
   402  	dockerCmd(c, "create", imageID)
   403  }
   404  
   405  // Test case for #23498
   406  func (s *DockerSuite) TestCreateUnsetEntrypoint(c *check.C) {
   407  	name := "test-entrypoint"
   408  	dockerfile := `FROM busybox
   409  ADD entrypoint.sh /entrypoint.sh
   410  RUN chmod 755 /entrypoint.sh
   411  ENTRYPOINT ["/entrypoint.sh"]
   412  CMD echo foobar`
   413  
   414  	ctx := fakecontext.New(c, "",
   415  		fakecontext.WithDockerfile(dockerfile),
   416  		fakecontext.WithFiles(map[string]string{
   417  			"entrypoint.sh": `#!/bin/sh
   418  echo "I am an entrypoint"
   419  exec "$@"`,
   420  		}))
   421  	defer ctx.Close()
   422  
   423  	cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
   424  
   425  	out := cli.DockerCmd(c, "create", "--entrypoint=", name, "echo", "foo").Combined()
   426  	id := strings.TrimSpace(out)
   427  	c.Assert(id, check.Not(check.Equals), "")
   428  	out = cli.DockerCmd(c, "start", "-a", id).Combined()
   429  	c.Assert(strings.TrimSpace(out), check.Equals, "foo")
   430  }
   431  
   432  // #22471
   433  func (s *DockerSuite) TestCreateStopTimeout(c *check.C) {
   434  	name1 := "test_create_stop_timeout_1"
   435  	dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox")
   436  
   437  	res := inspectFieldJSON(c, name1, "Config.StopTimeout")
   438  	c.Assert(res, checker.Contains, "15")
   439  
   440  	name2 := "test_create_stop_timeout_2"
   441  	dockerCmd(c, "create", "--name", name2, "busybox")
   442  
   443  	res = inspectFieldJSON(c, name2, "Config.StopTimeout")
   444  	c.Assert(res, checker.Contains, "null")
   445  }