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