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