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

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