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