github.com/uppal0016/docker_new@v0.0.0-20240123060250-1c98be13ac2c/integration-cli/docker_cli_run_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net"
     9  	"os"
    10  	"os/exec"
    11  	"path"
    12  	"path/filepath"
    13  	"reflect"
    14  	"regexp"
    15  	"sort"
    16  	"strconv"
    17  	"strings"
    18  	"sync"
    19  	"time"
    20  
    21  	"github.com/docker/docker/pkg/integration/checker"
    22  	"github.com/docker/docker/pkg/mount"
    23  	"github.com/docker/docker/pkg/stringutils"
    24  	"github.com/docker/docker/runconfig"
    25  	"github.com/docker/go-connections/nat"
    26  	"github.com/docker/libnetwork/netutils"
    27  	"github.com/docker/libnetwork/resolvconf"
    28  	"github.com/go-check/check"
    29  	libcontainerUser "github.com/opencontainers/runc/libcontainer/user"
    30  )
    31  
    32  // "test123" should be printed by docker run
    33  func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
    34  	out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
    35  	if out != "test123\n" {
    36  		c.Fatalf("container should've printed 'test123', got '%s'", out)
    37  	}
    38  }
    39  
    40  // "test" should be printed
    41  func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
    42  	out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
    43  	if out != "test\n" {
    44  		c.Errorf("container should've printed 'test'")
    45  	}
    46  }
    47  
    48  // docker run should not leak file descriptors. This test relies on Unix
    49  // specific functionality and cannot run on Windows.
    50  func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
    51  	testRequires(c, DaemonIsLinux)
    52  	out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
    53  
    54  	// normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
    55  	if out != "0  1  2  3\n" {
    56  		c.Errorf("container should've printed '0  1  2  3', not: %s", out)
    57  	}
    58  }
    59  
    60  // it should be possible to lookup Google DNS
    61  // this will fail when Internet access is unavailable
    62  func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
    63  	testRequires(c, Network, NotArm)
    64  	image := DefaultImage
    65  	if daemonPlatform == "windows" {
    66  		// nslookup isn't present in Windows busybox. Is built-in.
    67  		image = WindowsBaseImage
    68  	}
    69  	dockerCmd(c, "run", image, "nslookup", "google.com")
    70  }
    71  
    72  // the exit code should be 0
    73  func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
    74  	dockerCmd(c, "run", "busybox", "true")
    75  }
    76  
    77  // the exit code should be 1
    78  func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
    79  	_, exitCode, err := dockerCmdWithError("run", "busybox", "false")
    80  	c.Assert(err, checker.NotNil)
    81  	c.Assert(exitCode, checker.Equals, 1)
    82  }
    83  
    84  // it should be possible to pipe in data via stdin to a process running in a container
    85  func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
    86  	// TODO Windows: This needs some work to make compatible.
    87  	testRequires(c, DaemonIsLinux)
    88  	runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat")
    89  	runCmd.Stdin = strings.NewReader("blahblah")
    90  	out, _, _, err := runCommandWithStdoutStderr(runCmd)
    91  	if err != nil {
    92  		c.Fatalf("failed to run container: %v, output: %q", err, out)
    93  	}
    94  
    95  	out = strings.TrimSpace(out)
    96  	dockerCmd(c, "wait", out)
    97  
    98  	logsOut, _ := dockerCmd(c, "logs", out)
    99  
   100  	containerLogs := strings.TrimSpace(logsOut)
   101  	if containerLogs != "blahblah" {
   102  		c.Errorf("logs didn't print the container's logs %s", containerLogs)
   103  	}
   104  
   105  	dockerCmd(c, "rm", out)
   106  }
   107  
   108  // the container's ID should be printed when starting a container in detached mode
   109  func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
   110  	out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
   111  
   112  	out = strings.TrimSpace(out)
   113  	dockerCmd(c, "wait", out)
   114  
   115  	rmOut, _ := dockerCmd(c, "rm", out)
   116  
   117  	rmOut = strings.TrimSpace(rmOut)
   118  	if rmOut != out {
   119  		c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
   120  	}
   121  }
   122  
   123  // the working directory should be set correctly
   124  func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
   125  	// TODO Windows: There's a Windows bug stopping this from working.
   126  	testRequires(c, DaemonIsLinux)
   127  	dir := "/root"
   128  	image := "busybox"
   129  	if daemonPlatform == "windows" {
   130  		dir = `/windows`
   131  		image = WindowsBaseImage
   132  	}
   133  
   134  	// First with -w
   135  	out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd")
   136  	out = strings.TrimSpace(out)
   137  	if out != dir {
   138  		c.Errorf("-w failed to set working directory")
   139  	}
   140  
   141  	// Then with --workdir
   142  	out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd")
   143  	out = strings.TrimSpace(out)
   144  	if out != dir {
   145  		c.Errorf("--workdir failed to set working directory")
   146  	}
   147  }
   148  
   149  // pinging Google's DNS resolver should fail when we disable the networking
   150  func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
   151  	count := "-c"
   152  	image := "busybox"
   153  	if daemonPlatform == "windows" {
   154  		count = "-n"
   155  		image = WindowsBaseImage
   156  	}
   157  
   158  	// First using the long form --net
   159  	out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8")
   160  	if err != nil && exitCode != 1 {
   161  		c.Fatal(out, err)
   162  	}
   163  	if exitCode != 1 {
   164  		c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
   165  	}
   166  }
   167  
   168  //test --link use container name to link target
   169  func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
   170  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   171  	// settings are not populated back yet on inspect.
   172  	testRequires(c, DaemonIsLinux)
   173  	dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
   174  
   175  	ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress")
   176  
   177  	out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
   178  	if !strings.Contains(out, ip+"	test") {
   179  		c.Fatalf("use a container name to link target failed")
   180  	}
   181  }
   182  
   183  //test --link use container id to link target
   184  func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
   185  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   186  	// settings are not populated back yet on inspect.
   187  	testRequires(c, DaemonIsLinux)
   188  	cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
   189  
   190  	cID = strings.TrimSpace(cID)
   191  	ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress")
   192  
   193  	out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
   194  	if !strings.Contains(out, ip+"	test") {
   195  		c.Fatalf("use a container id to link target failed")
   196  	}
   197  }
   198  
   199  func (s *DockerSuite) TestUserDefinedNetworkLinks(c *check.C) {
   200  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   201  	dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
   202  
   203  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
   204  	c.Assert(waitRun("first"), check.IsNil)
   205  
   206  	// run a container in user-defined network udlinkNet with a link for an existing container
   207  	// and a link for a container that doesn't exist
   208  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
   209  		"--link=third:bar", "busybox", "top")
   210  	c.Assert(waitRun("second"), check.IsNil)
   211  
   212  	// ping to first and its alias foo must succeed
   213  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   214  	c.Assert(err, check.IsNil)
   215  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   216  	c.Assert(err, check.IsNil)
   217  
   218  	// ping to third and its alias must fail
   219  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
   220  	c.Assert(err, check.NotNil)
   221  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
   222  	c.Assert(err, check.NotNil)
   223  
   224  	// start third container now
   225  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top")
   226  	c.Assert(waitRun("third"), check.IsNil)
   227  
   228  	// ping to third and its alias must succeed now
   229  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
   230  	c.Assert(err, check.IsNil)
   231  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
   232  	c.Assert(err, check.IsNil)
   233  }
   234  
   235  func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) {
   236  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   237  	dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
   238  
   239  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
   240  	c.Assert(waitRun("first"), check.IsNil)
   241  
   242  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
   243  		"busybox", "top")
   244  	c.Assert(waitRun("second"), check.IsNil)
   245  
   246  	// ping to first and its alias foo must succeed
   247  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   248  	c.Assert(err, check.IsNil)
   249  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   250  	c.Assert(err, check.IsNil)
   251  
   252  	// Restart first container
   253  	dockerCmd(c, "restart", "first")
   254  	c.Assert(waitRun("first"), check.IsNil)
   255  
   256  	// ping to first and its alias foo must still succeed
   257  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   258  	c.Assert(err, check.IsNil)
   259  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   260  	c.Assert(err, check.IsNil)
   261  
   262  	// Restart second container
   263  	dockerCmd(c, "restart", "second")
   264  	c.Assert(waitRun("second"), check.IsNil)
   265  
   266  	// ping to first and its alias foo must still succeed
   267  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   268  	c.Assert(err, check.IsNil)
   269  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   270  	c.Assert(err, check.IsNil)
   271  }
   272  
   273  func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *check.C) {
   274  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   275  
   276  	defaults := []string{"bridge", "host", "none"}
   277  	for _, net := range defaults {
   278  		out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top")
   279  		c.Assert(err, checker.NotNil)
   280  		c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error())
   281  	}
   282  }
   283  
   284  func (s *DockerSuite) TestUserDefinedNetworkAlias(c *check.C) {
   285  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   286  	dockerCmd(c, "network", "create", "-d", "bridge", "net1")
   287  
   288  	dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox", "top")
   289  	c.Assert(waitRun("first"), check.IsNil)
   290  
   291  	dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox", "top")
   292  	c.Assert(waitRun("second"), check.IsNil)
   293  
   294  	// ping to first and its network-scoped aliases
   295  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   296  	c.Assert(err, check.IsNil)
   297  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
   298  	c.Assert(err, check.IsNil)
   299  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
   300  	c.Assert(err, check.IsNil)
   301  
   302  	// Restart first container
   303  	dockerCmd(c, "restart", "first")
   304  	c.Assert(waitRun("first"), check.IsNil)
   305  
   306  	// ping to first and its network-scoped aliases must succeed
   307  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   308  	c.Assert(err, check.IsNil)
   309  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
   310  	c.Assert(err, check.IsNil)
   311  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
   312  	c.Assert(err, check.IsNil)
   313  }
   314  
   315  // Issue 9677.
   316  func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) {
   317  	out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true")
   318  	if err != nil {
   319  		if !strings.Contains(out, "flag provided but not defined: --exec-opt") { // no daemon (client-only)
   320  			c.Fatal(err, out)
   321  		}
   322  	}
   323  }
   324  
   325  // Regression test for #4979
   326  func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
   327  
   328  	var (
   329  		out      string
   330  		exitCode int
   331  	)
   332  
   333  	// Create a file in a volume
   334  	if daemonPlatform == "windows" {
   335  		out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, WindowsBaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`)
   336  	} else {
   337  		out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
   338  	}
   339  	if exitCode != 0 {
   340  		c.Fatal("1", out, exitCode)
   341  	}
   342  
   343  	// Read the file from another container using --volumes-from to access the volume in the second container
   344  	if daemonPlatform == "windows" {
   345  		out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", WindowsBaseImage, "cmd", "/c", `type c:\some\dir\file`)
   346  	} else {
   347  		out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
   348  	}
   349  	if exitCode != 0 {
   350  		c.Fatal("2", out, exitCode)
   351  	}
   352  }
   353  
   354  // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
   355  // But the volume call is just a normal volume, not a bind mount
   356  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
   357  	var (
   358  		dockerFile    string
   359  		containerPath string
   360  		cmd           string
   361  	)
   362  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   363  	// Windows does not support symlinks inside a volume path
   364  	testRequires(c, SameHostDaemon, DaemonIsLinux)
   365  	name := "test-volume-symlink"
   366  
   367  	dir, err := ioutil.TempDir("", name)
   368  	if err != nil {
   369  		c.Fatal(err)
   370  	}
   371  	defer os.RemoveAll(dir)
   372  
   373  	// In the case of Windows to Windows CI, if the machine is setup so that
   374  	// the temp directory is not the C: drive, this test is invalid and will
   375  	// not work.
   376  	if daemonPlatform == "windows" && strings.ToLower(dir[:1]) != "c" {
   377  		c.Skip("Requires TEMP to point to C: drive")
   378  	}
   379  
   380  	f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
   381  	if err != nil {
   382  		c.Fatal(err)
   383  	}
   384  	f.Close()
   385  
   386  	if daemonPlatform == "windows" {
   387  		dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", WindowsBaseImage, dir, dir)
   388  		containerPath = `c:\test\test`
   389  		cmd = "tasklist"
   390  	} else {
   391  		dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
   392  		containerPath = "/test/test"
   393  		cmd = "true"
   394  	}
   395  	if _, err := buildImage(name, dockerFile, false); err != nil {
   396  		c.Fatal(err)
   397  	}
   398  
   399  	dockerCmd(c, "run", "-v", containerPath, name, cmd)
   400  }
   401  
   402  // Volume path is a symlink in the container
   403  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *check.C) {
   404  	var (
   405  		dockerFile    string
   406  		containerPath string
   407  		cmd           string
   408  	)
   409  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   410  	// Windows does not support symlinks inside a volume path
   411  	testRequires(c, SameHostDaemon, DaemonIsLinux)
   412  	name := "test-volume-symlink2"
   413  
   414  	if daemonPlatform == "windows" {
   415  		dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", WindowsBaseImage, name, name)
   416  		containerPath = `c:\test\test`
   417  		cmd = "tasklist"
   418  	} else {
   419  		dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name)
   420  		containerPath = "/test/test"
   421  		cmd = "true"
   422  	}
   423  	if _, err := buildImage(name, dockerFile, false); err != nil {
   424  		c.Fatal(err)
   425  	}
   426  
   427  	dockerCmd(c, "run", "-v", containerPath, name, cmd)
   428  }
   429  
   430  func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
   431  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   432  	// Windows does not support read-only bind mounts.
   433  	testRequires(c, DaemonIsLinux)
   434  	if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
   435  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   436  	}
   437  }
   438  
   439  func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *check.C) {
   440  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   441  	// Windows does not support read-only bind mounts. Modified for when ro is supported.
   442  	testRequires(c, DaemonIsLinux)
   443  	var (
   444  		volumeDir string
   445  		fileInVol string
   446  	)
   447  	if daemonPlatform == "windows" {
   448  		volumeDir = `c:/test` // Forward-slash as using busybox
   449  		fileInVol = `c:/test/file`
   450  	} else {
   451  		testRequires(c, DaemonIsLinux)
   452  		volumeDir = "/test"
   453  		fileInVol = `/test/file`
   454  	}
   455  	dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
   456  
   457  	if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 {
   458  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   459  	}
   460  }
   461  
   462  // Regression test for #1201
   463  func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
   464  	var (
   465  		volumeDir string
   466  		fileInVol string
   467  	)
   468  	if daemonPlatform == "windows" {
   469  		volumeDir = `c:/test` // Forward-slash as using busybox
   470  		fileInVol = `c:/test/file`
   471  	} else {
   472  		volumeDir = "/test"
   473  		fileInVol = "/test/file"
   474  	}
   475  
   476  	dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
   477  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol)
   478  
   479  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) {
   480  		c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out)
   481  	}
   482  
   483  	dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol)
   484  }
   485  
   486  func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
   487  	// TODO Windows: This test cannot yet run on a Windows daemon as Windows does
   488  	// not support read-only bind mounts as at TP5
   489  	testRequires(c, DaemonIsLinux)
   490  	dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
   491  
   492  	// Expect this "rw" mode to be be ignored since the inherited volume is "ro"
   493  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
   494  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
   495  	}
   496  
   497  	dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
   498  
   499  	// Expect this to be read-only since both are "ro"
   500  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
   501  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
   502  	}
   503  }
   504  
   505  // Test for GH#10618
   506  func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
   507  	path1 := randomTmpDirPath("test1", daemonPlatform)
   508  	path2 := randomTmpDirPath("test2", daemonPlatform)
   509  
   510  	someplace := ":/someplace"
   511  	if daemonPlatform == "windows" {
   512  		// Windows requires that the source directory exists before calling HCS
   513  		testRequires(c, SameHostDaemon)
   514  		someplace = `:c:\someplace`
   515  		if err := os.MkdirAll(path1, 0755); err != nil {
   516  			c.Fatalf("Failed to create %s: %q", path1, err)
   517  		}
   518  		defer os.RemoveAll(path1)
   519  		if err := os.MkdirAll(path2, 0755); err != nil {
   520  			c.Fatalf("Failed to create %s: %q", path1, err)
   521  		}
   522  		defer os.RemoveAll(path2)
   523  	}
   524  	mountstr1 := path1 + someplace
   525  	mountstr2 := path2 + someplace
   526  
   527  	if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
   528  		c.Fatal("Expected error about duplicate mount definitions")
   529  	} else {
   530  		if !strings.Contains(out, "Duplicate mount point") {
   531  			c.Fatalf("Expected 'duplicate mount point' error, got %v", out)
   532  		}
   533  	}
   534  }
   535  
   536  // Test for #1351
   537  func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
   538  	prefix := ""
   539  	if daemonPlatform == "windows" {
   540  		prefix = `c:`
   541  	}
   542  	dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
   543  	dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo")
   544  }
   545  
   546  func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
   547  	prefix := ""
   548  	if daemonPlatform == "windows" {
   549  		prefix = `c:`
   550  	}
   551  	dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
   552  	dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar")
   553  	dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
   554  }
   555  
   556  // this tests verifies the ID format for the container
   557  func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
   558  	out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
   559  	if err != nil {
   560  		c.Fatal(err)
   561  	}
   562  	if exit != 0 {
   563  		c.Fatalf("expected exit code 0 received %d", exit)
   564  	}
   565  
   566  	match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
   567  	if err != nil {
   568  		c.Fatal(err)
   569  	}
   570  	if !match {
   571  		c.Fatalf("Invalid container ID: %s", out)
   572  	}
   573  }
   574  
   575  // Test that creating a container with a volume doesn't crash. Regression test for #995.
   576  func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
   577  	prefix := ""
   578  	if daemonPlatform == "windows" {
   579  		prefix = `c:`
   580  	}
   581  	dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true")
   582  }
   583  
   584  // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
   585  // Note that this bug happens only with symlinks with a target that starts with '/'.
   586  func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
   587  	// Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...)
   588  	testRequires(c, DaemonIsLinux)
   589  	image := "docker-test-createvolumewithsymlink"
   590  
   591  	buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
   592  	buildCmd.Stdin = strings.NewReader(`FROM busybox
   593  		RUN ln -s home /bar`)
   594  	buildCmd.Dir = workingDirectory
   595  	err := buildCmd.Run()
   596  	if err != nil {
   597  		c.Fatalf("could not build '%s': %v", image, err)
   598  	}
   599  
   600  	_, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
   601  	if err != nil || exitCode != 0 {
   602  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   603  	}
   604  
   605  	volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
   606  	c.Assert(err, checker.IsNil)
   607  
   608  	_, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink")
   609  	if err != nil || exitCode != 0 {
   610  		c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
   611  	}
   612  
   613  	_, err = os.Stat(volPath)
   614  	if !os.IsNotExist(err) {
   615  		c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
   616  	}
   617  }
   618  
   619  // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
   620  func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
   621  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   622  	// Windows does not support symlinks inside a volume path
   623  	testRequires(c, DaemonIsLinux)
   624  	name := "docker-test-volumesfromsymlinkpath"
   625  	prefix := ""
   626  	dfContents := `FROM busybox
   627  		RUN ln -s home /foo
   628  		VOLUME ["/foo/bar"]`
   629  
   630  	if daemonPlatform == "windows" {
   631  		prefix = `c:`
   632  		dfContents = `FROM ` + WindowsBaseImage + `
   633  	    RUN mkdir c:\home
   634  		RUN mklink /D c:\foo c:\home
   635  		VOLUME ["c:/foo/bar"]
   636  		ENTRYPOINT c:\windows\system32\cmd.exe`
   637  	}
   638  
   639  	buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
   640  	buildCmd.Stdin = strings.NewReader(dfContents)
   641  	buildCmd.Dir = workingDirectory
   642  	err := buildCmd.Run()
   643  	if err != nil {
   644  		c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
   645  	}
   646  
   647  	out, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name)
   648  	if err != nil || exitCode != 0 {
   649  		c.Fatalf("[run] (volume) err: %v, exitcode: %d, out: %s", err, exitCode, out)
   650  	}
   651  
   652  	_, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls "+prefix+"/foo | grep -q bar")
   653  	if err != nil || exitCode != 0 {
   654  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   655  	}
   656  }
   657  
   658  func (s *DockerSuite) TestRunExitCode(c *check.C) {
   659  	var (
   660  		exit int
   661  		err  error
   662  	)
   663  
   664  	_, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72")
   665  
   666  	if err == nil {
   667  		c.Fatal("should not have a non nil error")
   668  	}
   669  	if exit != 72 {
   670  		c.Fatalf("expected exit code 72 received %d", exit)
   671  	}
   672  }
   673  
   674  func (s *DockerSuite) TestRunUserDefaults(c *check.C) {
   675  	expected := "uid=0(root) gid=0(root)"
   676  	if daemonPlatform == "windows" {
   677  		expected = "uid=1000(ContainerAdministrator) gid=1000(ContainerAdministrator)"
   678  	}
   679  	out, _ := dockerCmd(c, "run", "busybox", "id")
   680  	if !strings.Contains(out, expected) {
   681  		c.Fatalf("expected '%s' got %s", expected, out)
   682  	}
   683  }
   684  
   685  func (s *DockerSuite) TestRunUserByName(c *check.C) {
   686  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   687  	// not support the use of -u
   688  	testRequires(c, DaemonIsLinux)
   689  	out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
   690  	if !strings.Contains(out, "uid=0(root) gid=0(root)") {
   691  		c.Fatalf("expected root user got %s", out)
   692  	}
   693  }
   694  
   695  func (s *DockerSuite) TestRunUserByID(c *check.C) {
   696  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   697  	// not support the use of -u
   698  	testRequires(c, DaemonIsLinux)
   699  	out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
   700  	if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
   701  		c.Fatalf("expected daemon user got %s", out)
   702  	}
   703  }
   704  
   705  func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
   706  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   707  	// not support the use of -u
   708  	testRequires(c, DaemonIsLinux, NotArm)
   709  	out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id")
   710  	if err == nil {
   711  		c.Fatal("No error, but must be.", out)
   712  	}
   713  	if !strings.Contains(out, libcontainerUser.ErrRange.Error()) {
   714  		c.Fatalf("expected error about uids range, got %s", out)
   715  	}
   716  }
   717  
   718  func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
   719  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   720  	// not support the use of -u
   721  	testRequires(c, DaemonIsLinux)
   722  	out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id")
   723  	if err == nil {
   724  		c.Fatal("No error, but must be.", out)
   725  	}
   726  	if !strings.Contains(out, libcontainerUser.ErrRange.Error()) {
   727  		c.Fatalf("expected error about uids range, got %s", out)
   728  	}
   729  }
   730  
   731  func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
   732  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   733  	// not support the use of -u
   734  	testRequires(c, DaemonIsLinux)
   735  	out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id")
   736  	if err != nil {
   737  		c.Fatal(err, out)
   738  	}
   739  	if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
   740  		c.Fatalf("expected daemon user got %s", out)
   741  	}
   742  }
   743  
   744  func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
   745  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   746  	// not support the use of -u
   747  	testRequires(c, DaemonIsLinux)
   748  	_, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id")
   749  	if err == nil {
   750  		c.Fatal("unknown user should cause container to fail")
   751  	}
   752  }
   753  
   754  func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
   755  	sleepTime := "2"
   756  	if daemonPlatform == "windows" {
   757  		sleepTime = "20" // Make more reliable on Windows
   758  	}
   759  	group := sync.WaitGroup{}
   760  	group.Add(2)
   761  
   762  	errChan := make(chan error, 2)
   763  	for i := 0; i < 2; i++ {
   764  		go func() {
   765  			defer group.Done()
   766  			_, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime)
   767  			errChan <- err
   768  		}()
   769  	}
   770  
   771  	group.Wait()
   772  	close(errChan)
   773  
   774  	for err := range errChan {
   775  		c.Assert(err, check.IsNil)
   776  	}
   777  }
   778  
   779  func (s *DockerSuite) TestRunEnvironment(c *check.C) {
   780  	// TODO Windows: Environment handling is different between Linux and
   781  	// Windows and this test relies currently on unix functionality.
   782  	testRequires(c, DaemonIsLinux)
   783  	cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
   784  	cmd.Env = append(os.Environ(),
   785  		"TRUE=false",
   786  		"TRICKY=tri\ncky\n",
   787  	)
   788  
   789  	out, _, err := runCommandWithOutput(cmd)
   790  	if err != nil {
   791  		c.Fatal(err, out)
   792  	}
   793  
   794  	actualEnv := strings.Split(strings.TrimSpace(out), "\n")
   795  	sort.Strings(actualEnv)
   796  
   797  	goodEnv := []string{
   798  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   799  		"HOSTNAME=testing",
   800  		"FALSE=true",
   801  		"TRUE=false",
   802  		"TRICKY=tri",
   803  		"cky",
   804  		"",
   805  		"HOME=/root",
   806  	}
   807  	sort.Strings(goodEnv)
   808  	if len(goodEnv) != len(actualEnv) {
   809  		c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
   810  	}
   811  	for i := range goodEnv {
   812  		if actualEnv[i] != goodEnv[i] {
   813  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   814  		}
   815  	}
   816  }
   817  
   818  func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
   819  	// TODO Windows: Environment handling is different between Linux and
   820  	// Windows and this test relies currently on unix functionality.
   821  	testRequires(c, DaemonIsLinux)
   822  
   823  	// Test to make sure that when we use -e on env vars that are
   824  	// not set in our local env that they're removed (if present) in
   825  	// the container
   826  
   827  	cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
   828  	cmd.Env = appendBaseEnv(true)
   829  
   830  	out, _, err := runCommandWithOutput(cmd)
   831  	if err != nil {
   832  		c.Fatal(err, out)
   833  	}
   834  
   835  	actualEnv := strings.Split(strings.TrimSpace(out), "\n")
   836  	sort.Strings(actualEnv)
   837  
   838  	goodEnv := []string{
   839  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   840  		"HOME=/root",
   841  	}
   842  	sort.Strings(goodEnv)
   843  	if len(goodEnv) != len(actualEnv) {
   844  		c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
   845  	}
   846  	for i := range goodEnv {
   847  		if actualEnv[i] != goodEnv[i] {
   848  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   849  		}
   850  	}
   851  }
   852  
   853  func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
   854  	// TODO Windows: Environment handling is different between Linux and
   855  	// Windows and this test relies currently on unix functionality.
   856  	testRequires(c, DaemonIsLinux)
   857  
   858  	// Test to make sure that when we use -e on env vars that are
   859  	// already in the env that we're overriding them
   860  
   861  	cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
   862  	cmd.Env = appendBaseEnv(true, "HOSTNAME=bar")
   863  
   864  	out, _, err := runCommandWithOutput(cmd)
   865  	if err != nil {
   866  		c.Fatal(err, out)
   867  	}
   868  
   869  	actualEnv := strings.Split(strings.TrimSpace(out), "\n")
   870  	sort.Strings(actualEnv)
   871  
   872  	goodEnv := []string{
   873  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   874  		"HOME=/root2",
   875  		"HOSTNAME=bar",
   876  	}
   877  	sort.Strings(goodEnv)
   878  	if len(goodEnv) != len(actualEnv) {
   879  		c.Fatalf("Wrong environment: should be %d variables, not %d: %q", len(goodEnv), len(actualEnv), strings.Join(actualEnv, ", "))
   880  	}
   881  	for i := range goodEnv {
   882  		if actualEnv[i] != goodEnv[i] {
   883  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   884  		}
   885  	}
   886  }
   887  
   888  func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
   889  	if daemonPlatform == "windows" {
   890  		// Windows busybox does not have ping. Use built in ping instead.
   891  		dockerCmd(c, "run", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1")
   892  	} else {
   893  		dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
   894  	}
   895  }
   896  
   897  func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
   898  	// TODO Windows: This is Linux specific as --link is not supported and
   899  	// this will be deprecated in favor of container networking model.
   900  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   901  	dockerCmd(c, "run", "--name", "linked", "busybox", "true")
   902  
   903  	_, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true")
   904  	if err == nil {
   905  		c.Fatal("Expected error")
   906  	}
   907  }
   908  
   909  // #7851 hostname outside container shows FQDN, inside only shortname
   910  // For testing purposes it is not required to set host's hostname directly
   911  // and use "--net=host" (as the original issue submitter did), as the same
   912  // codepath is executed with "docker run -h <hostname>".  Both were manually
   913  // tested, but this testcase takes the simpler path of using "run -h .."
   914  func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
   915  	// TODO Windows: -h is not yet functional.
   916  	testRequires(c, DaemonIsLinux)
   917  	out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
   918  	if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
   919  		c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
   920  	}
   921  }
   922  
   923  func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
   924  	// Not applicable for Windows as Windows daemon does not support
   925  	// the concept of --privileged, and mknod is a Unix concept.
   926  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   927  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   928  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   929  		c.Fatalf("expected output ok received %s", actual)
   930  	}
   931  }
   932  
   933  func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
   934  	// Not applicable for Windows as Windows daemon does not support
   935  	// the concept of --privileged, and mknod is a Unix concept.
   936  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   937  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   938  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   939  		c.Fatalf("expected output ok received %s", actual)
   940  	}
   941  }
   942  
   943  func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
   944  	// Not applicable for Windows as there is no concept of --cap-drop
   945  	testRequires(c, DaemonIsLinux)
   946  	out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls")
   947  	if err == nil {
   948  		c.Fatal(err, out)
   949  	}
   950  }
   951  
   952  func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
   953  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   954  	testRequires(c, DaemonIsLinux)
   955  	out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   956  
   957  	if err == nil {
   958  		c.Fatal(err, out)
   959  	}
   960  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   961  		c.Fatalf("expected output not ok received %s", actual)
   962  	}
   963  }
   964  
   965  func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
   966  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   967  	testRequires(c, DaemonIsLinux)
   968  	out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   969  
   970  	if err == nil {
   971  		c.Fatal(err, out)
   972  	}
   973  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   974  		c.Fatalf("expected output not ok received %s", actual)
   975  	}
   976  }
   977  
   978  func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
   979  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   980  	testRequires(c, DaemonIsLinux)
   981  	out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   982  	if err == nil {
   983  		c.Fatal(err, out)
   984  	}
   985  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   986  		c.Fatalf("expected output not ok received %s", actual)
   987  	}
   988  }
   989  
   990  func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
   991  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   992  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   993  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   994  
   995  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   996  		c.Fatalf("expected output ok received %s", actual)
   997  	}
   998  }
   999  
  1000  func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
  1001  	// Not applicable for Windows as there is no concept of --cap-add
  1002  	testRequires(c, DaemonIsLinux)
  1003  	out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls")
  1004  	if err == nil {
  1005  		c.Fatal(err, out)
  1006  	}
  1007  }
  1008  
  1009  func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
  1010  	// Not applicable for Windows as there is no concept of --cap-add
  1011  	testRequires(c, DaemonIsLinux)
  1012  	out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  1013  
  1014  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  1015  		c.Fatalf("expected output ok received %s", actual)
  1016  	}
  1017  }
  1018  
  1019  func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
  1020  	// Not applicable for Windows as there is no concept of --cap-add
  1021  	testRequires(c, DaemonIsLinux)
  1022  	out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  1023  
  1024  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  1025  		c.Fatalf("expected output ok received %s", actual)
  1026  	}
  1027  }
  1028  
  1029  func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
  1030  	// Not applicable for Windows as there is no concept of --cap-add
  1031  	testRequires(c, DaemonIsLinux)
  1032  	out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
  1033  	if err == nil {
  1034  		c.Fatal(err, out)
  1035  	}
  1036  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  1037  		c.Fatalf("expected output not ok received %s", actual)
  1038  	}
  1039  }
  1040  
  1041  func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
  1042  	// Not applicable for Windows as there is no concept of --group-add
  1043  	testRequires(c, DaemonIsLinux)
  1044  	out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id")
  1045  
  1046  	groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777"
  1047  	if actual := strings.Trim(out, "\r\n"); actual != groupsList {
  1048  		c.Fatalf("expected output %s received %s", groupsList, actual)
  1049  	}
  1050  }
  1051  
  1052  func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
  1053  	// Not applicable for Windows as there is no concept of --privileged
  1054  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1055  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  1056  
  1057  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  1058  		c.Fatalf("expected output ok received %s", actual)
  1059  	}
  1060  }
  1061  
  1062  func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
  1063  	// Not applicable for Windows as there is no concept of unprivileged
  1064  	testRequires(c, DaemonIsLinux)
  1065  	out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
  1066  
  1067  	if err == nil {
  1068  		c.Fatal(err, out)
  1069  	}
  1070  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
  1071  		c.Fatalf("expected output not ok received %s", actual)
  1072  	}
  1073  }
  1074  
  1075  func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
  1076  	// Not applicable for Windows as there is no concept of unprivileged
  1077  	testRequires(c, DaemonIsLinux, NotArm)
  1078  	if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
  1079  		c.Fatal("sys should not be writable in a non privileged container")
  1080  	}
  1081  }
  1082  
  1083  func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
  1084  	// Not applicable for Windows as there is no concept of unprivileged
  1085  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  1086  	if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
  1087  		c.Fatalf("sys should be writable in privileged container")
  1088  	}
  1089  }
  1090  
  1091  func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
  1092  	// Not applicable for Windows as there is no concept of unprivileged
  1093  	testRequires(c, DaemonIsLinux)
  1094  	if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
  1095  		c.Fatal("proc should not be writable in a non privileged container")
  1096  	}
  1097  }
  1098  
  1099  func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
  1100  	// Not applicable for Windows as there is no concept of --privileged
  1101  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1102  	if _, code := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); code != 0 {
  1103  		c.Fatalf("proc should be writable in privileged container")
  1104  	}
  1105  }
  1106  
  1107  func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
  1108  	// Not applicable on Windows as /dev/ is a Unix specific concept
  1109  	// TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user
  1110  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1111  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
  1112  	deviceLineFields := strings.Fields(out)
  1113  	deviceLineFields[6] = ""
  1114  	deviceLineFields[7] = ""
  1115  	deviceLineFields[8] = ""
  1116  	expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
  1117  
  1118  	if !(reflect.DeepEqual(deviceLineFields, expected)) {
  1119  		c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
  1120  	}
  1121  }
  1122  
  1123  func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
  1124  	// Not applicable on Windows as /dev/ is a Unix specific concept
  1125  	testRequires(c, DaemonIsLinux)
  1126  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
  1127  	if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
  1128  		c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
  1129  	}
  1130  }
  1131  
  1132  func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
  1133  	// Not applicable on Windows as it does not support chroot
  1134  	testRequires(c, DaemonIsLinux)
  1135  	dockerCmd(c, "run", "busybox", "chroot", "/", "true")
  1136  }
  1137  
  1138  func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
  1139  	// Not applicable on Windows as Windows does not support --device
  1140  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1141  	out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
  1142  	if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
  1143  		c.Fatalf("expected output /dev/nulo, received %s", actual)
  1144  	}
  1145  }
  1146  
  1147  func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) {
  1148  	// Not applicable on Windows as Windows does not support --device
  1149  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1150  	out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero")
  1151  	if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" {
  1152  		c.Fatalf("expected output /dev/zero, received %s", actual)
  1153  	}
  1154  }
  1155  
  1156  func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *check.C) {
  1157  	// Not applicable on Windows as Windows does not support --device
  1158  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1159  	_, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero")
  1160  	if err == nil {
  1161  		c.Fatalf("run container with device mode ro should fail")
  1162  	}
  1163  }
  1164  
  1165  func (s *DockerSuite) TestRunModeHostname(c *check.C) {
  1166  	// Not applicable on Windows as Windows does not support -h
  1167  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  1168  
  1169  	out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
  1170  
  1171  	if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
  1172  		c.Fatalf("expected 'testhostname', but says: %q", actual)
  1173  	}
  1174  
  1175  	out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
  1176  
  1177  	hostname, err := os.Hostname()
  1178  	if err != nil {
  1179  		c.Fatal(err)
  1180  	}
  1181  	if actual := strings.Trim(out, "\r\n"); actual != hostname {
  1182  		c.Fatalf("expected %q, but says: %q", hostname, actual)
  1183  	}
  1184  }
  1185  
  1186  func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
  1187  	out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
  1188  	expected := "/\n"
  1189  	if daemonPlatform == "windows" {
  1190  		expected = "C:" + expected
  1191  	}
  1192  	if out != expected {
  1193  		c.Fatalf("pwd returned %q (expected %s)", s, expected)
  1194  	}
  1195  }
  1196  
  1197  func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
  1198  	if daemonPlatform == "windows" {
  1199  		// Windows busybox will fail with Permission Denied on items such as pagefile.sys
  1200  		dockerCmd(c, "run", "-v", `c:\:c:\host`, WindowsBaseImage, "cmd", "-c", "dir", `c:\host`)
  1201  	} else {
  1202  		dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
  1203  	}
  1204  }
  1205  
  1206  func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
  1207  	mount := "/:/"
  1208  	targetDir := "/host"
  1209  	if daemonPlatform == "windows" {
  1210  		mount = `c:\:c\`
  1211  		targetDir = "c:/host" // Forward slash as using busybox
  1212  	}
  1213  	out, _, err := dockerCmdWithError("run", "-v", mount, "busybox", "ls", targetDir)
  1214  	if err == nil {
  1215  		c.Fatal(out, err)
  1216  	}
  1217  }
  1218  
  1219  // Verify that a container gets default DNS when only localhost resolvers exist
  1220  func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
  1221  	// Not applicable on Windows as this is testing Unix specific functionality
  1222  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1223  
  1224  	// preserve original resolv.conf for restoring after test
  1225  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1226  	if os.IsNotExist(err) {
  1227  		c.Fatalf("/etc/resolv.conf does not exist")
  1228  	}
  1229  	// defer restored original conf
  1230  	defer func() {
  1231  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1232  			c.Fatal(err)
  1233  		}
  1234  	}()
  1235  
  1236  	// test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
  1237  	// 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
  1238  	// GetNameservers(), leading to a replacement of nameservers with the default set
  1239  	tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
  1240  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1241  		c.Fatal(err)
  1242  	}
  1243  
  1244  	actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  1245  	// check that the actual defaults are appended to the commented out
  1246  	// localhost resolver (which should be preserved)
  1247  	// NOTE: if we ever change the defaults from google dns, this will break
  1248  	expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1249  	if actual != expected {
  1250  		c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  1251  	}
  1252  }
  1253  
  1254  func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
  1255  	// Not applicable on Windows as Windows does not support --dns*, or
  1256  	// the Unix-specific functionality of resolv.conf.
  1257  	testRequires(c, DaemonIsLinux)
  1258  	out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf")
  1259  
  1260  	// The client will get a warning on stderr when setting DNS to a localhost address; verify this:
  1261  	if !strings.Contains(stderr, "Localhost DNS setting") {
  1262  		c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
  1263  	}
  1264  
  1265  	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1266  	if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
  1267  		c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
  1268  	}
  1269  
  1270  	out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf")
  1271  
  1272  	actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1273  	if actual != "nameserver 127.0.0.1 options ndots:3" {
  1274  		c.Fatalf("expected 'nameserver 127.0.0.1 options ndots:3', but says: %q", actual)
  1275  	}
  1276  }
  1277  
  1278  func (s *DockerSuite) TestRunDnsRepeatOptions(c *check.C) {
  1279  	testRequires(c, DaemonIsLinux)
  1280  	out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf")
  1281  
  1282  	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1283  	if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
  1284  		c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual)
  1285  	}
  1286  }
  1287  
  1288  func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  1289  	// Not applicable on Windows as testing Unix specific functionality
  1290  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1291  
  1292  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1293  	if os.IsNotExist(err) {
  1294  		c.Fatalf("/etc/resolv.conf does not exist")
  1295  	}
  1296  
  1297  	hostNamservers := resolvconf.GetNameservers(origResolvConf, netutils.IP)
  1298  	hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  1299  
  1300  	var out string
  1301  	out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1302  
  1303  	if actualNameservers := resolvconf.GetNameservers([]byte(out), netutils.IP); string(actualNameservers[0]) != "127.0.0.1" {
  1304  		c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  1305  	}
  1306  
  1307  	actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1308  	if len(actualSearch) != len(hostSearch) {
  1309  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1310  	}
  1311  	for i := range actualSearch {
  1312  		if actualSearch[i] != hostSearch[i] {
  1313  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1314  		}
  1315  	}
  1316  
  1317  	out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1318  
  1319  	actualNameservers := resolvconf.GetNameservers([]byte(out), netutils.IP)
  1320  	if len(actualNameservers) != len(hostNamservers) {
  1321  		c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  1322  	}
  1323  	for i := range actualNameservers {
  1324  		if actualNameservers[i] != hostNamservers[i] {
  1325  			c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  1326  		}
  1327  	}
  1328  
  1329  	if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1330  		c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  1331  	}
  1332  
  1333  	// test with file
  1334  	tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  1335  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1336  		c.Fatal(err)
  1337  	}
  1338  	// put the old resolvconf back
  1339  	defer func() {
  1340  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1341  			c.Fatal(err)
  1342  		}
  1343  	}()
  1344  
  1345  	resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1346  	if os.IsNotExist(err) {
  1347  		c.Fatalf("/etc/resolv.conf does not exist")
  1348  	}
  1349  
  1350  	hostNamservers = resolvconf.GetNameservers(resolvConf, netutils.IP)
  1351  	hostSearch = resolvconf.GetSearchDomains(resolvConf)
  1352  
  1353  	out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  1354  	if actualNameservers = resolvconf.GetNameservers([]byte(out), netutils.IP); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  1355  		c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  1356  	}
  1357  
  1358  	actualSearch = resolvconf.GetSearchDomains([]byte(out))
  1359  	if len(actualSearch) != len(hostSearch) {
  1360  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1361  	}
  1362  	for i := range actualSearch {
  1363  		if actualSearch[i] != hostSearch[i] {
  1364  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1365  		}
  1366  	}
  1367  }
  1368  
  1369  // Test to see if a non-root user can resolve a DNS name. Also
  1370  // check if the container resolv.conf file has at least 0644 perm.
  1371  func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  1372  	// Not applicable on Windows as Windows does not support --user
  1373  	testRequires(c, SameHostDaemon, Network, DaemonIsLinux, NotArm)
  1374  
  1375  	dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "apt.dockerproject.org")
  1376  
  1377  	cID, err := getIDByName("testperm")
  1378  	if err != nil {
  1379  		c.Fatal(err)
  1380  	}
  1381  
  1382  	fmode := (os.FileMode)(0644)
  1383  	finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  1384  	if err != nil {
  1385  		c.Fatal(err)
  1386  	}
  1387  
  1388  	if (finfo.Mode() & fmode) != fmode {
  1389  		c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
  1390  	}
  1391  }
  1392  
  1393  // Test if container resolv.conf gets updated the next time it restarts
  1394  // if host /etc/resolv.conf has changed. This only applies if the container
  1395  // uses the host's /etc/resolv.conf and does not have any dns options provided.
  1396  func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  1397  	// Not applicable on Windows as testing unix specific functionality
  1398  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1399  
  1400  	tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n")
  1401  	tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  1402  
  1403  	//take a copy of resolv.conf for restoring after test completes
  1404  	resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  1405  	if err != nil {
  1406  		c.Fatal(err)
  1407  	}
  1408  
  1409  	// This test case is meant to test monitoring resolv.conf when it is
  1410  	// a regular file not a bind mounc. So we unmount resolv.conf and replace
  1411  	// it with a file containing the original settings.
  1412  	cmd := exec.Command("umount", "/etc/resolv.conf")
  1413  	if _, err = runCommand(cmd); err != nil {
  1414  		c.Fatal(err)
  1415  	}
  1416  
  1417  	//cleanup
  1418  	defer func() {
  1419  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1420  			c.Fatal(err)
  1421  		}
  1422  	}()
  1423  
  1424  	//1. test that a restarting container gets an updated resolv.conf
  1425  	dockerCmd(c, "run", "--name='first'", "busybox", "true")
  1426  	containerID1, err := getIDByName("first")
  1427  	if err != nil {
  1428  		c.Fatal(err)
  1429  	}
  1430  
  1431  	// replace resolv.conf with our temporary copy
  1432  	bytesResolvConf := []byte(tmpResolvConf)
  1433  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1434  		c.Fatal(err)
  1435  	}
  1436  
  1437  	// start the container again to pickup changes
  1438  	dockerCmd(c, "start", "first")
  1439  
  1440  	// check for update in container
  1441  	containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  1442  	if err != nil {
  1443  		c.Fatal(err)
  1444  	}
  1445  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1446  		c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1447  	}
  1448  
  1449  	/*	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1450  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1451  						c.Fatal(err)
  1452  								} */
  1453  	//2. test that a restarting container does not receive resolv.conf updates
  1454  	//   if it modified the container copy of the starting point resolv.conf
  1455  	dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  1456  	containerID2, err := getIDByName("second")
  1457  	if err != nil {
  1458  		c.Fatal(err)
  1459  	}
  1460  
  1461  	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1462  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1463  		c.Fatal(err)
  1464  	}
  1465  
  1466  	// start the container again
  1467  	dockerCmd(c, "start", "second")
  1468  
  1469  	// check for update in container
  1470  	containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  1471  	if err != nil {
  1472  		c.Fatal(err)
  1473  	}
  1474  
  1475  	if bytes.Equal(containerResolv, resolvConfSystem) {
  1476  		c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv))
  1477  	}
  1478  
  1479  	//3. test that a running container's resolv.conf is not modified while running
  1480  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1481  	runningContainerID := strings.TrimSpace(out)
  1482  
  1483  	// replace resolv.conf
  1484  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1485  		c.Fatal(err)
  1486  	}
  1487  
  1488  	// check for update in container
  1489  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1490  	if err != nil {
  1491  		c.Fatal(err)
  1492  	}
  1493  
  1494  	if bytes.Equal(containerResolv, bytesResolvConf) {
  1495  		c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  1496  	}
  1497  
  1498  	//4. test that a running container's resolv.conf is updated upon restart
  1499  	//   (the above container is still running..)
  1500  	dockerCmd(c, "restart", runningContainerID)
  1501  
  1502  	// check for update in container
  1503  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1504  	if err != nil {
  1505  		c.Fatal(err)
  1506  	}
  1507  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1508  		c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  1509  	}
  1510  
  1511  	//5. test that additions of a localhost resolver are cleaned from
  1512  	//   host resolv.conf before updating container's resolv.conf copies
  1513  
  1514  	// replace resolv.conf with a localhost-only nameserver copy
  1515  	bytesResolvConf = []byte(tmpLocalhostResolvConf)
  1516  	if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1517  		c.Fatal(err)
  1518  	}
  1519  
  1520  	// start the container again to pickup changes
  1521  	dockerCmd(c, "start", "first")
  1522  
  1523  	// our first exited container ID should have been updated, but with default DNS
  1524  	// after the cleanup of resolv.conf found only a localhost nameserver:
  1525  	containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1526  	if err != nil {
  1527  		c.Fatal(err)
  1528  	}
  1529  
  1530  	expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1531  	if !bytes.Equal(containerResolv, []byte(expected)) {
  1532  		c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1533  	}
  1534  
  1535  	//6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1536  	//   of containers' resolv.conf.
  1537  
  1538  	// Restore the original resolv.conf
  1539  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1540  		c.Fatal(err)
  1541  	}
  1542  
  1543  	// Run the container so it picks up the old settings
  1544  	dockerCmd(c, "run", "--name='third'", "busybox", "true")
  1545  	containerID3, err := getIDByName("third")
  1546  	if err != nil {
  1547  		c.Fatal(err)
  1548  	}
  1549  
  1550  	// Create a modified resolv.conf.aside and override resolv.conf with it
  1551  	bytesResolvConf = []byte(tmpResolvConf)
  1552  	if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1553  		c.Fatal(err)
  1554  	}
  1555  
  1556  	err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1557  	if err != nil {
  1558  		c.Fatal(err)
  1559  	}
  1560  
  1561  	// start the container again to pickup changes
  1562  	dockerCmd(c, "start", "third")
  1563  
  1564  	// check for update in container
  1565  	containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1566  	if err != nil {
  1567  		c.Fatal(err)
  1568  	}
  1569  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1570  		c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1571  	}
  1572  
  1573  	//cleanup, restore original resolv.conf happens in defer func()
  1574  }
  1575  
  1576  func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1577  	// Not applicable on Windows as it does not support --add-host
  1578  	testRequires(c, DaemonIsLinux)
  1579  	out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1580  
  1581  	actual := strings.Trim(out, "\r\n")
  1582  	if actual != "86.75.30.9\textra" {
  1583  		c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1584  	}
  1585  }
  1586  
  1587  // Regression test for #6983
  1588  func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1589  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  1590  	if exitCode != 0 {
  1591  		c.Fatalf("Container should have exited with error code 0")
  1592  	}
  1593  }
  1594  
  1595  // Regression test for #6983
  1596  func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1597  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1598  	if exitCode != 0 {
  1599  		c.Fatalf("Container should have exited with error code 0")
  1600  	}
  1601  }
  1602  
  1603  // Regression test for #6983
  1604  func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1605  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1606  	if exitCode != 0 {
  1607  		c.Fatalf("Container should have exited with error code 0")
  1608  	}
  1609  }
  1610  
  1611  // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1612  // but using --attach instead of -a to make sure we read the flag correctly
  1613  func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1614  	cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1615  	_, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1616  	if err == nil {
  1617  		c.Fatal("Container should have exited with error code different than 0")
  1618  	} else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1619  		c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1620  	}
  1621  }
  1622  
  1623  func (s *DockerSuite) TestRunState(c *check.C) {
  1624  	// TODO Windows: This needs some rework as Windows busybox does not support top
  1625  	testRequires(c, DaemonIsLinux)
  1626  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1627  
  1628  	id := strings.TrimSpace(out)
  1629  	state := inspectField(c, id, "State.Running")
  1630  	if state != "true" {
  1631  		c.Fatal("Container state is 'not running'")
  1632  	}
  1633  	pid1 := inspectField(c, id, "State.Pid")
  1634  	if pid1 == "0" {
  1635  		c.Fatal("Container state Pid 0")
  1636  	}
  1637  
  1638  	dockerCmd(c, "stop", id)
  1639  	state = inspectField(c, id, "State.Running")
  1640  	if state != "false" {
  1641  		c.Fatal("Container state is 'running'")
  1642  	}
  1643  	pid2 := inspectField(c, id, "State.Pid")
  1644  	if pid2 == pid1 {
  1645  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1646  	}
  1647  
  1648  	dockerCmd(c, "start", id)
  1649  	state = inspectField(c, id, "State.Running")
  1650  	if state != "true" {
  1651  		c.Fatal("Container state is 'not running'")
  1652  	}
  1653  	pid3 := inspectField(c, id, "State.Pid")
  1654  	if pid3 == pid1 {
  1655  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1656  	}
  1657  }
  1658  
  1659  // Test for #1737
  1660  func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1661  	// Not applicable on Windows as it does not support uid or gid in this way
  1662  	testRequires(c, DaemonIsLinux)
  1663  	name := "testrunvolumesuidgid"
  1664  	_, err := buildImage(name,
  1665  		`FROM busybox
  1666  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1667  		RUN echo 'dockerio:x:1001:' >> /etc/group
  1668  		RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1669  		true)
  1670  	if err != nil {
  1671  		c.Fatal(err)
  1672  	}
  1673  
  1674  	// Test that the uid and gid is copied from the image to the volume
  1675  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1676  	out = strings.TrimSpace(out)
  1677  	if out != "dockerio:dockerio" {
  1678  		c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1679  	}
  1680  }
  1681  
  1682  // Test for #1582
  1683  func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1684  	// TODO Windows, post TP5. Windows does not yet support volume functionality
  1685  	// that copies from the image to the volume.
  1686  	testRequires(c, DaemonIsLinux)
  1687  	name := "testruncopyvolumecontent"
  1688  	_, err := buildImage(name,
  1689  		`FROM busybox
  1690  		RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1691  		true)
  1692  	if err != nil {
  1693  		c.Fatal(err)
  1694  	}
  1695  
  1696  	// Test that the content is copied from the image to the volume
  1697  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1698  	if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1699  		c.Fatal("Container failed to transfer content to volume")
  1700  	}
  1701  }
  1702  
  1703  func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1704  	name := "testrunmdcleanuponentrypoint"
  1705  	if _, err := buildImage(name,
  1706  		`FROM busybox
  1707  		ENTRYPOINT ["echo"]
  1708  		CMD ["testingpoint"]`,
  1709  		true); err != nil {
  1710  		c.Fatal(err)
  1711  	}
  1712  
  1713  	out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1714  	if exit != 0 {
  1715  		c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1716  	}
  1717  	out = strings.TrimSpace(out)
  1718  	expected := "root"
  1719  	if daemonPlatform == "windows" {
  1720  		expected = `user manager\containeradministrator`
  1721  	}
  1722  	if out != expected {
  1723  		c.Fatalf("Expected output %s, got %q", expected, out)
  1724  	}
  1725  }
  1726  
  1727  // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1728  func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1729  	existingFile := "/bin/cat"
  1730  	expected := "not a directory"
  1731  	if daemonPlatform == "windows" {
  1732  		existingFile = `\windows\system32\ntdll.dll`
  1733  		expected = `Cannot mkdir: \windows\system32\ntdll.dll is not a directory.`
  1734  	}
  1735  
  1736  	out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox")
  1737  	if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) {
  1738  		c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode)
  1739  	}
  1740  }
  1741  
  1742  func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1743  	name := "testrunexitonstdinclose"
  1744  
  1745  	meow := "/bin/cat"
  1746  	delay := 1
  1747  	if daemonPlatform == "windows" {
  1748  		meow = "cat"
  1749  		delay = 60
  1750  	}
  1751  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow)
  1752  
  1753  	stdin, err := runCmd.StdinPipe()
  1754  	if err != nil {
  1755  		c.Fatal(err)
  1756  	}
  1757  	stdout, err := runCmd.StdoutPipe()
  1758  	if err != nil {
  1759  		c.Fatal(err)
  1760  	}
  1761  
  1762  	if err := runCmd.Start(); err != nil {
  1763  		c.Fatal(err)
  1764  	}
  1765  	if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1766  		c.Fatal(err)
  1767  	}
  1768  
  1769  	r := bufio.NewReader(stdout)
  1770  	line, err := r.ReadString('\n')
  1771  	if err != nil {
  1772  		c.Fatal(err)
  1773  	}
  1774  	line = strings.TrimSpace(line)
  1775  	if line != "hello" {
  1776  		c.Fatalf("Output should be 'hello', got '%q'", line)
  1777  	}
  1778  	if err := stdin.Close(); err != nil {
  1779  		c.Fatal(err)
  1780  	}
  1781  	finish := make(chan error)
  1782  	go func() {
  1783  		finish <- runCmd.Wait()
  1784  		close(finish)
  1785  	}()
  1786  	select {
  1787  	case err := <-finish:
  1788  		c.Assert(err, check.IsNil)
  1789  	case <-time.After(time.Duration(delay) * time.Second):
  1790  		c.Fatal("docker run failed to exit on stdin close")
  1791  	}
  1792  	state := inspectField(c, name, "State.Running")
  1793  
  1794  	if state != "false" {
  1795  		c.Fatal("Container must be stopped after stdin closing")
  1796  	}
  1797  }
  1798  
  1799  // Test for #2267
  1800  func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1801  	// Cannot run on Windows as Windows does not support diff.
  1802  	testRequires(c, DaemonIsLinux)
  1803  	name := "writehosts"
  1804  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1805  	if !strings.Contains(out, "test2267") {
  1806  		c.Fatal("/etc/hosts should contain 'test2267'")
  1807  	}
  1808  
  1809  	out, _ = dockerCmd(c, "diff", name)
  1810  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1811  		c.Fatal("diff should be empty")
  1812  	}
  1813  }
  1814  
  1815  func eqToBaseDiff(out string, c *check.C) bool {
  1816  	name := "eqToBaseDiff" + stringutils.GenerateRandomAlphaOnlyString(32)
  1817  	dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello")
  1818  	cID, err := getIDByName(name)
  1819  	c.Assert(err, check.IsNil)
  1820  
  1821  	baseDiff, _ := dockerCmd(c, "diff", cID)
  1822  	baseArr := strings.Split(baseDiff, "\n")
  1823  	sort.Strings(baseArr)
  1824  	outArr := strings.Split(out, "\n")
  1825  	sort.Strings(outArr)
  1826  	return sliceEq(baseArr, outArr)
  1827  }
  1828  
  1829  func sliceEq(a, b []string) bool {
  1830  	if len(a) != len(b) {
  1831  		return false
  1832  	}
  1833  
  1834  	for i := range a {
  1835  		if a[i] != b[i] {
  1836  			return false
  1837  		}
  1838  	}
  1839  
  1840  	return true
  1841  }
  1842  
  1843  // Test for #2267
  1844  func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1845  	// Cannot run on Windows as Windows does not support diff.
  1846  	testRequires(c, DaemonIsLinux)
  1847  	name := "writehostname"
  1848  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1849  	if !strings.Contains(out, "test2267") {
  1850  		c.Fatal("/etc/hostname should contain 'test2267'")
  1851  	}
  1852  
  1853  	out, _ = dockerCmd(c, "diff", name)
  1854  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1855  		c.Fatal("diff should be empty")
  1856  	}
  1857  }
  1858  
  1859  // Test for #2267
  1860  func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1861  	// Cannot run on Windows as Windows does not support diff.
  1862  	testRequires(c, DaemonIsLinux)
  1863  	name := "writeresolv"
  1864  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1865  	if !strings.Contains(out, "test2267") {
  1866  		c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1867  	}
  1868  
  1869  	out, _ = dockerCmd(c, "diff", name)
  1870  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1871  		c.Fatal("diff should be empty")
  1872  	}
  1873  }
  1874  
  1875  func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1876  	// Cannot run on Windows as Windows does not support --device
  1877  	testRequires(c, DaemonIsLinux)
  1878  	name := "baddevice"
  1879  	out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1880  
  1881  	if err == nil {
  1882  		c.Fatal("Run should fail with bad device")
  1883  	}
  1884  	expected := `"/etc": not a device node`
  1885  	if !strings.Contains(out, expected) {
  1886  		c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1887  	}
  1888  }
  1889  
  1890  func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1891  	name := "entrypoint"
  1892  
  1893  	out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar")
  1894  	expected := "foobar"
  1895  
  1896  	if out != expected {
  1897  		c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1898  	}
  1899  }
  1900  
  1901  func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1902  	testRequires(c, SameHostDaemon)
  1903  	if daemonPlatform == "linux" {
  1904  		testRequires(c, DaemonIsLinux, NotUserNamespace)
  1905  	}
  1906  
  1907  	tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1908  	if err != nil {
  1909  		c.Fatal(err)
  1910  	}
  1911  
  1912  	defer os.RemoveAll(tmpDir)
  1913  	writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1914  
  1915  	// TODO Windows Post TP5. Windows does not yet support :ro binds
  1916  	if daemonPlatform != "windows" {
  1917  		// Test reading from a read-only bind mount
  1918  		out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1919  		if !strings.Contains(out, "touch-me") {
  1920  			c.Fatal("Container failed to read from bind mount")
  1921  		}
  1922  	}
  1923  
  1924  	// test writing to bind mount
  1925  	if daemonPlatform == "windows" {
  1926  		dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla")
  1927  	} else {
  1928  		dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1929  	}
  1930  
  1931  	readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1932  
  1933  	// test mounting to an illegal destination directory
  1934  	_, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1935  	if err == nil {
  1936  		c.Fatal("Container bind mounted illegal directory")
  1937  	}
  1938  
  1939  	// Windows does not (and likely never will) support mounting a single file
  1940  	if daemonPlatform != "windows" {
  1941  		// test mount a file
  1942  		dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1943  		content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1944  		expected := "yotta"
  1945  		if content != expected {
  1946  			c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1947  		}
  1948  	}
  1949  }
  1950  
  1951  // Ensure that CIDFile gets deleted if it's empty
  1952  // Perform this test by making `docker run` fail
  1953  func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1954  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1955  	if err != nil {
  1956  		c.Fatal(err)
  1957  	}
  1958  	defer os.RemoveAll(tmpDir)
  1959  	tmpCidFile := path.Join(tmpDir, "cid")
  1960  
  1961  	image := "emptyfs"
  1962  	if daemonPlatform == "windows" {
  1963  		// Windows can't support an emptyfs image. Just use the regular Windows image
  1964  		image = WindowsBaseImage
  1965  	}
  1966  	out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image)
  1967  	if err == nil {
  1968  		c.Fatalf("Run without command must fail. out=%s", out)
  1969  	} else if !strings.Contains(out, "No command specified") {
  1970  		c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1971  	}
  1972  
  1973  	if _, err := os.Stat(tmpCidFile); err == nil {
  1974  		c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1975  	}
  1976  }
  1977  
  1978  // #2098 - Docker cidFiles only contain short version of the containerId
  1979  //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1980  // TestRunCidFile tests that run --cidfile returns the longid
  1981  func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1982  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1983  	if err != nil {
  1984  		c.Fatal(err)
  1985  	}
  1986  	tmpCidFile := path.Join(tmpDir, "cid")
  1987  	defer os.RemoveAll(tmpDir)
  1988  
  1989  	out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1990  
  1991  	id := strings.TrimSpace(out)
  1992  	buffer, err := ioutil.ReadFile(tmpCidFile)
  1993  	if err != nil {
  1994  		c.Fatal(err)
  1995  	}
  1996  	cid := string(buffer)
  1997  	if len(cid) != 64 {
  1998  		c.Fatalf("--cidfile should be a long id, not %q", id)
  1999  	}
  2000  	if cid != id {
  2001  		c.Fatalf("cid must be equal to %s, got %s", id, cid)
  2002  	}
  2003  }
  2004  
  2005  func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  2006  	mac := "12:34:56:78:9a:bc"
  2007  	var out string
  2008  	if daemonPlatform == "windows" {
  2009  		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
  2010  		mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
  2011  	} else {
  2012  		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
  2013  	}
  2014  
  2015  	actualMac := strings.TrimSpace(out)
  2016  	if actualMac != mac {
  2017  		c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  2018  	}
  2019  }
  2020  
  2021  func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  2022  	// TODO Windows. Network settings are not propagated back to inspect.
  2023  	testRequires(c, DaemonIsLinux)
  2024  	mac := "12:34:56:78:9a:bc"
  2025  	out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  2026  
  2027  	id := strings.TrimSpace(out)
  2028  	inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress")
  2029  	if inspectedMac != mac {
  2030  		c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  2031  	}
  2032  }
  2033  
  2034  // test docker run use an invalid mac address
  2035  func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  2036  	out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  2037  	//use an invalid mac address should with an error out
  2038  	if err == nil || !strings.Contains(out, "is not a valid mac address") {
  2039  		c.Fatalf("run with an invalid --mac-address should with error out")
  2040  	}
  2041  }
  2042  
  2043  func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  2044  	// TODO Windows. Network settings are not propagated back to inspect.
  2045  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2046  
  2047  	out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  2048  
  2049  	id := strings.TrimSpace(out)
  2050  	ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress")
  2051  	iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  2052  		"!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  2053  	out, _, err := runCommandWithOutput(iptCmd)
  2054  	if err != nil {
  2055  		c.Fatal(err, out)
  2056  	}
  2057  	if err := deleteContainer(id); err != nil {
  2058  		c.Fatal(err)
  2059  	}
  2060  
  2061  	dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  2062  }
  2063  
  2064  func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  2065  	// TODO Windows. The duplicate NAT message returned by Windows will be
  2066  	// changing as is currently completely undecipherable. Does need modifying
  2067  	// to run sh rather than top though as top isn't in Windows busybox.
  2068  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2069  
  2070  	port := "1234"
  2071  	dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  2072  
  2073  	out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  2074  	if err == nil {
  2075  		c.Fatalf("Binding on used port must fail")
  2076  	}
  2077  	if !strings.Contains(out, "port is already allocated") {
  2078  		c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  2079  	}
  2080  }
  2081  
  2082  // https://github.com/docker/docker/issues/12148
  2083  func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  2084  	// TODO Windows. -P is not yet supported
  2085  	testRequires(c, DaemonIsLinux)
  2086  	// allocate a dynamic port to get the most recent
  2087  	out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  2088  
  2089  	id := strings.TrimSpace(out)
  2090  	out, _ = dockerCmd(c, "port", id, "80")
  2091  
  2092  	strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  2093  	port, err := strconv.ParseInt(strPort, 10, 64)
  2094  	if err != nil {
  2095  		c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  2096  	}
  2097  
  2098  	// allocate a static port and a dynamic port together, with static port
  2099  	// takes the next recent port in dynamic port range.
  2100  	dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  2101  }
  2102  
  2103  // Regression test for #7792
  2104  func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  2105  	// TODO Windows: Post TP5. Updated, but Windows does not support nested mounts currently.
  2106  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2107  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2108  
  2109  	tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  2110  	if err != nil {
  2111  		c.Fatal(err)
  2112  	}
  2113  	defer os.RemoveAll(tmpDir)
  2114  
  2115  	tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  2116  	if err != nil {
  2117  		c.Fatal(err)
  2118  	}
  2119  	defer os.RemoveAll(tmpDir2)
  2120  
  2121  	// Create a temporary tmpfs mounc.
  2122  	fooDir := filepath.Join(tmpDir, "foo")
  2123  	if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  2124  		c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  2125  	}
  2126  
  2127  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  2128  		c.Fatal(err)
  2129  	}
  2130  
  2131  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  2132  		c.Fatal(err)
  2133  	}
  2134  
  2135  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  2136  		c.Fatal(err)
  2137  	}
  2138  
  2139  	dockerCmd(c, "run",
  2140  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir),
  2141  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir),
  2142  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2),
  2143  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir),
  2144  		"busybox:latest", "sh", "-c",
  2145  		"ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me")
  2146  }
  2147  
  2148  // Regression test for https://github.com/docker/docker/issues/8259
  2149  func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  2150  	// Not applicable on Windows as Windows does not support volumes
  2151  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2152  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2153  
  2154  	tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  2155  	if err != nil {
  2156  		c.Fatal(err)
  2157  	}
  2158  	defer os.RemoveAll(tmpDir)
  2159  
  2160  	linkPath := os.TempDir() + "/testlink2"
  2161  	if err := os.Symlink(tmpDir, linkPath); err != nil {
  2162  		c.Fatal(err)
  2163  	}
  2164  	defer os.RemoveAll(linkPath)
  2165  
  2166  	// Create first container
  2167  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
  2168  
  2169  	// Create second container with same symlinked path
  2170  	// This will fail if the referenced issue is hit with a "Volume exists" error
  2171  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
  2172  }
  2173  
  2174  //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  2175  func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  2176  	// While Windows supports volumes, it does not support --add-host hence
  2177  	// this test is not applicable on Windows.
  2178  	testRequires(c, DaemonIsLinux)
  2179  	out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  2180  	if !strings.Contains(out, "nameserver 127.0.0.1") {
  2181  		c.Fatal("/etc volume mount hides /etc/resolv.conf")
  2182  	}
  2183  
  2184  	out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  2185  	if !strings.Contains(out, "test123") {
  2186  		c.Fatal("/etc volume mount hides /etc/hostname")
  2187  	}
  2188  
  2189  	out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  2190  	out = strings.Replace(out, "\n", " ", -1)
  2191  	if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  2192  		c.Fatal("/etc volume mount hides /etc/hosts")
  2193  	}
  2194  }
  2195  
  2196  func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  2197  	// TODO Windows (Post TP5). Windows does not support volumes which
  2198  	// are pre-populated such as is built in the dockerfile used in this test.
  2199  	testRequires(c, DaemonIsLinux)
  2200  	if _, err := buildImage("dataimage",
  2201  		`FROM busybox
  2202  		RUN mkdir -p /foo
  2203  		RUN touch /foo/bar`,
  2204  		true); err != nil {
  2205  		c.Fatal(err)
  2206  	}
  2207  
  2208  	dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  2209  
  2210  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2211  		c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  2212  	}
  2213  
  2214  	tmpDir := randomTmpDirPath("docker_test_bind_mount_copy_data", daemonPlatform)
  2215  	if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2216  		c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  2217  	}
  2218  }
  2219  
  2220  func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  2221  	// just run with unknown image
  2222  	cmd := exec.Command(dockerBinary, "run", "asdfsg")
  2223  	stdout := bytes.NewBuffer(nil)
  2224  	cmd.Stdout = stdout
  2225  	if err := cmd.Run(); err == nil {
  2226  		c.Fatal("Run with unknown image should fail")
  2227  	}
  2228  	if stdout.Len() != 0 {
  2229  		c.Fatalf("Stdout contains output from pull: %s", stdout)
  2230  	}
  2231  }
  2232  
  2233  func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  2234  	testRequires(c, SameHostDaemon)
  2235  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  2236  	if _, err := buildImage("run_volumes_clean_paths",
  2237  		`FROM busybox
  2238  		VOLUME `+prefix+`/foo/`,
  2239  		true); err != nil {
  2240  		c.Fatal(err)
  2241  	}
  2242  
  2243  	dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  2244  
  2245  	out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash)
  2246  	if err != errMountNotFound {
  2247  		c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out)
  2248  	}
  2249  
  2250  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`)
  2251  	c.Assert(err, check.IsNil)
  2252  	if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) {
  2253  		c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out)
  2254  	}
  2255  
  2256  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash)
  2257  	if err != errMountNotFound {
  2258  		c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out)
  2259  	}
  2260  
  2261  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar")
  2262  	c.Assert(err, check.IsNil)
  2263  	if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) {
  2264  		c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out)
  2265  	}
  2266  }
  2267  
  2268  // Regression test for #3631
  2269  func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  2270  	// TODO Windows: This should be able to run on Windows if can find an
  2271  	// alternate to /dev/zero and /dev/stdout.
  2272  	testRequires(c, DaemonIsLinux)
  2273  	cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  2274  
  2275  	stdout, err := cont.StdoutPipe()
  2276  	if err != nil {
  2277  		c.Fatal(err)
  2278  	}
  2279  
  2280  	if err := cont.Start(); err != nil {
  2281  		c.Fatal(err)
  2282  	}
  2283  	n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2284  	if err != nil {
  2285  		c.Fatal(err)
  2286  	}
  2287  
  2288  	expected := 2 * 1024 * 2000
  2289  	if n != expected {
  2290  		c.Fatalf("Expected %d, got %d", expected, n)
  2291  	}
  2292  }
  2293  
  2294  func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  2295  	// TODO Windows: -P is not currently supported. Also network
  2296  	// settings are not propagated back.
  2297  	testRequires(c, DaemonIsLinux)
  2298  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2299  
  2300  	id := strings.TrimSpace(out)
  2301  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2302  	var ports nat.PortMap
  2303  	if err := unmarshalJSON([]byte(portstr), &ports); err != nil {
  2304  		c.Fatal(err)
  2305  	}
  2306  	for port, binding := range ports {
  2307  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2308  		if portnum < 3000 || portnum > 3003 {
  2309  			c.Fatalf("Port %d is out of range ", portnum)
  2310  		}
  2311  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2312  			c.Fatalf("Port is not mapped for the port %s", port)
  2313  		}
  2314  	}
  2315  }
  2316  
  2317  func (s *DockerSuite) TestRunExposePort(c *check.C) {
  2318  	out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  2319  	c.Assert(err, checker.NotNil, check.Commentf("--expose with an invalid port should error out"))
  2320  	c.Assert(out, checker.Contains, "invalid range format for --expose")
  2321  }
  2322  
  2323  func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  2324  	out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  2325  
  2326  	cID := strings.TrimSpace(out)
  2327  	_, _, err := dockerCmdWithError("start", cID)
  2328  
  2329  	// Windows and Linux are different here by architectural design. Linux will
  2330  	// fail to start the container, so an error is expected. Windows will
  2331  	// successfully start the container, and once started attempt to execute
  2332  	// the command which will fail.
  2333  	if daemonPlatform == "windows" {
  2334  		// Wait for it to exit.
  2335  		waitExited(cID, 30*time.Second)
  2336  		c.Assert(err, check.IsNil)
  2337  	} else {
  2338  		c.Assert(err, check.NotNil)
  2339  	}
  2340  
  2341  	rc := inspectField(c, cID, "State.ExitCode")
  2342  	if rc == "0" {
  2343  		c.Fatalf("ExitCode(%v) cannot be 0", rc)
  2344  	}
  2345  }
  2346  
  2347  func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  2348  	// Not applicable on Windows as uses Unix-specific capabilities
  2349  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2350  
  2351  	hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2352  	if err != nil {
  2353  		c.Fatal(err)
  2354  	}
  2355  
  2356  	out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2357  	out = strings.Trim(out, "\n")
  2358  	if hostIpc != out {
  2359  		c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  2360  	}
  2361  
  2362  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2363  	out = strings.Trim(out, "\n")
  2364  	if hostIpc == out {
  2365  		c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  2366  	}
  2367  }
  2368  
  2369  func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  2370  	// Not applicable on Windows as uses Unix-specific capabilities
  2371  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2372  
  2373  	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top")
  2374  
  2375  	id := strings.TrimSpace(out)
  2376  	state := inspectField(c, id, "State.Running")
  2377  	if state != "true" {
  2378  		c.Fatal("Container state is 'not running'")
  2379  	}
  2380  	pid1 := inspectField(c, id, "State.Pid")
  2381  
  2382  	parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  2383  	if err != nil {
  2384  		c.Fatal(err)
  2385  	}
  2386  
  2387  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  2388  	out = strings.Trim(out, "\n")
  2389  	if parentContainerIpc != out {
  2390  		c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  2391  	}
  2392  
  2393  	catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test")
  2394  	if catOutput != "test" {
  2395  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput)
  2396  	}
  2397  
  2398  	// check that /dev/mqueue is actually of mqueue type
  2399  	grepOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "grep", "/dev/mqueue", "/proc/mounts")
  2400  	if !strings.HasPrefix(grepOutput, "mqueue /dev/mqueue mqueue rw") {
  2401  		c.Fatalf("Output of 'grep /proc/mounts' expected 'mqueue /dev/mqueue mqueue rw' but found: %s", grepOutput)
  2402  	}
  2403  
  2404  	lsOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "ls", "/dev/mqueue")
  2405  	lsOutput = strings.Trim(lsOutput, "\n")
  2406  	if lsOutput != "toto" {
  2407  		c.Fatalf("Output of 'ls /dev/mqueue' expected 'toto' but found: %s", lsOutput)
  2408  	}
  2409  }
  2410  
  2411  func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  2412  	// Not applicable on Windows as uses Unix-specific capabilities
  2413  	testRequires(c, DaemonIsLinux)
  2414  	out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  2415  	if !strings.Contains(out, "abcd1234") || err == nil {
  2416  		c.Fatalf("run IPC from a non exists container should with correct error out")
  2417  	}
  2418  }
  2419  
  2420  func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  2421  	// Not applicable on Windows as uses Unix-specific capabilities
  2422  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2423  
  2424  	out, _ := dockerCmd(c, "create", "busybox")
  2425  
  2426  	id := strings.TrimSpace(out)
  2427  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  2428  	if err == nil {
  2429  		c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  2430  	}
  2431  }
  2432  
  2433  func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) {
  2434  	// Not applicable on Windows as uses Unix-specific capabilities
  2435  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2436  
  2437  	dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top")
  2438  	defer os.Remove("/dev/mqueue/toto")
  2439  	defer os.Remove("/dev/shm/test")
  2440  	volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm")
  2441  	c.Assert(err, checker.IsNil)
  2442  	if volPath != "/dev/shm" {
  2443  		c.Fatalf("volumePath should have been /dev/shm, was %s", volPath)
  2444  	}
  2445  
  2446  	out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test")
  2447  	if out != "test" {
  2448  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", out)
  2449  	}
  2450  
  2451  	// Check that the mq was created
  2452  	if _, err := os.Stat("/dev/mqueue/toto"); err != nil {
  2453  		c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error())
  2454  	}
  2455  }
  2456  
  2457  func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  2458  	// Not applicable on Windows as uses Unix-specific capabilities
  2459  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2460  
  2461  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2462  	id := strings.TrimSpace(out)
  2463  	c.Assert(waitRun(id), check.IsNil)
  2464  	pid1 := inspectField(c, id, "State.Pid")
  2465  
  2466  	parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2467  	if err != nil {
  2468  		c.Fatal(err)
  2469  	}
  2470  
  2471  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2472  	out = strings.Trim(out, "\n")
  2473  	if parentContainerNet != out {
  2474  		c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  2475  	}
  2476  }
  2477  
  2478  func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  2479  	// Not applicable on Windows as uses Unix-specific capabilities
  2480  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2481  
  2482  	hostPid, err := os.Readlink("/proc/1/ns/pid")
  2483  	if err != nil {
  2484  		c.Fatal(err)
  2485  	}
  2486  
  2487  	out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2488  	out = strings.Trim(out, "\n")
  2489  	if hostPid != out {
  2490  		c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  2491  	}
  2492  
  2493  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2494  	out = strings.Trim(out, "\n")
  2495  	if hostPid == out {
  2496  		c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  2497  	}
  2498  }
  2499  
  2500  func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  2501  	// Not applicable on Windows as uses Unix-specific capabilities
  2502  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2503  
  2504  	hostUTS, err := os.Readlink("/proc/1/ns/uts")
  2505  	if err != nil {
  2506  		c.Fatal(err)
  2507  	}
  2508  
  2509  	out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  2510  	out = strings.Trim(out, "\n")
  2511  	if hostUTS != out {
  2512  		c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  2513  	}
  2514  
  2515  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  2516  	out = strings.Trim(out, "\n")
  2517  	if hostUTS == out {
  2518  		c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  2519  	}
  2520  
  2521  	out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps")
  2522  	c.Assert(out, checker.Contains, runconfig.ErrConflictUTSHostname.Error())
  2523  }
  2524  
  2525  func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  2526  	// Remote daemons use TLS and this test is not applicable when TLS is required.
  2527  	testRequires(c, SameHostDaemon)
  2528  	if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  2529  		c.Fatalf("Should have worked: %v:\n%v", err, out)
  2530  	}
  2531  
  2532  	// Regardless of whether we specify true or false we need to
  2533  	// test to make sure tls is turned on if --tlsverify is specified at all
  2534  	out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  2535  	if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  2536  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2537  	}
  2538  
  2539  	out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  2540  	if err == nil || code == 0 || !strings.Contains(out, "cert") {
  2541  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2542  	}
  2543  }
  2544  
  2545  func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  2546  	// TODO Windows. Once moved to libnetwork/CNM, this may be able to be
  2547  	// re-instated.
  2548  	testRequires(c, DaemonIsLinux)
  2549  	// first find allocator current position
  2550  	out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2551  
  2552  	id := strings.TrimSpace(out)
  2553  	out, _ = dockerCmd(c, "port", id)
  2554  
  2555  	out = strings.TrimSpace(out)
  2556  	if out == "" {
  2557  		c.Fatal("docker port command output is empty")
  2558  	}
  2559  	out = strings.Split(out, ":")[1]
  2560  	lastPort, err := strconv.Atoi(out)
  2561  	if err != nil {
  2562  		c.Fatal(err)
  2563  	}
  2564  	port := lastPort + 1
  2565  	l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2566  	if err != nil {
  2567  		c.Fatal(err)
  2568  	}
  2569  	defer l.Close()
  2570  
  2571  	out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2572  
  2573  	id = strings.TrimSpace(out)
  2574  	dockerCmd(c, "port", id)
  2575  }
  2576  
  2577  func (s *DockerSuite) TestRunTTYWithPipe(c *check.C) {
  2578  	errChan := make(chan error)
  2579  	go func() {
  2580  		defer close(errChan)
  2581  
  2582  		cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2583  		if _, err := cmd.StdinPipe(); err != nil {
  2584  			errChan <- err
  2585  			return
  2586  		}
  2587  
  2588  		expected := "cannot enable tty mode"
  2589  		if out, _, err := runCommandWithOutput(cmd); err == nil {
  2590  			errChan <- fmt.Errorf("run should have failed")
  2591  			return
  2592  		} else if !strings.Contains(out, expected) {
  2593  			errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2594  			return
  2595  		}
  2596  	}()
  2597  
  2598  	select {
  2599  	case err := <-errChan:
  2600  		c.Assert(err, check.IsNil)
  2601  	case <-time.After(6 * time.Second):
  2602  		c.Fatal("container is running but should have failed")
  2603  	}
  2604  }
  2605  
  2606  func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  2607  	addr := "00:16:3E:08:00:50"
  2608  	args := []string{"run", "--mac-address", addr}
  2609  	expected := addr
  2610  
  2611  	if daemonPlatform != "windows" {
  2612  		args = append(args, "busybox", "ifconfig")
  2613  	} else {
  2614  		args = append(args, WindowsBaseImage, "ipconfig", "/all")
  2615  		expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
  2616  	}
  2617  
  2618  	if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
  2619  		c.Fatalf("Output should have contained %q: %s", expected, out)
  2620  	}
  2621  }
  2622  
  2623  func (s *DockerSuite) TestRunNetHost(c *check.C) {
  2624  	// Not applicable on Windows as uses Unix-specific capabilities
  2625  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2626  
  2627  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2628  	if err != nil {
  2629  		c.Fatal(err)
  2630  	}
  2631  
  2632  	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2633  	out = strings.Trim(out, "\n")
  2634  	if hostNet != out {
  2635  		c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  2636  	}
  2637  
  2638  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  2639  	out = strings.Trim(out, "\n")
  2640  	if hostNet == out {
  2641  		c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  2642  	}
  2643  }
  2644  
  2645  func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  2646  	// TODO Windows. As Windows networking evolves and converges towards
  2647  	// CNM, this test may be possible to enable on Windows.
  2648  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2649  
  2650  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2651  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2652  }
  2653  
  2654  func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  2655  	// Not applicable on Windows as uses Unix-specific capabilities
  2656  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2657  
  2658  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2659  	if err != nil {
  2660  		c.Fatal(err)
  2661  	}
  2662  
  2663  	dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2664  
  2665  	out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2666  	out = strings.Trim(out, "\n")
  2667  	if hostNet != out {
  2668  		c.Fatalf("Container should have host network namespace")
  2669  	}
  2670  }
  2671  
  2672  func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  2673  	// TODO Windows. This may be possible to enable in the future. However,
  2674  	// Windows does not currently support --expose, or populate the network
  2675  	// settings seen through inspect.
  2676  	testRequires(c, DaemonIsLinux)
  2677  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2678  
  2679  	id := strings.TrimSpace(out)
  2680  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2681  
  2682  	var ports nat.PortMap
  2683  	err := unmarshalJSON([]byte(portstr), &ports)
  2684  	c.Assert(err, checker.IsNil, check.Commentf("failed to unmarshal: %v", portstr))
  2685  	for port, binding := range ports {
  2686  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2687  		if portnum < 3000 || portnum > 3003 {
  2688  			c.Fatalf("Port %d is out of range ", portnum)
  2689  		}
  2690  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2691  			c.Fatal("Port is not mapped for the port "+port, out)
  2692  		}
  2693  	}
  2694  }
  2695  
  2696  func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  2697  	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "sleep", "30")
  2698  	out := inspectField(c, "test", "HostConfig.RestartPolicy.Name")
  2699  	if out != "no" {
  2700  		c.Fatalf("Set default restart policy failed")
  2701  	}
  2702  }
  2703  
  2704  func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  2705  	out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  2706  	timeout := 10 * time.Second
  2707  	if daemonPlatform == "windows" {
  2708  		timeout = 120 * time.Second
  2709  	}
  2710  
  2711  	id := strings.TrimSpace(string(out))
  2712  	if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
  2713  		c.Fatal(err)
  2714  	}
  2715  
  2716  	count := inspectField(c, id, "RestartCount")
  2717  	if count != "3" {
  2718  		c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2719  	}
  2720  
  2721  	MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2722  	if MaximumRetryCount != "3" {
  2723  		c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2724  	}
  2725  }
  2726  
  2727  func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  2728  	dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  2729  }
  2730  
  2731  func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  2732  	// Not applicable on Windows which does not support --read-only
  2733  	testRequires(c, DaemonIsLinux)
  2734  
  2735  	testReadOnlyFile(c, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me")
  2736  }
  2737  
  2738  func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  2739  	// Not applicable on Windows due to use of Unix specific functionality, plus
  2740  	// the use of --read-only which is not supported.
  2741  	// --read-only + userns has remount issues
  2742  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2743  
  2744  	// Ensure we have not broken writing /dev/pts
  2745  	out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  2746  	if status != 0 {
  2747  		c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  2748  	}
  2749  	expected := "type devpts (rw,"
  2750  	if !strings.Contains(string(out), expected) {
  2751  		c.Fatalf("expected output to contain %s but contains %s", expected, out)
  2752  	}
  2753  }
  2754  
  2755  func testReadOnlyFile(c *check.C, filenames ...string) {
  2756  	// Not applicable on Windows which does not support --read-only
  2757  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2758  	touch := "touch " + strings.Join(filenames, " ")
  2759  	out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch)
  2760  	c.Assert(err, checker.NotNil)
  2761  
  2762  	for _, f := range filenames {
  2763  		expected := "touch: " + f + ": Read-only file system"
  2764  		c.Assert(out, checker.Contains, expected)
  2765  	}
  2766  
  2767  	out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch)
  2768  	c.Assert(err, checker.NotNil)
  2769  
  2770  	for _, f := range filenames {
  2771  		expected := "touch: " + f + ": Read-only file system"
  2772  		c.Assert(out, checker.Contains, expected)
  2773  	}
  2774  }
  2775  
  2776  func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  2777  	// Not applicable on Windows which does not support --link
  2778  	// --read-only + userns has remount issues
  2779  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2780  
  2781  	dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  2782  
  2783  	out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  2784  	if !strings.Contains(string(out), "testlinked") {
  2785  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  2786  	}
  2787  }
  2788  
  2789  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  2790  	// Not applicable on Windows which does not support either --read-only or --dns.
  2791  	// --read-only + userns has remount issues
  2792  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2793  
  2794  	out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  2795  	if !strings.Contains(string(out), "1.1.1.1") {
  2796  		c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  2797  	}
  2798  }
  2799  
  2800  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  2801  	// Not applicable on Windows which does not support --read-only
  2802  	// --read-only + userns has remount issues
  2803  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2804  
  2805  	out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  2806  	if !strings.Contains(string(out), "testreadonly") {
  2807  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  2808  	}
  2809  }
  2810  
  2811  func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  2812  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2813  	dockerCmd(c, "run", "-d", "--name", "voltest", "-v", prefix+"/foo", "busybox", "sleep", "60")
  2814  	dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "sleep", "60")
  2815  
  2816  	// Remove the main volume container and restart the consuming container
  2817  	dockerCmd(c, "rm", "-f", "voltest")
  2818  
  2819  	// This should not fail since the volumes-from were already applied
  2820  	dockerCmd(c, "restart", "restarter")
  2821  }
  2822  
  2823  // run container with --rm should remove container if exit code != 0
  2824  func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2825  	name := "flowers"
  2826  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2827  	if err == nil {
  2828  		c.Fatal("Expected docker run to fail", out, err)
  2829  	}
  2830  
  2831  	out, err = getAllContainers()
  2832  	if err != nil {
  2833  		c.Fatal(out, err)
  2834  	}
  2835  
  2836  	if out != "" {
  2837  		c.Fatal("Expected not to have containers", out)
  2838  	}
  2839  }
  2840  
  2841  func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2842  	name := "sparkles"
  2843  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  2844  	if err == nil {
  2845  		c.Fatal("Expected docker run to fail", out, err)
  2846  	}
  2847  
  2848  	out, err = getAllContainers()
  2849  	if err != nil {
  2850  		c.Fatal(out, err)
  2851  	}
  2852  
  2853  	if out != "" {
  2854  		c.Fatal("Expected not to have containers", out)
  2855  	}
  2856  }
  2857  
  2858  func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2859  	// Not applicable on Windows as uses Unix specific functionality
  2860  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2861  	name := "ibuildthecloud"
  2862  	dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2863  
  2864  	c.Assert(waitRun(name), check.IsNil)
  2865  
  2866  	errchan := make(chan error)
  2867  	go func() {
  2868  		if out, _, err := dockerCmdWithError("kill", name); err != nil {
  2869  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  2870  		}
  2871  		close(errchan)
  2872  	}()
  2873  	select {
  2874  	case err := <-errchan:
  2875  		c.Assert(err, check.IsNil)
  2876  	case <-time.After(5 * time.Second):
  2877  		c.Fatal("Kill container timed out")
  2878  	}
  2879  }
  2880  
  2881  func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  2882  	// TODO Windows. This may be possible to enable once Windows supports
  2883  	// memory limits on containers
  2884  	testRequires(c, DaemonIsLinux)
  2885  	// this memory limit is 1 byte less than the min, which is 4MB
  2886  	// https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  2887  	out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  2888  	if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2889  		c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2890  	}
  2891  }
  2892  
  2893  func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  2894  	// Not applicable on Windows as uses Unix specific functionality
  2895  	testRequires(c, DaemonIsLinux)
  2896  	_, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2897  	if err == nil || code == 0 {
  2898  		c.Fatal("standard container should not be able to write to /proc/asound")
  2899  	}
  2900  }
  2901  
  2902  func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  2903  	// Not applicable on Windows as uses Unix specific functionality
  2904  	testRequires(c, DaemonIsLinux)
  2905  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  2906  	if code != 0 {
  2907  		return
  2908  	}
  2909  	if err != nil {
  2910  		c.Fatal(err)
  2911  	}
  2912  	if strings.Trim(out, "\n ") != "" {
  2913  		c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2914  	}
  2915  }
  2916  
  2917  func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  2918  	// Not applicable on Windows as uses Unix specific functionality
  2919  	testRequires(c, DaemonIsLinux)
  2920  	// some kernels don't have this configured so skip the test if this file is not found
  2921  	// on the host running the tests.
  2922  	if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2923  		c.Skip("kernel doesn't have latency_stats configured")
  2924  		return
  2925  	}
  2926  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  2927  	if code != 0 {
  2928  		return
  2929  	}
  2930  	if err != nil {
  2931  		c.Fatal(err)
  2932  	}
  2933  	if strings.Trim(out, "\n ") != "" {
  2934  		c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2935  	}
  2936  }
  2937  
  2938  func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  2939  	// Not applicable on Windows as uses Unix specific functionality
  2940  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  2941  
  2942  	testReadPaths := []string{
  2943  		"/proc/latency_stats",
  2944  		"/proc/timer_stats",
  2945  		"/proc/kcore",
  2946  	}
  2947  	for i, filePath := range testReadPaths {
  2948  		name := fmt.Sprintf("procsieve-%d", i)
  2949  		shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2950  
  2951  		out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2952  		if exitCode != 0 {
  2953  			return
  2954  		}
  2955  		if err != nil {
  2956  			c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2957  		}
  2958  	}
  2959  }
  2960  
  2961  func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  2962  	// Not applicable on Windows as uses Unix specific functionality
  2963  	testRequires(c, DaemonIsLinux)
  2964  	_, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  2965  	if err == nil || code == 0 {
  2966  		c.Fatal("container should not be able to mount into /proc")
  2967  	}
  2968  }
  2969  
  2970  func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  2971  	// Not applicable on Windows as uses Unix specific functionality
  2972  	testRequires(c, DaemonIsLinux)
  2973  	testRequires(c, NotUserNamespace)
  2974  	dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2975  }
  2976  
  2977  func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  2978  	// Not applicable on Windows as uses Unix specific functionality
  2979  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  2980  
  2981  	// In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run.
  2982  	errChan := make(chan error)
  2983  
  2984  	go func() {
  2985  		name := "acidburn"
  2986  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount")
  2987  		if err == nil ||
  2988  			!(strings.Contains(strings.ToLower(out), "permission denied") ||
  2989  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  2990  			errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err)
  2991  		} else {
  2992  			errChan <- nil
  2993  		}
  2994  	}()
  2995  
  2996  	go func() {
  2997  		name := "cereal"
  2998  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
  2999  		if err == nil ||
  3000  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  3001  				strings.Contains(strings.ToLower(out), "permission denied") ||
  3002  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  3003  			errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  3004  		} else {
  3005  			errChan <- nil
  3006  		}
  3007  	}()
  3008  
  3009  	/* Ensure still fails if running privileged with the default policy */
  3010  	go func() {
  3011  		name := "crashoverride"
  3012  		out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "seccomp=unconfined", "--security-opt", "apparmor=docker-default", "--name", name, "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
  3013  		if err == nil ||
  3014  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  3015  				strings.Contains(strings.ToLower(out), "permission denied") ||
  3016  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  3017  			errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  3018  		} else {
  3019  			errChan <- nil
  3020  		}
  3021  	}()
  3022  
  3023  	for i := 0; i < 3; i++ {
  3024  		err := <-errChan
  3025  		if err != nil {
  3026  			c.Fatal(err)
  3027  		}
  3028  	}
  3029  }
  3030  
  3031  func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  3032  	// TODO Windows: This may be possible once Windows moves to libnetwork and CNM
  3033  	testRequires(c, DaemonIsLinux)
  3034  	dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  3035  	out, _ := dockerCmd(c, "port", "test")
  3036  	out = strings.Trim(out, "\r\n")
  3037  	if out != "" {
  3038  		c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  3039  	}
  3040  }
  3041  
  3042  // Issue #10184.
  3043  func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  3044  	// Not applicable on Windows as uses Unix specific functionality
  3045  	testRequires(c, DaemonIsLinux)
  3046  	const permissions = "crw-rw-rw-"
  3047  	out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  3048  	if status != 0 {
  3049  		c.Fatalf("expected status 0, got %d", status)
  3050  	}
  3051  	if !strings.HasPrefix(out, permissions) {
  3052  		c.Fatalf("output should begin with %q, got %q", permissions, out)
  3053  	}
  3054  }
  3055  
  3056  func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  3057  	// Not applicable on Windows as uses Unix specific functionality
  3058  	testRequires(c, DaemonIsLinux)
  3059  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  3060  
  3061  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  3062  		c.Fatalf("expected output ok received %s", actual)
  3063  	}
  3064  }
  3065  
  3066  // https://github.com/docker/docker/pull/14498
  3067  func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  3068  	// TODO Windows post TP5. Enable the read-only bits once they are
  3069  	// supported on the platform.
  3070  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  3071  
  3072  	dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true")
  3073  	if daemonPlatform != "windows" {
  3074  		dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  3075  	}
  3076  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  3077  
  3078  	if daemonPlatform != "windows" {
  3079  		mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test")
  3080  		c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point"))
  3081  		if mRO.RW {
  3082  			c.Fatalf("Expected RO volume was RW")
  3083  		}
  3084  	}
  3085  
  3086  	mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test")
  3087  	c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point"))
  3088  	if !mRW.RW {
  3089  		c.Fatalf("Expected RW volume was RO")
  3090  	}
  3091  }
  3092  
  3093  func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  3094  	// Not applicable on Windows as uses Unix specific functionality
  3095  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  3096  
  3097  	testWritePaths := []string{
  3098  		/* modprobe and core_pattern should both be denied by generic
  3099  		 * policy of denials for /proc/sys/kernel. These files have been
  3100  		 * picked to be checked as they are particularly sensitive to writes */
  3101  		"/proc/sys/kernel/modprobe",
  3102  		"/proc/sys/kernel/core_pattern",
  3103  		"/proc/sysrq-trigger",
  3104  		"/proc/kcore",
  3105  	}
  3106  	for i, filePath := range testWritePaths {
  3107  		name := fmt.Sprintf("writeprocsieve-%d", i)
  3108  
  3109  		shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  3110  		out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  3111  		if code != 0 {
  3112  			return
  3113  		}
  3114  		if err != nil {
  3115  			c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  3116  		}
  3117  	}
  3118  }
  3119  
  3120  func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  3121  	// Not applicable on Windows as uses Unix specific functionality
  3122  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  3123  
  3124  	expected := "test123"
  3125  
  3126  	filename := createTmpFile(c, expected)
  3127  	defer os.Remove(filename)
  3128  
  3129  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3130  
  3131  	for i := range nwfiles {
  3132  		actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  3133  		if actual != expected {
  3134  			c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  3135  		}
  3136  	}
  3137  }
  3138  
  3139  func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  3140  	// Not applicable on Windows as uses Unix specific functionality
  3141  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  3142  
  3143  	filename := createTmpFile(c, "test123")
  3144  	defer os.Remove(filename)
  3145  
  3146  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3147  
  3148  	for i := range nwfiles {
  3149  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  3150  		if err == nil || exitCode == 0 {
  3151  			c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  3152  		}
  3153  	}
  3154  }
  3155  
  3156  func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  3157  	// Not applicable on Windows as uses Unix specific functionality
  3158  	// --read-only + userns has remount issues
  3159  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  3160  
  3161  	filename := createTmpFile(c, "test123")
  3162  	defer os.Remove(filename)
  3163  
  3164  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3165  
  3166  	for i := range nwfiles {
  3167  		_, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  3168  		if exitCode != 0 {
  3169  			c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3170  		}
  3171  	}
  3172  
  3173  	for i := range nwfiles {
  3174  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  3175  		if err == nil || exitCode == 0 {
  3176  			c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3177  		}
  3178  	}
  3179  }
  3180  
  3181  func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  3182  	// Windows does not support this functionality
  3183  	testRequires(c, DaemonIsLinux)
  3184  	repoName := s.setupTrustedImage(c, "trusted-run")
  3185  
  3186  	// Try run
  3187  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3188  	s.trustedCmd(runCmd)
  3189  	out, _, err := runCommandWithOutput(runCmd)
  3190  	if err != nil {
  3191  		c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  3192  	}
  3193  
  3194  	if !strings.Contains(string(out), "Tagging") {
  3195  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3196  	}
  3197  
  3198  	dockerCmd(c, "rmi", repoName)
  3199  
  3200  	// Try untrusted run to ensure we pushed the tag to the registry
  3201  	runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  3202  	s.trustedCmd(runCmd)
  3203  	out, _, err = runCommandWithOutput(runCmd)
  3204  	if err != nil {
  3205  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  3206  	}
  3207  
  3208  	if !strings.Contains(string(out), "Status: Downloaded") {
  3209  		c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  3210  	}
  3211  }
  3212  
  3213  func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  3214  	// Windows does not support this functionality
  3215  	testRequires(c, DaemonIsLinux)
  3216  	repoName := fmt.Sprintf("%v/dockercliuntrusted/runtest:latest", privateRegistryURL)
  3217  	// tag the image and upload it to the private registry
  3218  	dockerCmd(c, "tag", "busybox", repoName)
  3219  	dockerCmd(c, "push", repoName)
  3220  	dockerCmd(c, "rmi", repoName)
  3221  
  3222  	// Try trusted run on untrusted tag
  3223  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3224  	s.trustedCmd(runCmd)
  3225  	out, _, err := runCommandWithOutput(runCmd)
  3226  	if err == nil {
  3227  		c.Fatalf("Error expected when running trusted run with:\n%s", out)
  3228  	}
  3229  
  3230  	if !strings.Contains(string(out), "does not have trust data for") {
  3231  		c.Fatalf("Missing expected output on trusted run:\n%s", out)
  3232  	}
  3233  }
  3234  
  3235  func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  3236  	// Windows does not support this functionality
  3237  	testRequires(c, DaemonIsLinux)
  3238  	c.Skip("Currently changes system time, causing instability")
  3239  	repoName := s.setupTrustedImage(c, "trusted-run-expired")
  3240  
  3241  	// Certificates have 10 years of expiration
  3242  	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  3243  
  3244  	runAtDifferentDate(elevenYearsFromNow, func() {
  3245  		// Try run
  3246  		runCmd := exec.Command(dockerBinary, "run", repoName)
  3247  		s.trustedCmd(runCmd)
  3248  		out, _, err := runCommandWithOutput(runCmd)
  3249  		if err == nil {
  3250  			c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  3251  		}
  3252  
  3253  		if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  3254  			c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  3255  		}
  3256  	})
  3257  
  3258  	runAtDifferentDate(elevenYearsFromNow, func() {
  3259  		// Try run
  3260  		runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  3261  		s.trustedCmd(runCmd)
  3262  		out, _, err := runCommandWithOutput(runCmd)
  3263  		if err != nil {
  3264  			c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  3265  		}
  3266  
  3267  		if !strings.Contains(string(out), "Status: Downloaded") {
  3268  			c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  3269  		}
  3270  	})
  3271  }
  3272  
  3273  func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  3274  	// Windows does not support this functionality
  3275  	testRequires(c, DaemonIsLinux)
  3276  	repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  3277  	evilLocalConfigDir, err := ioutil.TempDir("", "evilrun-local-config-dir")
  3278  	if err != nil {
  3279  		c.Fatalf("Failed to create local temp dir")
  3280  	}
  3281  
  3282  	// tag the image and upload it to the private registry
  3283  	dockerCmd(c, "tag", "busybox", repoName)
  3284  
  3285  	pushCmd := exec.Command(dockerBinary, "push", repoName)
  3286  	s.trustedCmd(pushCmd)
  3287  	out, _, err := runCommandWithOutput(pushCmd)
  3288  	if err != nil {
  3289  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3290  	}
  3291  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3292  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3293  	}
  3294  
  3295  	dockerCmd(c, "rmi", repoName)
  3296  
  3297  	// Try run
  3298  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3299  	s.trustedCmd(runCmd)
  3300  	out, _, err = runCommandWithOutput(runCmd)
  3301  	if err != nil {
  3302  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  3303  	}
  3304  
  3305  	if !strings.Contains(string(out), "Tagging") {
  3306  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3307  	}
  3308  
  3309  	dockerCmd(c, "rmi", repoName)
  3310  
  3311  	// Kill the notary server, start a new "evil" one.
  3312  	s.not.Close()
  3313  	s.not, err = newTestNotary(c)
  3314  	if err != nil {
  3315  		c.Fatalf("Restarting notary server failed.")
  3316  	}
  3317  
  3318  	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  3319  	// tag an image and upload it to the private registry
  3320  	dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  3321  
  3322  	// Push up to the new server
  3323  	pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  3324  	s.trustedCmd(pushCmd)
  3325  	out, _, err = runCommandWithOutput(pushCmd)
  3326  	if err != nil {
  3327  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3328  	}
  3329  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3330  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3331  	}
  3332  
  3333  	// Now, try running with the original client from this new trust server. This should fallback to our cached timestamp and metadata.
  3334  	runCmd = exec.Command(dockerBinary, "run", repoName)
  3335  	s.trustedCmd(runCmd)
  3336  	out, _, err = runCommandWithOutput(runCmd)
  3337  
  3338  	if err != nil {
  3339  		c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out)
  3340  	}
  3341  	if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") {
  3342  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3343  	}
  3344  }
  3345  
  3346  func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  3347  	// Not applicable on Windows as uses Unix specific functionality
  3348  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3349  
  3350  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  3351  	id := strings.TrimSpace(out)
  3352  	c.Assert(waitRun(id), check.IsNil)
  3353  	pid1 := inspectField(c, id, "State.Pid")
  3354  
  3355  	_, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  3356  	if err != nil {
  3357  		c.Fatal(err)
  3358  	}
  3359  }
  3360  
  3361  func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  3362  	// Not applicable on Windows as uses Unix specific functionality
  3363  	testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotGCCGO)
  3364  
  3365  	// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  3366  	// itself, but pid>1 should not be able to trace pid1.
  3367  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net")
  3368  	if exitCode == 0 {
  3369  		c.Fatal("ptrace was not successfully restricted by AppArmor")
  3370  	}
  3371  }
  3372  
  3373  func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  3374  	// Not applicable on Windows as uses Unix specific functionality
  3375  	testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor)
  3376  
  3377  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  3378  	if exitCode != 0 {
  3379  		c.Fatal("ptrace of self failed.")
  3380  	}
  3381  }
  3382  
  3383  func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
  3384  	// Not applicable on Windows as uses Unix specific functionality
  3385  	testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace)
  3386  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  3387  	if exitCode == 0 {
  3388  		// If our test failed, attempt to repair the host system...
  3389  		_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  3390  		if exitCode == 0 {
  3391  			c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  3392  		}
  3393  	}
  3394  }
  3395  
  3396  func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  3397  	// Not applicable on Windows as uses Unix specific functionality
  3398  	testRequires(c, DaemonIsLinux)
  3399  
  3400  	dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  3401  }
  3402  
  3403  // run create container failed should clean up the container
  3404  func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  3405  	// TODO Windows. This may be possible to enable once link is supported
  3406  	testRequires(c, DaemonIsLinux)
  3407  	name := "unique_name"
  3408  	_, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  3409  	c.Assert(err, check.NotNil, check.Commentf("Expected docker run to fail!"))
  3410  
  3411  	containerID, err := inspectFieldWithError(name, "Id")
  3412  	c.Assert(err, checker.NotNil, check.Commentf("Expected not to have this container: %s!", containerID))
  3413  	c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  3414  }
  3415  
  3416  func (s *DockerSuite) TestRunNamedVolume(c *check.C) {
  3417  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  3418  	testRequires(c, DaemonIsLinux)
  3419  	dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar")
  3420  
  3421  	out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3422  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3423  
  3424  	out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3425  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3426  }
  3427  
  3428  func (s *DockerSuite) TestRunWithUlimits(c *check.C) {
  3429  	// Not applicable on Windows as uses Unix specific functionality
  3430  	testRequires(c, DaemonIsLinux)
  3431  
  3432  	out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
  3433  	ul := strings.TrimSpace(out)
  3434  	if ul != "42" {
  3435  		c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
  3436  	}
  3437  }
  3438  
  3439  func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) {
  3440  	// Not applicable on Windows as uses Unix specific functionality
  3441  	testRequires(c, DaemonIsLinux)
  3442  
  3443  	cgroupParent := "test"
  3444  	name := "cgroup-test"
  3445  
  3446  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3447  	if err != nil {
  3448  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3449  	}
  3450  	cgroupPaths := parseCgroupPaths(string(out))
  3451  	if len(cgroupPaths) == 0 {
  3452  		c.Fatalf("unexpected output - %q", string(out))
  3453  	}
  3454  	id, err := getIDByName(name)
  3455  	c.Assert(err, check.IsNil)
  3456  	expectedCgroup := path.Join(cgroupParent, id)
  3457  	found := false
  3458  	for _, path := range cgroupPaths {
  3459  		if strings.HasSuffix(path, expectedCgroup) {
  3460  			found = true
  3461  			break
  3462  		}
  3463  	}
  3464  	if !found {
  3465  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3466  	}
  3467  }
  3468  
  3469  func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) {
  3470  	// Not applicable on Windows as uses Unix specific functionality
  3471  	testRequires(c, DaemonIsLinux)
  3472  
  3473  	cgroupParent := "/cgroup-parent/test"
  3474  	name := "cgroup-test"
  3475  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3476  	if err != nil {
  3477  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3478  	}
  3479  	cgroupPaths := parseCgroupPaths(string(out))
  3480  	if len(cgroupPaths) == 0 {
  3481  		c.Fatalf("unexpected output - %q", string(out))
  3482  	}
  3483  	id, err := getIDByName(name)
  3484  	c.Assert(err, check.IsNil)
  3485  	expectedCgroup := path.Join(cgroupParent, id)
  3486  	found := false
  3487  	for _, path := range cgroupPaths {
  3488  		if strings.HasSuffix(path, expectedCgroup) {
  3489  			found = true
  3490  			break
  3491  		}
  3492  	}
  3493  	if !found {
  3494  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3495  	}
  3496  }
  3497  
  3498  // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
  3499  func (s *DockerSuite) TestRunInvalidCgroupParent(c *check.C) {
  3500  	// Not applicable on Windows as uses Unix specific functionality
  3501  	testRequires(c, DaemonIsLinux)
  3502  
  3503  	cgroupParent := "../../../../../../../../SHOULD_NOT_EXIST"
  3504  	cleanCgroupParent := "SHOULD_NOT_EXIST"
  3505  	name := "cgroup-invalid-test"
  3506  
  3507  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3508  	if err != nil {
  3509  		// XXX: This may include a daemon crash.
  3510  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3511  	}
  3512  
  3513  	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
  3514  	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
  3515  		c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
  3516  	}
  3517  
  3518  	cgroupPaths := parseCgroupPaths(string(out))
  3519  	if len(cgroupPaths) == 0 {
  3520  		c.Fatalf("unexpected output - %q", string(out))
  3521  	}
  3522  	id, err := getIDByName(name)
  3523  	c.Assert(err, check.IsNil)
  3524  	expectedCgroup := path.Join(cleanCgroupParent, id)
  3525  	found := false
  3526  	for _, path := range cgroupPaths {
  3527  		if strings.HasSuffix(path, expectedCgroup) {
  3528  			found = true
  3529  			break
  3530  		}
  3531  	}
  3532  	if !found {
  3533  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3534  	}
  3535  }
  3536  
  3537  // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
  3538  func (s *DockerSuite) TestRunAbsoluteInvalidCgroupParent(c *check.C) {
  3539  	// Not applicable on Windows as uses Unix specific functionality
  3540  	testRequires(c, DaemonIsLinux)
  3541  
  3542  	cgroupParent := "/../../../../../../../../SHOULD_NOT_EXIST"
  3543  	cleanCgroupParent := "/SHOULD_NOT_EXIST"
  3544  	name := "cgroup-absolute-invalid-test"
  3545  
  3546  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3547  	if err != nil {
  3548  		// XXX: This may include a daemon crash.
  3549  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3550  	}
  3551  
  3552  	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
  3553  	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
  3554  		c.Fatalf("SECURITY: --cgroup-parent with /../../ garbage paths cause files to be created in the host (this is bad) !!")
  3555  	}
  3556  
  3557  	cgroupPaths := parseCgroupPaths(string(out))
  3558  	if len(cgroupPaths) == 0 {
  3559  		c.Fatalf("unexpected output - %q", string(out))
  3560  	}
  3561  	id, err := getIDByName(name)
  3562  	c.Assert(err, check.IsNil)
  3563  	expectedCgroup := path.Join(cleanCgroupParent, id)
  3564  	found := false
  3565  	for _, path := range cgroupPaths {
  3566  		if strings.HasSuffix(path, expectedCgroup) {
  3567  			found = true
  3568  			break
  3569  		}
  3570  	}
  3571  	if !found {
  3572  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3573  	}
  3574  }
  3575  
  3576  func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
  3577  	// Not applicable on Windows as uses Unix specific functionality
  3578  	// --read-only + userns has remount issues
  3579  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3580  
  3581  	filename := "/sys/fs/cgroup/devices/test123"
  3582  	out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
  3583  	if err == nil {
  3584  		c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
  3585  	}
  3586  	expected := "Read-only file system"
  3587  	if !strings.Contains(out, expected) {
  3588  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  3589  	}
  3590  }
  3591  
  3592  func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) {
  3593  	// Not applicable on Windows which does not support --net=container
  3594  	testRequires(c, DaemonIsLinux)
  3595  	out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
  3596  	if err == nil || !strings.Contains(out, "cannot join own network") {
  3597  		c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
  3598  	}
  3599  }
  3600  
  3601  func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) {
  3602  	// Not applicable on Windows which does not support --net=container
  3603  	testRequires(c, DaemonIsLinux)
  3604  	out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
  3605  	if err != nil {
  3606  		c.Fatalf("failed to run container: %v, output: %q", err, out)
  3607  	}
  3608  
  3609  	out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
  3610  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) {
  3611  		c.Fatalf("run --net=container with --dns should error out")
  3612  	}
  3613  
  3614  	out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
  3615  	if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) {
  3616  		c.Fatalf("run --net=container with --mac-address should error out")
  3617  	}
  3618  
  3619  	out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
  3620  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) {
  3621  		c.Fatalf("run --net=container with --add-host should error out")
  3622  	}
  3623  }
  3624  
  3625  func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) {
  3626  	// Not applicable on Windows which does not support --net=container
  3627  	testRequires(c, DaemonIsLinux)
  3628  	dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  3629  
  3630  	out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
  3631  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3632  		c.Fatalf("run --net=container with -p should error out")
  3633  	}
  3634  
  3635  	out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
  3636  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3637  		c.Fatalf("run --net=container with -P should error out")
  3638  	}
  3639  
  3640  	out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
  3641  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) {
  3642  		c.Fatalf("run --net=container with --expose should error out")
  3643  	}
  3644  }
  3645  
  3646  func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
  3647  	// Not applicable on Windows which does not support --net=container or --link
  3648  	testRequires(c, DaemonIsLinux)
  3649  	dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
  3650  	dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  3651  	dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
  3652  	dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  3653  	dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
  3654  }
  3655  
  3656  func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
  3657  	// TODO Windows: This may be possible to convert.
  3658  	testRequires(c, DaemonIsLinux)
  3659  	out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  3660  
  3661  	var (
  3662  		count = 0
  3663  		parts = strings.Split(out, "\n")
  3664  	)
  3665  
  3666  	for _, l := range parts {
  3667  		if l != "" {
  3668  			count++
  3669  		}
  3670  	}
  3671  
  3672  	if count != 1 {
  3673  		c.Fatalf("Wrong interface count in container %d", count)
  3674  	}
  3675  
  3676  	if !strings.HasPrefix(out, "1: lo") {
  3677  		c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  3678  	}
  3679  }
  3680  
  3681  // Issue #4681
  3682  func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
  3683  	if daemonPlatform == "windows" {
  3684  		dockerCmd(c, "run", "--net=none", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1")
  3685  	} else {
  3686  		dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  3687  	}
  3688  }
  3689  
  3690  func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
  3691  	// Windows does not support --net=container
  3692  	testRequires(c, DaemonIsLinux, ExecSupport)
  3693  
  3694  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  3695  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
  3696  	out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  3697  
  3698  	if out1 != out {
  3699  		c.Fatal("containers with shared net namespace should have same hostname")
  3700  	}
  3701  }
  3702  
  3703  func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
  3704  	// TODO Windows: Network settings are not currently propagated. This may
  3705  	// be resolved in the future with the move to libnetwork and CNM.
  3706  	testRequires(c, DaemonIsLinux)
  3707  	out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  3708  	id := strings.TrimSpace(out)
  3709  	res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress")
  3710  	if res != "" {
  3711  		c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  3712  	}
  3713  }
  3714  
  3715  func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) {
  3716  	// Not applicable as Windows does not support --net=host
  3717  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace)
  3718  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3719  	dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
  3720  	dockerCmd(c, "stop", "first")
  3721  	dockerCmd(c, "stop", "second")
  3722  }
  3723  
  3724  func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *check.C) {
  3725  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3726  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork")
  3727  	dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top")
  3728  	c.Assert(waitRun("first"), check.IsNil)
  3729  	dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first")
  3730  }
  3731  
  3732  func (s *DockerSuite) TestContainersInMultipleNetworks(c *check.C) {
  3733  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3734  	// Create 2 networks using bridge driver
  3735  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3736  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3737  	// Run and connect containers to testnetwork1
  3738  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3739  	c.Assert(waitRun("first"), check.IsNil)
  3740  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3741  	c.Assert(waitRun("second"), check.IsNil)
  3742  	// Check connectivity between containers in testnetwork2
  3743  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3744  	// Connect containers to testnetwork2
  3745  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3746  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3747  	// Check connectivity between containers
  3748  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3749  }
  3750  
  3751  func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) {
  3752  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3753  	// Create 2 networks using bridge driver
  3754  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3755  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3756  	// Run 1 container in testnetwork1 and another in testnetwork2
  3757  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3758  	c.Assert(waitRun("first"), check.IsNil)
  3759  	dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top")
  3760  	c.Assert(waitRun("second"), check.IsNil)
  3761  
  3762  	// Check Isolation between containers : ping must fail
  3763  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3764  	c.Assert(err, check.NotNil)
  3765  	// Connect first container to testnetwork2
  3766  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3767  	// ping must succeed now
  3768  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3769  	c.Assert(err, check.IsNil)
  3770  
  3771  	// Disconnect first container from testnetwork2
  3772  	dockerCmd(c, "network", "disconnect", "testnetwork2", "first")
  3773  	// ping must fail again
  3774  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3775  	c.Assert(err, check.NotNil)
  3776  }
  3777  
  3778  func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) {
  3779  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3780  	// Create 2 networks using bridge driver
  3781  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3782  	// Run and connect containers to testnetwork1
  3783  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3784  	c.Assert(waitRun("first"), check.IsNil)
  3785  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3786  	c.Assert(waitRun("second"), check.IsNil)
  3787  	// Network delete with active containers must fail
  3788  	_, _, err := dockerCmdWithError("network", "rm", "testnetwork1")
  3789  	c.Assert(err, check.NotNil)
  3790  
  3791  	dockerCmd(c, "stop", "first")
  3792  	_, _, err = dockerCmdWithError("network", "rm", "testnetwork1")
  3793  	c.Assert(err, check.NotNil)
  3794  }
  3795  
  3796  func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) {
  3797  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3798  	// Create 2 networks using bridge driver
  3799  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3800  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3801  
  3802  	// Run and connect containers to testnetwork1
  3803  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3804  	c.Assert(waitRun("first"), check.IsNil)
  3805  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3806  	c.Assert(waitRun("second"), check.IsNil)
  3807  	// Check connectivity between containers in testnetwork2
  3808  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3809  	// Connect containers to testnetwork2
  3810  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3811  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3812  	// Check connectivity between containers
  3813  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3814  
  3815  	// Stop second container and test ping failures on both networks
  3816  	dockerCmd(c, "stop", "second")
  3817  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3818  	c.Assert(err, check.NotNil)
  3819  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2")
  3820  	c.Assert(err, check.NotNil)
  3821  
  3822  	// Start second container and connectivity must be restored on both networks
  3823  	dockerCmd(c, "start", "second")
  3824  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3825  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3826  }
  3827  
  3828  func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) {
  3829  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3830  	// Run a container with --net=host
  3831  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3832  	c.Assert(waitRun("first"), check.IsNil)
  3833  
  3834  	// Create a network using bridge driver
  3835  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3836  
  3837  	// Connecting to the user defined network must fail
  3838  	_, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3839  	c.Assert(err, check.NotNil)
  3840  }
  3841  
  3842  func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) {
  3843  	testRequires(c, DaemonIsLinux)
  3844  	dockerCmd(c, "run", "-d", "--name=first", "busybox", "top")
  3845  	c.Assert(waitRun("first"), check.IsNil)
  3846  	// Run second container in first container's network namespace
  3847  	dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top")
  3848  	c.Assert(waitRun("second"), check.IsNil)
  3849  
  3850  	// Create a network using bridge driver
  3851  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3852  
  3853  	// Connecting to the user defined network must fail
  3854  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second")
  3855  	c.Assert(err, check.NotNil)
  3856  	c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error())
  3857  }
  3858  
  3859  func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) {
  3860  	testRequires(c, DaemonIsLinux)
  3861  	dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top")
  3862  	c.Assert(waitRun("first"), check.IsNil)
  3863  
  3864  	// Create a network using bridge driver
  3865  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3866  
  3867  	// Connecting to the user defined network must fail
  3868  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3869  	c.Assert(err, check.NotNil)
  3870  	c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error())
  3871  
  3872  	// create a container connected to testnetwork1
  3873  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3874  	c.Assert(waitRun("second"), check.IsNil)
  3875  
  3876  	// Connect second container to none network. it must fail as well
  3877  	_, _, err = dockerCmdWithError("network", "connect", "none", "second")
  3878  	c.Assert(err, check.NotNil)
  3879  }
  3880  
  3881  // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited
  3882  func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) {
  3883  	cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true")
  3884  	in, err := cmd.StdinPipe()
  3885  	c.Assert(err, check.IsNil)
  3886  	defer in.Close()
  3887  	stdout := bytes.NewBuffer(nil)
  3888  	cmd.Stdout = stdout
  3889  	cmd.Stderr = stdout
  3890  	c.Assert(cmd.Start(), check.IsNil)
  3891  
  3892  	waitChan := make(chan error)
  3893  	go func() {
  3894  		waitChan <- cmd.Wait()
  3895  	}()
  3896  
  3897  	select {
  3898  	case err := <-waitChan:
  3899  		c.Assert(err, check.IsNil, check.Commentf(stdout.String()))
  3900  	case <-time.After(30 * time.Second):
  3901  		c.Fatal("timeout waiting for command to exit")
  3902  	}
  3903  }
  3904  
  3905  func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) {
  3906  	// TODO Windows: This needs validation (error out) in the daemon.
  3907  	testRequires(c, DaemonIsLinux)
  3908  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true")
  3909  	c.Assert(err, check.NotNil)
  3910  	expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n"
  3911  	if !(strings.Contains(out, expected) || exitCode == 125) {
  3912  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  3913  	}
  3914  }
  3915  
  3916  func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) {
  3917  	// TODO Windows: This needs validation (error out) in the daemon.
  3918  	testRequires(c, DaemonIsLinux)
  3919  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true")
  3920  	c.Assert(err, check.NotNil)
  3921  	expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n"
  3922  	if !(strings.Contains(out, expected) || exitCode == 125) {
  3923  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  3924  	}
  3925  }
  3926  
  3927  // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127'
  3928  func (s *DockerSuite) TestRunNonExecutableCmd(c *check.C) {
  3929  	name := "testNonExecutableCmd"
  3930  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "foo")
  3931  	_, exit, _ := runCommandWithOutput(runCmd)
  3932  	stateExitCode := findContainerExitCode(c, name)
  3933  	if !(exit == 127 && strings.Contains(stateExitCode, "127")) {
  3934  		c.Fatalf("Run non-executable command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode)
  3935  	}
  3936  }
  3937  
  3938  // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127.
  3939  func (s *DockerSuite) TestRunNonExistingCmd(c *check.C) {
  3940  	name := "testNonExistingCmd"
  3941  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/bin/foo")
  3942  	_, exit, _ := runCommandWithOutput(runCmd)
  3943  	stateExitCode := findContainerExitCode(c, name)
  3944  	if !(exit == 127 && strings.Contains(stateExitCode, "127")) {
  3945  		c.Fatalf("Run non-existing command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode)
  3946  	}
  3947  }
  3948  
  3949  // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or
  3950  // 127 on Windows. The difference is that in Windows, the container must be started
  3951  // as that's when the check is made (and yes, by it's design...)
  3952  func (s *DockerSuite) TestCmdCannotBeInvoked(c *check.C) {
  3953  	expected := 126
  3954  	if daemonPlatform == "windows" {
  3955  		expected = 127
  3956  	}
  3957  	name := "testCmdCannotBeInvoked"
  3958  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/etc")
  3959  	_, exit, _ := runCommandWithOutput(runCmd)
  3960  	stateExitCode := findContainerExitCode(c, name)
  3961  	if !(exit == expected && strings.Contains(stateExitCode, strconv.Itoa(expected))) {
  3962  		c.Fatalf("Run cmd that cannot be invoked should have errored with code %d, but we got exit: %d, State.ExitCode: %s", expected, exit, stateExitCode)
  3963  	}
  3964  }
  3965  
  3966  // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains  'Unable to find image'
  3967  func (s *DockerSuite) TestRunNonExistingImage(c *check.C) {
  3968  	runCmd := exec.Command(dockerBinary, "run", "foo")
  3969  	out, exit, err := runCommandWithOutput(runCmd)
  3970  	if !(err != nil && exit == 125 && strings.Contains(out, "Unable to find image")) {
  3971  		c.Fatalf("Run non-existing image should have errored with 'Unable to find image' code 125, but we got out: %s, exit: %d, err: %s", out, exit, err)
  3972  	}
  3973  }
  3974  
  3975  // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed
  3976  func (s *DockerSuite) TestDockerFails(c *check.C) {
  3977  	runCmd := exec.Command(dockerBinary, "run", "-foo", "busybox")
  3978  	out, exit, err := runCommandWithOutput(runCmd)
  3979  	if !(err != nil && exit == 125) {
  3980  		c.Fatalf("Docker run with flag not defined should exit with 125, but we got out: %s, exit: %d, err: %s", out, exit, err)
  3981  	}
  3982  }
  3983  
  3984  // TestRunInvalidReference invokes docker run with a bad reference.
  3985  func (s *DockerSuite) TestRunInvalidReference(c *check.C) {
  3986  	out, exit, _ := dockerCmdWithError("run", "busybox@foo")
  3987  	if exit == 0 {
  3988  		c.Fatalf("expected non-zero exist code; received %d", exit)
  3989  	}
  3990  
  3991  	if !strings.Contains(out, "Error parsing reference") {
  3992  		c.Fatalf(`Expected "Error parsing reference" in output; got: %s`, out)
  3993  	}
  3994  }
  3995  
  3996  // Test fix for issue #17854
  3997  func (s *DockerSuite) TestRunInitLayerPathOwnership(c *check.C) {
  3998  	// Not applicable on Windows as it does not support Linux uid/gid ownership
  3999  	testRequires(c, DaemonIsLinux)
  4000  	name := "testetcfileownership"
  4001  	_, err := buildImage(name,
  4002  		`FROM busybox
  4003  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  4004  		RUN echo 'dockerio:x:1001:' >> /etc/group
  4005  		RUN chown dockerio:dockerio /etc`,
  4006  		true)
  4007  	if err != nil {
  4008  		c.Fatal(err)
  4009  	}
  4010  
  4011  	// Test that dockerio ownership of /etc is retained at runtime
  4012  	out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc")
  4013  	out = strings.TrimSpace(out)
  4014  	if out != "dockerio:dockerio" {
  4015  		c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out)
  4016  	}
  4017  }
  4018  
  4019  func (s *DockerSuite) TestRunWithOomScoreAdj(c *check.C) {
  4020  	testRequires(c, DaemonIsLinux)
  4021  
  4022  	expected := "642"
  4023  	out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj")
  4024  	oomScoreAdj := strings.TrimSpace(out)
  4025  	if oomScoreAdj != "642" {
  4026  		c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj)
  4027  	}
  4028  }
  4029  
  4030  func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) {
  4031  	testRequires(c, DaemonIsLinux)
  4032  
  4033  	out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true")
  4034  	c.Assert(err, check.NotNil)
  4035  	expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]."
  4036  	if !strings.Contains(out, expected) {
  4037  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  4038  	}
  4039  	out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true")
  4040  	c.Assert(err, check.NotNil)
  4041  	expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]."
  4042  	if !strings.Contains(out, expected) {
  4043  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  4044  	}
  4045  }
  4046  
  4047  func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) {
  4048  	// Volume propagation is linux only. Also it creates directories for
  4049  	// bind mounting, so needs to be same host.
  4050  	testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace)
  4051  
  4052  	// Prepare a source directory to bind mount
  4053  	tmpDir, err := ioutil.TempDir("", "volume-source")
  4054  	if err != nil {
  4055  		c.Fatal(err)
  4056  	}
  4057  	defer os.RemoveAll(tmpDir)
  4058  
  4059  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  4060  		c.Fatal(err)
  4061  	}
  4062  
  4063  	// Convert this directory into a shared mount point so that we do
  4064  	// not rely on propagation properties of parent mount.
  4065  	cmd := exec.Command("mount", "--bind", tmpDir, tmpDir)
  4066  	if _, err = runCommand(cmd); err != nil {
  4067  		c.Fatal(err)
  4068  	}
  4069  
  4070  	cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir)
  4071  	if _, err = runCommand(cmd); err != nil {
  4072  		c.Fatal(err)
  4073  	}
  4074  
  4075  	dockerCmd(c, "run", "--privileged", "-v", fmt.Sprintf("%s:/volume-dest:shared", tmpDir), "busybox", "mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1")
  4076  
  4077  	// Make sure a bind mount under a shared volume propagated to host.
  4078  	if mounted, _ := mount.Mounted(path.Join(tmpDir, "mnt1")); !mounted {
  4079  		c.Fatalf("Bind mount under shared volume did not propagate to host")
  4080  	}
  4081  
  4082  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  4083  }
  4084  
  4085  func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) {
  4086  	// Volume propagation is linux only. Also it creates directories for
  4087  	// bind mounting, so needs to be same host.
  4088  	testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace)
  4089  
  4090  	// Prepare a source directory to bind mount
  4091  	tmpDir, err := ioutil.TempDir("", "volume-source")
  4092  	if err != nil {
  4093  		c.Fatal(err)
  4094  	}
  4095  	defer os.RemoveAll(tmpDir)
  4096  
  4097  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  4098  		c.Fatal(err)
  4099  	}
  4100  
  4101  	// Prepare a source directory with file in it. We will bind mount this
  4102  	// direcotry and see if file shows up.
  4103  	tmpDir2, err := ioutil.TempDir("", "volume-source2")
  4104  	if err != nil {
  4105  		c.Fatal(err)
  4106  	}
  4107  	defer os.RemoveAll(tmpDir2)
  4108  
  4109  	if err := ioutil.WriteFile(path.Join(tmpDir2, "slave-testfile"), []byte("Test"), 0644); err != nil {
  4110  		c.Fatal(err)
  4111  	}
  4112  
  4113  	// Convert this directory into a shared mount point so that we do
  4114  	// not rely on propagation properties of parent mount.
  4115  	cmd := exec.Command("mount", "--bind", tmpDir, tmpDir)
  4116  	if _, err = runCommand(cmd); err != nil {
  4117  		c.Fatal(err)
  4118  	}
  4119  
  4120  	cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir)
  4121  	if _, err = runCommand(cmd); err != nil {
  4122  		c.Fatal(err)
  4123  	}
  4124  
  4125  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "-v", fmt.Sprintf("%s:/volume-dest:slave", tmpDir), "busybox", "top")
  4126  
  4127  	// Bind mount tmpDir2/ onto tmpDir/mnt1. If mount propagates inside
  4128  	// container then contents of tmpDir2/slave-testfile should become
  4129  	// visible at "/volume-dest/mnt1/slave-testfile"
  4130  	cmd = exec.Command("mount", "--bind", tmpDir2, path.Join(tmpDir, "mnt1"))
  4131  	if _, err = runCommand(cmd); err != nil {
  4132  		c.Fatal(err)
  4133  	}
  4134  
  4135  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/volume-dest/mnt1/slave-testfile")
  4136  
  4137  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  4138  
  4139  	if out != "Test" {
  4140  		c.Fatalf("Bind mount under slave volume did not propagate to container")
  4141  	}
  4142  }
  4143  
  4144  func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *check.C) {
  4145  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4146  	out, exitcode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile")
  4147  
  4148  	if exitcode == 0 {
  4149  		c.Fatalf("expected non-zero exit code; received %d", exitcode)
  4150  	}
  4151  
  4152  	if expected := "Invalid volume specification"; !strings.Contains(out, expected) {
  4153  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  4154  	}
  4155  }
  4156  
  4157  func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *check.C) {
  4158  	testRequires(c, DaemonIsLinux)
  4159  
  4160  	testImg := "testvolumecopy"
  4161  	_, err := buildImage(testImg, `
  4162  	FROM busybox
  4163  	RUN mkdir -p /foo && echo hello > /foo/hello
  4164  	`, true)
  4165  	c.Assert(err, check.IsNil)
  4166  
  4167  	dockerCmd(c, "run", "-v", "foo:/foo", testImg)
  4168  	out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello")
  4169  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  4170  }
  4171  
  4172  func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *check.C) {
  4173  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  4174  
  4175  	dockerCmd(c, "volume", "create", "--name", "test")
  4176  
  4177  	dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4178  	dockerCmd(c, "volume", "inspect", "test")
  4179  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  4180  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4181  
  4182  	dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4183  	dockerCmd(c, "rm", "-fv", "test")
  4184  	dockerCmd(c, "volume", "inspect", "test")
  4185  	out, _ = dockerCmd(c, "volume", "ls", "-q")
  4186  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4187  }
  4188  
  4189  func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) {
  4190  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  4191  
  4192  	dockerCmd(c, "volume", "create", "--name", "test")
  4193  	dockerCmd(c, "run", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4194  	dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true")
  4195  
  4196  	// Remove the parent so there are not other references to the volumes
  4197  	dockerCmd(c, "rm", "-f", "parent")
  4198  	// now remove the child and ensure the named volume (and only the named volume) still exists
  4199  	dockerCmd(c, "rm", "-fv", "child")
  4200  	dockerCmd(c, "volume", "inspect", "test")
  4201  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  4202  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4203  }
  4204  
  4205  func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) {
  4206  	nroutines, err := getGoroutineNumber()
  4207  	c.Assert(err, checker.IsNil)
  4208  
  4209  	runSleepingContainer(c, "--name=test", "-p", "8000:8000")
  4210  
  4211  	// Wait until container is fully up and running
  4212  	c.Assert(waitRun("test"), check.IsNil)
  4213  
  4214  	out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true")
  4215  	// We will need the following `inspect` to diagnose the issue if test fails (#21247)
  4216  	out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test")
  4217  	out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail")
  4218  	c.Assert(err, checker.NotNil, check.Commentf("Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2))
  4219  	// check for windows error as well
  4220  	// TODO Windows Post TP5. Fix the error message string
  4221  	c.Assert(strings.Contains(string(out), "port is already allocated") ||
  4222  		strings.Contains(string(out), "were not connected because a duplicate name exists") ||
  4223  		strings.Contains(string(out), "HNS failed with error : Failed to create endpoint"), checker.Equals, true, check.Commentf("Output: %s", out))
  4224  	dockerCmd(c, "rm", "-f", "test")
  4225  
  4226  	// NGoroutines is not updated right away, so we need to wait before failing
  4227  	c.Assert(waitForGoroutines(nroutines), checker.IsNil)
  4228  }
  4229  
  4230  // Test for one character directory name case (#20122)
  4231  func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *check.C) {
  4232  	testRequires(c, DaemonIsLinux)
  4233  
  4234  	out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo")
  4235  	c.Assert(strings.TrimSpace(out), checker.Equals, "/foo")
  4236  }
  4237  
  4238  func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) {
  4239  	testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume
  4240  	_, err := buildImage("volumecopy",
  4241  		`FROM busybox
  4242  		RUN mkdir /foo && echo hello > /foo/bar
  4243  		CMD cat /foo/bar`,
  4244  		true,
  4245  	)
  4246  	c.Assert(err, checker.IsNil)
  4247  
  4248  	dockerCmd(c, "volume", "create", "--name=test")
  4249  
  4250  	// test with the nocopy flag
  4251  	out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy")
  4252  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4253  	// test default behavior which is to copy for non-binds
  4254  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  4255  	c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  4256  	// error out when the volume is already populated
  4257  	out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy")
  4258  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4259  	// do not error out when copy isn't explicitly set even though it's already populated
  4260  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  4261  	c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  4262  
  4263  	// do not allow copy modes on volumes-from
  4264  	dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true")
  4265  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true")
  4266  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4267  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true")
  4268  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4269  
  4270  	// do not allow copy modes on binds
  4271  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true")
  4272  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4273  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true")
  4274  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4275  }
  4276  
  4277  func (s *DockerSuite) TestRunTooLongHostname(c *check.C) {
  4278  	// Test case in #21445
  4279  	hostname1 := "this-is-a-way-too-long-hostname-but-it-should-give-a-nice-error.local"
  4280  	out, _, err := dockerCmdWithError("run", "--hostname", hostname1, "busybox", "echo", "test")
  4281  	c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!"))
  4282  	c.Assert(out, checker.Contains, "invalid hostname format for --hostname:", check.Commentf("Expected to have 'invalid hostname format for --hostname:' in the output, get: %s!", out))
  4283  
  4284  	// HOST_NAME_MAX=64 so 65 bytes will fail
  4285  	hostname2 := "this-is-a-hostname-with-65-bytes-so-it-should-give-an-error.local"
  4286  	out, _, err = dockerCmdWithError("run", "--hostname", hostname2, "busybox", "echo", "test")
  4287  	c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!"))
  4288  	c.Assert(out, checker.Contains, "invalid hostname format for --hostname:", check.Commentf("Expected to have 'invalid hostname format for --hostname:' in the output, get: %s!", out))
  4289  
  4290  	// 64 bytes will be OK
  4291  	hostname3 := "this-is-a-hostname-with-64-bytes-so-will-not-give-an-error.local"
  4292  	dockerCmd(c, "run", "--hostname", hostname3, "busybox", "echo", "test")
  4293  }