github.com/docker/docker@v299999999.0.0-20200612211812-aaf470eca7b5+incompatible/integration-cli/docker_cli_run_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"context"
     7  	"encoding/json"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"net"
    12  	"os"
    13  	"os/exec"
    14  	"path"
    15  	"path/filepath"
    16  	"reflect"
    17  	"regexp"
    18  	"runtime"
    19  	"sort"
    20  	"strconv"
    21  	"strings"
    22  	"sync"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/Microsoft/hcsshim/osversion"
    27  	"github.com/docker/docker/client"
    28  	"github.com/docker/docker/integration-cli/cli"
    29  	"github.com/docker/docker/integration-cli/cli/build"
    30  	"github.com/docker/docker/pkg/stringid"
    31  	"github.com/docker/docker/runconfig"
    32  	"github.com/docker/docker/testutil"
    33  	"github.com/docker/docker/testutil/fakecontext"
    34  	"github.com/docker/go-connections/nat"
    35  	"github.com/docker/libnetwork/resolvconf"
    36  	"github.com/docker/libnetwork/types"
    37  	"github.com/moby/sys/mount"
    38  	"github.com/moby/sys/mountinfo"
    39  	"gotest.tools/v3/assert"
    40  	"gotest.tools/v3/icmd"
    41  )
    42  
    43  // "test123" should be printed by docker run
    44  func (s *DockerSuite) TestRunEchoStdout(c *testing.T) {
    45  	out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
    46  	if out != "test123\n" {
    47  		c.Fatalf("container should've printed 'test123', got '%s'", out)
    48  	}
    49  }
    50  
    51  // "test" should be printed
    52  func (s *DockerSuite) TestRunEchoNamedContainer(c *testing.T) {
    53  	out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
    54  	if out != "test\n" {
    55  		c.Errorf("container should've printed 'test'")
    56  	}
    57  }
    58  
    59  // docker run should not leak file descriptors. This test relies on Unix
    60  // specific functionality and cannot run on Windows.
    61  func (s *DockerSuite) TestRunLeakyFileDescriptors(c *testing.T) {
    62  	testRequires(c, DaemonIsLinux)
    63  	out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
    64  
    65  	// normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
    66  	if out != "0  1  2  3\n" {
    67  		c.Errorf("container should've printed '0  1  2  3', not: %s", out)
    68  	}
    69  }
    70  
    71  // it should be possible to lookup Google DNS
    72  // this will fail when Internet access is unavailable
    73  func (s *DockerSuite) TestRunLookupGoogleDNS(c *testing.T) {
    74  	testRequires(c, Network, NotArm)
    75  	if testEnv.OSType == "windows" {
    76  		// nslookup isn't present in Windows busybox. Is built-in. Further,
    77  		// nslookup isn't present in nanoserver. Hence just use PowerShell...
    78  		dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com")
    79  	} else {
    80  		dockerCmd(c, "run", "busybox", "nslookup", "google.com")
    81  	}
    82  
    83  }
    84  
    85  // the exit code should be 0
    86  func (s *DockerSuite) TestRunExitCodeZero(c *testing.T) {
    87  	dockerCmd(c, "run", "busybox", "true")
    88  }
    89  
    90  // the exit code should be 1
    91  func (s *DockerSuite) TestRunExitCodeOne(c *testing.T) {
    92  	_, exitCode, err := dockerCmdWithError("run", "busybox", "false")
    93  	assert.ErrorContains(c, err, "")
    94  	assert.Equal(c, exitCode, 1)
    95  }
    96  
    97  // it should be possible to pipe in data via stdin to a process running in a container
    98  func (s *DockerSuite) TestRunStdinPipe(c *testing.T) {
    99  	// TODO Windows: This needs some work to make compatible.
   100  	testRequires(c, DaemonIsLinux)
   101  	result := icmd.RunCmd(icmd.Cmd{
   102  		Command: []string{dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat"},
   103  		Stdin:   strings.NewReader("blahblah"),
   104  	})
   105  	result.Assert(c, icmd.Success)
   106  	out := result.Stdout()
   107  
   108  	out = strings.TrimSpace(out)
   109  	dockerCmd(c, "wait", out)
   110  
   111  	logsOut, _ := dockerCmd(c, "logs", out)
   112  
   113  	containerLogs := strings.TrimSpace(logsOut)
   114  	if containerLogs != "blahblah" {
   115  		c.Errorf("logs didn't print the container's logs %s", containerLogs)
   116  	}
   117  
   118  	dockerCmd(c, "rm", out)
   119  }
   120  
   121  // the container's ID should be printed when starting a container in detached mode
   122  func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *testing.T) {
   123  	out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
   124  
   125  	out = strings.TrimSpace(out)
   126  	dockerCmd(c, "wait", out)
   127  
   128  	rmOut, _ := dockerCmd(c, "rm", out)
   129  
   130  	rmOut = strings.TrimSpace(rmOut)
   131  	if rmOut != out {
   132  		c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
   133  	}
   134  }
   135  
   136  // the working directory should be set correctly
   137  func (s *DockerSuite) TestRunWorkingDirectory(c *testing.T) {
   138  	dir := "/root"
   139  	image := "busybox"
   140  	if testEnv.OSType == "windows" {
   141  		dir = `C:/Windows`
   142  	}
   143  
   144  	// First with -w
   145  	out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd")
   146  	out = strings.TrimSpace(out)
   147  	if out != dir {
   148  		c.Errorf("-w failed to set working directory")
   149  	}
   150  
   151  	// Then with --workdir
   152  	out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd")
   153  	out = strings.TrimSpace(out)
   154  	if out != dir {
   155  		c.Errorf("--workdir failed to set working directory")
   156  	}
   157  }
   158  
   159  // pinging Google's DNS resolver should fail when we disable the networking
   160  func (s *DockerSuite) TestRunWithoutNetworking(c *testing.T) {
   161  	count := "-c"
   162  	image := "busybox"
   163  	if testEnv.OSType == "windows" {
   164  		count = "-n"
   165  		image = testEnv.PlatformDefaults.BaseImage
   166  	}
   167  
   168  	// First using the long form --net
   169  	out, exitCode, err := dockerCmdWithError("run", "--net=none", image, "ping", count, "1", "8.8.8.8")
   170  	if err != nil && exitCode != 1 {
   171  		c.Fatal(out, err)
   172  	}
   173  	if exitCode != 1 {
   174  		c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
   175  	}
   176  }
   177  
   178  // test --link use container name to link target
   179  func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *testing.T) {
   180  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   181  	// settings are not populated back yet on inspect.
   182  	testRequires(c, DaemonIsLinux)
   183  	dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
   184  
   185  	ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress")
   186  
   187  	out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
   188  	if !strings.Contains(out, ip+"	test") {
   189  		c.Fatalf("use a container name to link target failed")
   190  	}
   191  }
   192  
   193  // test --link use container id to link target
   194  func (s *DockerSuite) TestRunLinksContainerWithContainerID(c *testing.T) {
   195  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   196  	// settings are not populated back yet on inspect.
   197  	testRequires(c, DaemonIsLinux)
   198  	cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
   199  
   200  	cID = strings.TrimSpace(cID)
   201  	ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress")
   202  
   203  	out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
   204  	if !strings.Contains(out, ip+"	test") {
   205  		c.Fatalf("use a container id to link target failed")
   206  	}
   207  }
   208  
   209  func (s *DockerSuite) TestUserDefinedNetworkLinks(c *testing.T) {
   210  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   211  	dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
   212  
   213  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
   214  	assert.Assert(c, waitRun("first") == nil)
   215  
   216  	// run a container in user-defined network udlinkNet with a link for an existing container
   217  	// and a link for a container that doesn't exist
   218  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
   219  		"--link=third:bar", "busybox", "top")
   220  	assert.Assert(c, waitRun("second") == nil)
   221  
   222  	// ping to first and its alias foo must succeed
   223  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   224  	assert.NilError(c, err)
   225  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   226  	assert.NilError(c, err)
   227  
   228  	// ping to third and its alias must fail
   229  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
   230  	assert.ErrorContains(c, err, "")
   231  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
   232  	assert.ErrorContains(c, err, "")
   233  
   234  	// start third container now
   235  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top")
   236  	assert.Assert(c, waitRun("third") == nil)
   237  
   238  	// ping to third and its alias must succeed now
   239  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third")
   240  	assert.NilError(c, err)
   241  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar")
   242  	assert.NilError(c, err)
   243  }
   244  
   245  func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) {
   246  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   247  	dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet")
   248  
   249  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top")
   250  	assert.Assert(c, waitRun("first") == nil)
   251  
   252  	dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo",
   253  		"busybox", "top")
   254  	assert.Assert(c, waitRun("second") == nil)
   255  
   256  	// ping to first and its alias foo must succeed
   257  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   258  	assert.NilError(c, err)
   259  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   260  	assert.NilError(c, err)
   261  
   262  	// Restart first container
   263  	dockerCmd(c, "restart", "first")
   264  	assert.Assert(c, waitRun("first") == nil)
   265  
   266  	// ping to first and its alias foo must still succeed
   267  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   268  	assert.NilError(c, err)
   269  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   270  	assert.NilError(c, err)
   271  
   272  	// Restart second container
   273  	dockerCmd(c, "restart", "second")
   274  	assert.Assert(c, waitRun("second") == nil)
   275  
   276  	// ping to first and its alias foo must still succeed
   277  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   278  	assert.NilError(c, err)
   279  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
   280  	assert.NilError(c, err)
   281  }
   282  
   283  func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *testing.T) {
   284  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   285  
   286  	defaults := []string{"bridge", "host", "none"}
   287  	for _, net := range defaults {
   288  		out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top")
   289  		assert.ErrorContains(c, err, "")
   290  		assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkAndAlias.Error()))
   291  	}
   292  }
   293  
   294  func (s *DockerSuite) TestUserDefinedNetworkAlias(c *testing.T) {
   295  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
   296  	dockerCmd(c, "network", "create", "-d", "bridge", "net1")
   297  
   298  	cid1, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top")
   299  	assert.Assert(c, waitRun("first") == nil)
   300  
   301  	// Check if default short-id alias is added automatically
   302  	id := strings.TrimSpace(cid1)
   303  	aliases := inspectField(c, id, "NetworkSettings.Networks.net1.Aliases")
   304  	assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id)))
   305  	cid2, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top")
   306  	assert.Assert(c, waitRun("second") == nil)
   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  	assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id)))
   312  	// ping to first and its network-scoped aliases
   313  	_, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   314  	assert.NilError(c, err)
   315  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
   316  	assert.NilError(c, err)
   317  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
   318  	assert.NilError(c, err)
   319  	// ping first container's short-id alias
   320  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1))
   321  	assert.NilError(c, err)
   322  
   323  	// Restart first container
   324  	dockerCmd(c, "restart", "first")
   325  	assert.Assert(c, waitRun("first") == nil)
   326  
   327  	// ping to first and its network-scoped aliases must succeed
   328  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first")
   329  	assert.NilError(c, err)
   330  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1")
   331  	assert.NilError(c, err)
   332  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2")
   333  	assert.NilError(c, err)
   334  	// ping first container's short-id alias
   335  	_, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1))
   336  	assert.NilError(c, err)
   337  }
   338  
   339  // Issue 9677.
   340  func (s *DockerSuite) TestRunWithDaemonFlags(c *testing.T) {
   341  	out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true")
   342  	assert.ErrorContains(c, err, "")
   343  	assert.Assert(c, strings.Contains(out, "unknown flag: --exec-opt"))
   344  }
   345  
   346  // Regression test for #4979
   347  func (s *DockerSuite) TestRunWithVolumesFromExited(c *testing.T) {
   348  
   349  	var (
   350  		out      string
   351  		exitCode int
   352  	)
   353  
   354  	// Create a file in a volume
   355  	if testEnv.OSType == "windows" {
   356  		out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`)
   357  	} else {
   358  		out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
   359  	}
   360  	if exitCode != 0 {
   361  		c.Fatal("1", out, exitCode)
   362  	}
   363  
   364  	// Read the file from another container using --volumes-from to access the volume in the second container
   365  	if testEnv.OSType == "windows" {
   366  		out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`)
   367  	} else {
   368  		out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
   369  	}
   370  	if exitCode != 0 {
   371  		c.Fatal("2", out, exitCode)
   372  	}
   373  }
   374  
   375  // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
   376  // But the volume call is just a normal volume, not a bind mount
   377  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *testing.T) {
   378  	var (
   379  		dockerFile    string
   380  		containerPath string
   381  		cmd           string
   382  	)
   383  	// This test cannot run on a Windows daemon as
   384  	// Windows does not support symlinks inside a volume path
   385  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
   386  	name := "test-volume-symlink"
   387  
   388  	dir, err := ioutil.TempDir("", name)
   389  	if err != nil {
   390  		c.Fatal(err)
   391  	}
   392  	defer os.RemoveAll(dir)
   393  
   394  	// In the case of Windows to Windows CI, if the machine is setup so that
   395  	// the temp directory is not the C: drive, this test is invalid and will
   396  	// not work.
   397  	if testEnv.OSType == "windows" && strings.ToLower(dir[:1]) != "c" {
   398  		c.Skip("Requires TEMP to point to C: drive")
   399  	}
   400  
   401  	f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
   402  	if err != nil {
   403  		c.Fatal(err)
   404  	}
   405  	f.Close()
   406  
   407  	if testEnv.OSType == "windows" {
   408  		dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir %s\nRUN mklink /D c:\\test %s", testEnv.PlatformDefaults.BaseImage, dir, dir)
   409  		containerPath = `c:\test\test`
   410  		cmd = "tasklist"
   411  	} else {
   412  		dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
   413  		containerPath = "/test/test"
   414  		cmd = "true"
   415  	}
   416  	buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
   417  	dockerCmd(c, "run", "-v", containerPath, name, cmd)
   418  }
   419  
   420  // Volume path is a symlink in the container
   421  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *testing.T) {
   422  	var (
   423  		dockerFile    string
   424  		containerPath string
   425  		cmd           string
   426  	)
   427  	// This test cannot run on a Windows daemon as
   428  	// Windows does not support symlinks inside a volume path
   429  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
   430  	name := "test-volume-symlink2"
   431  
   432  	if testEnv.OSType == "windows" {
   433  		dockerFile = fmt.Sprintf("FROM %s\nRUN mkdir c:\\%s\nRUN mklink /D c:\\test c:\\%s", testEnv.PlatformDefaults.BaseImage, name, name)
   434  		containerPath = `c:\test\test`
   435  		cmd = "tasklist"
   436  	} else {
   437  		dockerFile = fmt.Sprintf("FROM busybox\nRUN mkdir -p /%s\nRUN ln -s /%s /test", name, name)
   438  		containerPath = "/test/test"
   439  		cmd = "true"
   440  	}
   441  	buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile))
   442  	dockerCmd(c, "run", "-v", containerPath, name, cmd)
   443  }
   444  
   445  func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *testing.T) {
   446  	if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
   447  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   448  	}
   449  }
   450  
   451  func (s *DockerSuite) TestRunVolumesFromInReadonlyModeFails(c *testing.T) {
   452  	var (
   453  		volumeDir string
   454  		fileInVol string
   455  	)
   456  	if testEnv.OSType == "windows" {
   457  		volumeDir = `c:/test` // Forward-slash as using busybox
   458  		fileInVol = `c:/test/file`
   459  	} else {
   460  		testRequires(c, DaemonIsLinux)
   461  		volumeDir = "/test"
   462  		fileInVol = `/test/file`
   463  	}
   464  	dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
   465  
   466  	if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 {
   467  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   468  	}
   469  }
   470  
   471  // Regression test for #1201
   472  func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *testing.T) {
   473  	var (
   474  		volumeDir string
   475  		fileInVol string
   476  	)
   477  	if testEnv.OSType == "windows" {
   478  		volumeDir = `c:/test` // Forward-slash as using busybox
   479  		fileInVol = `c:/test/file`
   480  	} else {
   481  		volumeDir = "/test"
   482  		fileInVol = "/test/file"
   483  	}
   484  
   485  	dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true")
   486  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol)
   487  
   488  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) {
   489  		c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out)
   490  	}
   491  
   492  	dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol)
   493  }
   494  
   495  func (s *DockerSuite) TestVolumesFromGetsProperMode(c *testing.T) {
   496  	testRequires(c, testEnv.IsLocalDaemon)
   497  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
   498  	hostpath := RandomTmpDirPath("test", testEnv.OSType)
   499  	if err := os.MkdirAll(hostpath, 0755); err != nil {
   500  		c.Fatalf("Failed to create %s: %q", hostpath, err)
   501  	}
   502  	defer os.RemoveAll(hostpath)
   503  
   504  	dockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true")
   505  
   506  	// Expect this "rw" mode to be be ignored since the inherited volume is "ro"
   507  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil {
   508  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
   509  	}
   510  
   511  	dockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true")
   512  
   513  	// Expect this to be read-only since both are "ro"
   514  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil {
   515  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
   516  	}
   517  }
   518  
   519  // Test for GH#10618
   520  func (s *DockerSuite) TestRunNoDupVolumes(c *testing.T) {
   521  	path1 := RandomTmpDirPath("test1", testEnv.OSType)
   522  	path2 := RandomTmpDirPath("test2", testEnv.OSType)
   523  
   524  	someplace := ":/someplace"
   525  	if testEnv.OSType == "windows" {
   526  		// Windows requires that the source directory exists before calling HCS
   527  		testRequires(c, testEnv.IsLocalDaemon)
   528  		someplace = `:c:\someplace`
   529  		if err := os.MkdirAll(path1, 0755); err != nil {
   530  			c.Fatalf("Failed to create %s: %q", path1, err)
   531  		}
   532  		defer os.RemoveAll(path1)
   533  		if err := os.MkdirAll(path2, 0755); err != nil {
   534  			c.Fatalf("Failed to create %s: %q", path1, err)
   535  		}
   536  		defer os.RemoveAll(path2)
   537  	}
   538  	mountstr1 := path1 + someplace
   539  	mountstr2 := path2 + someplace
   540  
   541  	if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
   542  		c.Fatal("Expected error about duplicate mount definitions")
   543  	} else {
   544  		if !strings.Contains(out, "Duplicate mount point") {
   545  			c.Fatalf("Expected 'duplicate mount point' error, got %v", out)
   546  		}
   547  	}
   548  
   549  	// Test for https://github.com/docker/docker/issues/22093
   550  	volumename1 := "test1"
   551  	volumename2 := "test2"
   552  	volume1 := volumename1 + someplace
   553  	volume2 := volumename2 + someplace
   554  	if out, _, err := dockerCmdWithError("run", "-v", volume1, "-v", volume2, "busybox", "true"); err == nil {
   555  		c.Fatal("Expected error about duplicate mount definitions")
   556  	} else {
   557  		if !strings.Contains(out, "Duplicate mount point") {
   558  			c.Fatalf("Expected 'duplicate mount point' error, got %v", out)
   559  		}
   560  	}
   561  	// create failed should have create volume volumename1 or volumename2
   562  	// we should remove volumename2 or volumename2 successfully
   563  	out, _ := dockerCmd(c, "volume", "ls")
   564  	if strings.Contains(out, volumename1) {
   565  		dockerCmd(c, "volume", "rm", volumename1)
   566  	} else {
   567  		dockerCmd(c, "volume", "rm", volumename2)
   568  	}
   569  }
   570  
   571  // Test for #1351
   572  func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *testing.T) {
   573  	prefix := ""
   574  	if testEnv.OSType == "windows" {
   575  		prefix = `c:`
   576  	}
   577  	dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
   578  	dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo")
   579  }
   580  
   581  func (s *DockerSuite) TestRunMultipleVolumesFrom(c *testing.T) {
   582  	prefix := ""
   583  	if testEnv.OSType == "windows" {
   584  		prefix = `c:`
   585  	}
   586  	dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo")
   587  	dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar")
   588  	dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
   589  }
   590  
   591  // this tests verifies the ID format for the container
   592  func (s *DockerSuite) TestRunVerifyContainerID(c *testing.T) {
   593  	out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
   594  	if err != nil {
   595  		c.Fatal(err)
   596  	}
   597  	if exit != 0 {
   598  		c.Fatalf("expected exit code 0 received %d", exit)
   599  	}
   600  
   601  	match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
   602  	if err != nil {
   603  		c.Fatal(err)
   604  	}
   605  	if !match {
   606  		c.Fatalf("Invalid container ID: %s", out)
   607  	}
   608  }
   609  
   610  // Test that creating a container with a volume doesn't crash. Regression test for #995.
   611  func (s *DockerSuite) TestRunCreateVolume(c *testing.T) {
   612  	prefix := ""
   613  	if testEnv.OSType == "windows" {
   614  		prefix = `c:`
   615  	}
   616  	dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true")
   617  }
   618  
   619  // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
   620  // Note that this bug happens only with symlinks with a target that starts with '/'.
   621  func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *testing.T) {
   622  	// Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...)
   623  	testRequires(c, DaemonIsLinux)
   624  	workingDirectory, err := ioutil.TempDir("", "TestRunCreateVolumeWithSymlink")
   625  	assert.NilError(c, err)
   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  	assert.NilError(c, err)
   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 *testing.T) {
   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  	assert.NilError(c, err)
   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.OSType == "windows" {
   671  		prefix = `c:`
   672  		dfContents = `FROM ` + testEnv.PlatformDefaults.BaseImage + `
   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 *testing.T) {
   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 *testing.T) {
   715  	expected := "uid=0(root) gid=0(root)"
   716  	if testEnv.OSType == "windows" {
   717  		expected = "uid=0(root) gid=0(root) groups=0(root)"
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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  		assert.NilError(c, err)
   813  	}
   814  }
   815  
   816  func (s *DockerSuite) TestRunEnvironment(c *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   922  	if testEnv.OSType == "windows" {
   923  		// Windows busybox does not have ping. Use built in ping instead.
   924  		dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
   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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  1199  	// Not applicable on Windows as Windows does not support -h
  1200  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  1220  	out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
  1221  	expected := "/\n"
  1222  	if testEnv.OSType == "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 *testing.T) {
  1231  	if testEnv.OSType == "windows" {
  1232  		// Windows busybox will fail with Permission Denied on items such as pagefile.sys
  1233  		dockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "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 *testing.T) {
  1240  	mount := "/:/"
  1241  	targetDir := "/host"
  1242  	if testEnv.OSType == "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 *testing.T) {
  1254  	// Not applicable on Windows as this is testing Unix specific functionality
  1255  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  1322  	// Not applicable on Windows as testing Unix specific functionality
  1323  	testRequires(c, testEnv.IsLocalDaemon, 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); actualNameservers[0] != "127.0.0.1" {
  1337  		c.Fatalf("expected '127.0.0.1', but says: %q", 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)); actualSearch[0] != "mydomain" {
  1363  		c.Fatalf("expected 'mydomain', but says: %q", 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); 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 *testing.T) {
  1404  	// Not applicable on Windows as Windows does not support --user
  1405  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  1426  	// Not applicable on Windows as testing unix specific functionality
  1427  	testRequires(c, testEnv.IsLocalDaemon, 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 := mountinfo.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  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1463  		c.Fatal(err)
  1464  	}
  1465  
  1466  	// start the container again to pickup changes
  1467  	dockerCmd(c, "start", "first")
  1468  
  1469  	// check for update in container
  1470  	containerResolv := readContainerFile(c, containerID1, "resolv.conf")
  1471  	if !bytes.Equal(containerResolv, tmpResolvConf) {
  1472  		c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1473  	}
  1474  
  1475  	/*	// make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1476  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1477  						c.Fatal(err)
  1478  								} */
  1479  	// 2. test that a restarting container does not receive resolv.conf updates
  1480  	//   if it modified the container copy of the starting point resolv.conf
  1481  	dockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  1482  	containerID2 := getIDByName(c, "second")
  1483  
  1484  	// make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1485  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1486  		c.Fatal(err)
  1487  	}
  1488  
  1489  	// start the container again
  1490  	dockerCmd(c, "start", "second")
  1491  
  1492  	// check for update in container
  1493  	containerResolv = readContainerFile(c, containerID2, "resolv.conf")
  1494  	if bytes.Equal(containerResolv, resolvConfSystem) {
  1495  		c.Fatalf("Container's resolv.conf should not have been updated with host resolv.conf: %q", string(containerResolv))
  1496  	}
  1497  
  1498  	// 3. test that a running container's resolv.conf is not modified while running
  1499  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1500  	runningContainerID := strings.TrimSpace(out)
  1501  
  1502  	// replace resolv.conf
  1503  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1504  		c.Fatal(err)
  1505  	}
  1506  
  1507  	// check for update in container
  1508  	containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
  1509  	if bytes.Equal(containerResolv, tmpResolvConf) {
  1510  		c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  1511  	}
  1512  
  1513  	// 4. test that a running container's resolv.conf is updated upon restart
  1514  	//   (the above container is still running..)
  1515  	dockerCmd(c, "restart", runningContainerID)
  1516  
  1517  	// check for update in container
  1518  	containerResolv = readContainerFile(c, runningContainerID, "resolv.conf")
  1519  	if !bytes.Equal(containerResolv, tmpResolvConf) {
  1520  		c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv))
  1521  	}
  1522  
  1523  	// 5. test that additions of a localhost resolver are cleaned from
  1524  	//   host resolv.conf before updating container's resolv.conf copies
  1525  
  1526  	// replace resolv.conf with a localhost-only nameserver copy
  1527  	if err = ioutil.WriteFile("/etc/resolv.conf", tmpLocalhostResolvConf, 0644); err != nil {
  1528  		c.Fatal(err)
  1529  	}
  1530  
  1531  	// start the container again to pickup changes
  1532  	dockerCmd(c, "start", "first")
  1533  
  1534  	// our first exited container ID should have been updated, but with default DNS
  1535  	// after the cleanup of resolv.conf found only a localhost nameserver:
  1536  	containerResolv = readContainerFile(c, containerID1, "resolv.conf")
  1537  	expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1538  	if !bytes.Equal(containerResolv, []byte(expected)) {
  1539  		c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1540  	}
  1541  
  1542  	// 6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1543  	//   of containers' resolv.conf.
  1544  
  1545  	// Restore the original resolv.conf
  1546  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1547  		c.Fatal(err)
  1548  	}
  1549  
  1550  	// Run the container so it picks up the old settings
  1551  	dockerCmd(c, "run", "--name=third", "busybox", "true")
  1552  	containerID3 := getIDByName(c, "third")
  1553  
  1554  	// Create a modified resolv.conf.aside and override resolv.conf with it
  1555  	if err := ioutil.WriteFile("/etc/resolv.conf.aside", tmpResolvConf, 0644); err != nil {
  1556  		c.Fatal(err)
  1557  	}
  1558  
  1559  	err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1560  	if err != nil {
  1561  		c.Fatal(err)
  1562  	}
  1563  
  1564  	// start the container again to pickup changes
  1565  	dockerCmd(c, "start", "third")
  1566  
  1567  	// check for update in container
  1568  	containerResolv = readContainerFile(c, containerID3, "resolv.conf")
  1569  	if !bytes.Equal(containerResolv, tmpResolvConf) {
  1570  		c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1571  	}
  1572  
  1573  	// cleanup, restore original resolv.conf happens in defer func()
  1574  }
  1575  
  1576  func (s *DockerSuite) TestRunAddHost(c *testing.T) {
  1577  	// Not applicable on Windows as it does not support --add-host
  1578  	testRequires(c, DaemonIsLinux)
  1579  	out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1580  
  1581  	actual := strings.Trim(out, "\r\n")
  1582  	if actual != "86.75.30.9\textra" {
  1583  		c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1584  	}
  1585  }
  1586  
  1587  // Regression test for #6983
  1588  func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *testing.T) {
  1589  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  1590  	if exitCode != 0 {
  1591  		c.Fatalf("Container should have exited with error code 0")
  1592  	}
  1593  }
  1594  
  1595  // Regression test for #6983
  1596  func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *testing.T) {
  1597  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1598  	if exitCode != 0 {
  1599  		c.Fatalf("Container should have exited with error code 0")
  1600  	}
  1601  }
  1602  
  1603  // Regression test for #6983
  1604  func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *testing.T) {
  1605  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1606  	if exitCode != 0 {
  1607  		c.Fatalf("Container should have exited with error code 0")
  1608  	}
  1609  }
  1610  
  1611  // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1612  // but using --attach instead of -a to make sure we read the flag correctly
  1613  func (s *DockerSuite) TestRunAttachWithDetach(c *testing.T) {
  1614  	icmd.RunCommand(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true").Assert(c, icmd.Expected{
  1615  		ExitCode: 1,
  1616  		Error:    "exit status 1",
  1617  		Err:      "Conflicting options: -a and -d",
  1618  	})
  1619  }
  1620  
  1621  func (s *DockerSuite) TestRunState(c *testing.T) {
  1622  	// TODO Windows: This needs some rework as Windows busybox does not support top
  1623  	testRequires(c, DaemonIsLinux)
  1624  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1625  
  1626  	id := strings.TrimSpace(out)
  1627  	state := inspectField(c, id, "State.Running")
  1628  	if state != "true" {
  1629  		c.Fatal("Container state is 'not running'")
  1630  	}
  1631  	pid1 := inspectField(c, id, "State.Pid")
  1632  	if pid1 == "0" {
  1633  		c.Fatal("Container state Pid 0")
  1634  	}
  1635  
  1636  	dockerCmd(c, "stop", id)
  1637  	state = inspectField(c, id, "State.Running")
  1638  	if state != "false" {
  1639  		c.Fatal("Container state is 'running'")
  1640  	}
  1641  	pid2 := inspectField(c, id, "State.Pid")
  1642  	if pid2 == pid1 {
  1643  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1644  	}
  1645  
  1646  	dockerCmd(c, "start", id)
  1647  	state = inspectField(c, id, "State.Running")
  1648  	if state != "true" {
  1649  		c.Fatal("Container state is 'not running'")
  1650  	}
  1651  	pid3 := inspectField(c, id, "State.Pid")
  1652  	if pid3 == pid1 {
  1653  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1654  	}
  1655  }
  1656  
  1657  // Test for #1737
  1658  func (s *DockerSuite) TestRunCopyVolumeUIDGID(c *testing.T) {
  1659  	// Not applicable on Windows as it does not support uid or gid in this way
  1660  	testRequires(c, DaemonIsLinux)
  1661  	name := "testrunvolumesuidgid"
  1662  	buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1663  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1664  		RUN echo 'dockerio:x:1001:' >> /etc/group
  1665  		RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`))
  1666  
  1667  	// Test that the uid and gid is copied from the image to the volume
  1668  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1669  	out = strings.TrimSpace(out)
  1670  	if out != "dockerio:dockerio" {
  1671  		c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1672  	}
  1673  }
  1674  
  1675  // Test for #1582
  1676  func (s *DockerSuite) TestRunCopyVolumeContent(c *testing.T) {
  1677  	// TODO Windows, post RS1. Windows does not yet support volume functionality
  1678  	// that copies from the image to the volume.
  1679  	testRequires(c, DaemonIsLinux)
  1680  	name := "testruncopyvolumecontent"
  1681  	buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1682  		RUN mkdir -p /hello/local && echo hello > /hello/local/world`))
  1683  
  1684  	// Test that the content is copied from the image to the volume
  1685  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1686  	if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1687  		c.Fatal("Container failed to transfer content to volume")
  1688  	}
  1689  }
  1690  
  1691  func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *testing.T) {
  1692  	name := "testrunmdcleanuponentrypoint"
  1693  	buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  1694  		ENTRYPOINT ["echo"]
  1695  		CMD ["testingpoint"]`))
  1696  
  1697  	out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1698  	if exit != 0 {
  1699  		c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1700  	}
  1701  	out = strings.TrimSpace(out)
  1702  	expected := "root"
  1703  	if testEnv.OSType == "windows" {
  1704  		if strings.Contains(testEnv.PlatformDefaults.BaseImage, "servercore") {
  1705  			expected = `user manager\containeradministrator`
  1706  		} else {
  1707  			expected = `ContainerAdministrator` // nanoserver
  1708  		}
  1709  	}
  1710  	if out != expected {
  1711  		c.Fatalf("Expected output %s, got %q. %s", expected, out, testEnv.PlatformDefaults.BaseImage)
  1712  	}
  1713  }
  1714  
  1715  // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1716  func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *testing.T) {
  1717  	existingFile := "/bin/cat"
  1718  	expected := "not a directory"
  1719  	if testEnv.OSType == "windows" {
  1720  		existingFile = `\windows\system32\ntdll.dll`
  1721  		expected = `The directory name is invalid.`
  1722  	}
  1723  
  1724  	out, exitCode, err := dockerCmdWithError("run", "-w", existingFile, "busybox")
  1725  	if !(err != nil && exitCode == 125 && strings.Contains(out, expected)) {
  1726  		c.Fatalf("Existing binary as a directory should error out with exitCode 125; we got: %s, exitCode: %d", out, exitCode)
  1727  	}
  1728  }
  1729  
  1730  func (s *DockerSuite) TestRunExitOnStdinClose(c *testing.T) {
  1731  	name := "testrunexitonstdinclose"
  1732  
  1733  	meow := "/bin/cat"
  1734  	delay := 60
  1735  	if testEnv.OSType == "windows" {
  1736  		meow = "cat"
  1737  	}
  1738  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow)
  1739  
  1740  	stdin, err := runCmd.StdinPipe()
  1741  	if err != nil {
  1742  		c.Fatal(err)
  1743  	}
  1744  	stdout, err := runCmd.StdoutPipe()
  1745  	if err != nil {
  1746  		c.Fatal(err)
  1747  	}
  1748  
  1749  	if err := runCmd.Start(); err != nil {
  1750  		c.Fatal(err)
  1751  	}
  1752  	if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1753  		c.Fatal(err)
  1754  	}
  1755  
  1756  	r := bufio.NewReader(stdout)
  1757  	line, err := r.ReadString('\n')
  1758  	if err != nil {
  1759  		c.Fatal(err)
  1760  	}
  1761  	line = strings.TrimSpace(line)
  1762  	if line != "hello" {
  1763  		c.Fatalf("Output should be 'hello', got '%q'", line)
  1764  	}
  1765  	if err := stdin.Close(); err != nil {
  1766  		c.Fatal(err)
  1767  	}
  1768  	finish := make(chan error, 1)
  1769  	go func() {
  1770  		finish <- runCmd.Wait()
  1771  		close(finish)
  1772  	}()
  1773  	select {
  1774  	case err := <-finish:
  1775  		assert.NilError(c, err)
  1776  	case <-time.After(time.Duration(delay) * time.Second):
  1777  		c.Fatal("docker run failed to exit on stdin close")
  1778  	}
  1779  	state := inspectField(c, name, "State.Running")
  1780  
  1781  	if state != "false" {
  1782  		c.Fatal("Container must be stopped after stdin closing")
  1783  	}
  1784  }
  1785  
  1786  // Test run -i --restart xxx doesn't hang
  1787  func (s *DockerSuite) TestRunInteractiveWithRestartPolicy(c *testing.T) {
  1788  	name := "test-inter-restart"
  1789  
  1790  	result := icmd.RunCmd(icmd.Cmd{
  1791  		Command: []string{dockerBinary, "run", "-i", "--name", name, "--restart=always", "busybox", "sh"},
  1792  		Stdin:   bytes.NewBufferString("exit 11"),
  1793  	})
  1794  	defer func() {
  1795  		cli.Docker(cli.Args("stop", name)).Assert(c, icmd.Success)
  1796  	}()
  1797  
  1798  	result.Assert(c, icmd.Expected{ExitCode: 11})
  1799  }
  1800  
  1801  // Test for #2267
  1802  func (s *DockerSuite) TestRunWriteSpecialFilesAndNotCommit(c *testing.T) {
  1803  	// Cannot run on Windows as this files are not present in Windows
  1804  	testRequires(c, DaemonIsLinux)
  1805  
  1806  	testRunWriteSpecialFilesAndNotCommit(c, "writehosts", "/etc/hosts")
  1807  	testRunWriteSpecialFilesAndNotCommit(c, "writehostname", "/etc/hostname")
  1808  	testRunWriteSpecialFilesAndNotCommit(c, "writeresolv", "/etc/resolv.conf")
  1809  }
  1810  
  1811  func testRunWriteSpecialFilesAndNotCommit(c *testing.T, name, path string) {
  1812  	command := fmt.Sprintf("echo test2267 >> %s && cat %s", path, path)
  1813  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command)
  1814  	if !strings.Contains(out, "test2267") {
  1815  		c.Fatalf("%s should contain 'test2267'", path)
  1816  	}
  1817  
  1818  	out, _ = dockerCmd(c, "diff", name)
  1819  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1820  		c.Fatal("diff should be empty")
  1821  	}
  1822  }
  1823  
  1824  func eqToBaseDiff(out string, c *testing.T) bool {
  1825  	name := "eqToBaseDiff" + testutil.GenerateRandomAlphaOnlyString(32)
  1826  	dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello")
  1827  	cID := getIDByName(c, name)
  1828  	baseDiff, _ := dockerCmd(c, "diff", cID)
  1829  	baseArr := strings.Split(baseDiff, "\n")
  1830  	sort.Strings(baseArr)
  1831  	outArr := strings.Split(out, "\n")
  1832  	sort.Strings(outArr)
  1833  	return sliceEq(baseArr, outArr)
  1834  }
  1835  
  1836  func sliceEq(a, b []string) bool {
  1837  	if len(a) != len(b) {
  1838  		return false
  1839  	}
  1840  
  1841  	for i := range a {
  1842  		if a[i] != b[i] {
  1843  			return false
  1844  		}
  1845  	}
  1846  
  1847  	return true
  1848  }
  1849  
  1850  func (s *DockerSuite) TestRunWithBadDevice(c *testing.T) {
  1851  	// Cannot run on Windows as Windows does not support --device
  1852  	testRequires(c, DaemonIsLinux)
  1853  	name := "baddevice"
  1854  	out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1855  
  1856  	if err == nil {
  1857  		c.Fatal("Run should fail with bad device")
  1858  	}
  1859  	expected := `"/etc": not a device node`
  1860  	if !strings.Contains(out, expected) {
  1861  		c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1862  	}
  1863  }
  1864  
  1865  func (s *DockerSuite) TestRunEntrypoint(c *testing.T) {
  1866  	name := "entrypoint"
  1867  
  1868  	out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar")
  1869  	expected := "foobar"
  1870  
  1871  	if out != expected {
  1872  		c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1873  	}
  1874  }
  1875  
  1876  func (s *DockerSuite) TestRunBindMounts(c *testing.T) {
  1877  	testRequires(c, testEnv.IsLocalDaemon)
  1878  	if testEnv.OSType == "linux" {
  1879  		testRequires(c, DaemonIsLinux, NotUserNamespace)
  1880  	}
  1881  
  1882  	if testEnv.OSType == "windows" {
  1883  		// Disabled prior to RS5 due to how volumes are mapped
  1884  		testRequires(c, DaemonIsWindowsAtLeastBuild(osversion.RS5))
  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/tmpx:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmpx")
  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.OSType == "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.OSType != "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 *testing.T) {
  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.OSType == "windows" {
  1945  		// Windows can't support an emptyfs image. Just use the regular Windows image
  1946  		image = testEnv.PlatformDefaults.BaseImage
  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 *testing.T) {
  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 *testing.T) {
  1988  	mac := "12:34:56:78:9a:bc"
  1989  	var out string
  1990  	if testEnv.OSType == "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 *testing.T) {
  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 *testing.T) {
  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 *testing.T) {
  2026  	// TODO Windows. Network settings are not propagated back to inspect.
  2027  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  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, testEnv.IsLocalDaemon, 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 *testing.T) {
  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 *testing.T) {
  2082  	// TODO Windows: Post RS1. Windows does not support nested mounts.
  2083  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  2127  	// Not applicable on Windows as Windows does not support volumes
  2128  	testRequires(c, testEnv.IsLocalDaemon, 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 *testing.T) {
  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 *testing.T) {
  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.OSType)
  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 *testing.T) {
  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 *testing.T) {
  2207  	testRequires(c, testEnv.IsLocalDaemon)
  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  	assert.NilError(c, err)
  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  	assert.NilError(c, err)
  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 *testing.T) {
  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  
  2242  	args := []string{"run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | cat -v"}
  2243  	cont := exec.Command(dockerBinary, args...)
  2244  
  2245  	stdout, err := cont.StdoutPipe()
  2246  	if err != nil {
  2247  		c.Fatal(err)
  2248  	}
  2249  
  2250  	if err := cont.Start(); err != nil {
  2251  		c.Fatal(err)
  2252  	}
  2253  	defer func() { go cont.Wait() }()
  2254  	n, err := ConsumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2255  	if err != nil {
  2256  		c.Fatal(err)
  2257  	}
  2258  
  2259  	expected := 2 * 1024 * 2000
  2260  	if n != expected {
  2261  		c.Fatalf("Expected %d, got %d", expected, n)
  2262  	}
  2263  }
  2264  
  2265  func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *testing.T) {
  2266  	// TODO Windows: -P is not currently supported. Also network
  2267  	// settings are not propagated back.
  2268  	testRequires(c, DaemonIsLinux)
  2269  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2270  
  2271  	id := strings.TrimSpace(out)
  2272  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2273  	var ports nat.PortMap
  2274  	if err := json.Unmarshal([]byte(portstr), &ports); err != nil {
  2275  		c.Fatal(err)
  2276  	}
  2277  	for port, binding := range ports {
  2278  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2279  		if portnum < 3000 || portnum > 3003 {
  2280  			c.Fatalf("Port %d is out of range ", portnum)
  2281  		}
  2282  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2283  			c.Fatalf("Port is not mapped for the port %s", port)
  2284  		}
  2285  	}
  2286  }
  2287  
  2288  func (s *DockerSuite) TestRunExposePort(c *testing.T) {
  2289  	out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  2290  	assert.Assert(c, err != nil, "--expose with an invalid port should error out")
  2291  	assert.Assert(c, strings.Contains(out, "invalid range format for --expose"))
  2292  }
  2293  
  2294  func (s *DockerSuite) TestRunModeIpcHost(c *testing.T) {
  2295  	// Not applicable on Windows as uses Unix-specific capabilities
  2296  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2297  
  2298  	hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2299  	if err != nil {
  2300  		c.Fatal(err)
  2301  	}
  2302  
  2303  	out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2304  	out = strings.Trim(out, "\n")
  2305  	if hostIpc != out {
  2306  		c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  2307  	}
  2308  
  2309  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2310  	out = strings.Trim(out, "\n")
  2311  	if hostIpc == out {
  2312  		c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  2313  	}
  2314  }
  2315  
  2316  func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *testing.T) {
  2317  	// Not applicable on Windows as uses Unix-specific capabilities
  2318  	testRequires(c, DaemonIsLinux)
  2319  	out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  2320  	if !strings.Contains(out, "abcd1234") || err == nil {
  2321  		c.Fatalf("run IPC from a non exists container should with correct error out")
  2322  	}
  2323  }
  2324  
  2325  func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *testing.T) {
  2326  	// Not applicable on Windows as uses Unix-specific capabilities
  2327  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  2328  
  2329  	out, _ := dockerCmd(c, "create", "busybox")
  2330  
  2331  	id := strings.TrimSpace(out)
  2332  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  2333  	if err == nil {
  2334  		c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  2335  	}
  2336  }
  2337  
  2338  func (s *DockerSuite) TestRunModePIDContainer(c *testing.T) {
  2339  	// Not applicable on Windows as uses Unix-specific capabilities
  2340  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  2341  
  2342  	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top")
  2343  
  2344  	id := strings.TrimSpace(out)
  2345  	state := inspectField(c, id, "State.Running")
  2346  	if state != "true" {
  2347  		c.Fatal("Container state is 'not running'")
  2348  	}
  2349  	pid1 := inspectField(c, id, "State.Pid")
  2350  
  2351  	parentContainerPid, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/pid", pid1))
  2352  	if err != nil {
  2353  		c.Fatal(err)
  2354  	}
  2355  
  2356  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid")
  2357  	out = strings.Trim(out, "\n")
  2358  	if parentContainerPid != out {
  2359  		c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out)
  2360  	}
  2361  }
  2362  
  2363  func (s *DockerSuite) TestRunModePIDContainerNotExists(c *testing.T) {
  2364  	// Not applicable on Windows as uses Unix-specific capabilities
  2365  	testRequires(c, DaemonIsLinux)
  2366  	out, _, err := dockerCmdWithError("run", "-d", "--pid", "container:abcd1234", "busybox", "top")
  2367  	if !strings.Contains(out, "abcd1234") || err == nil {
  2368  		c.Fatalf("run PID from a non exists container should with correct error out")
  2369  	}
  2370  }
  2371  
  2372  func (s *DockerSuite) TestRunModePIDContainerNotRunning(c *testing.T) {
  2373  	// Not applicable on Windows as uses Unix-specific capabilities
  2374  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  2375  
  2376  	out, _ := dockerCmd(c, "create", "busybox")
  2377  
  2378  	id := strings.TrimSpace(out)
  2379  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox")
  2380  	if err == nil {
  2381  		c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err)
  2382  	}
  2383  }
  2384  
  2385  func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *testing.T) {
  2386  	// Not applicable on Windows as uses Unix-specific capabilities
  2387  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2388  
  2389  	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")
  2390  	defer os.Remove("/dev/mqueue/toto")
  2391  	defer os.Remove("/dev/shm/test")
  2392  	volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm")
  2393  	assert.NilError(c, err)
  2394  	if volPath != "/dev/shm" {
  2395  		c.Fatalf("volumePath should have been /dev/shm, was %s", volPath)
  2396  	}
  2397  
  2398  	out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test")
  2399  	if out != "test" {
  2400  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", out)
  2401  	}
  2402  
  2403  	// Check that the mq was created
  2404  	if _, err := os.Stat("/dev/mqueue/toto"); err != nil {
  2405  		c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error())
  2406  	}
  2407  }
  2408  
  2409  func (s *DockerSuite) TestContainerNetworkMode(c *testing.T) {
  2410  	// Not applicable on Windows as uses Unix-specific capabilities
  2411  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  2412  
  2413  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2414  	id := strings.TrimSpace(out)
  2415  	assert.NilError(c, waitRun(id))
  2416  	pid1 := inspectField(c, id, "State.Pid")
  2417  
  2418  	parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2419  	if err != nil {
  2420  		c.Fatal(err)
  2421  	}
  2422  
  2423  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2424  	out = strings.Trim(out, "\n")
  2425  	if parentContainerNet != out {
  2426  		c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  2427  	}
  2428  }
  2429  
  2430  func (s *DockerSuite) TestRunModePIDHost(c *testing.T) {
  2431  	// Not applicable on Windows as uses Unix-specific capabilities
  2432  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2433  
  2434  	hostPid, err := os.Readlink("/proc/1/ns/pid")
  2435  	if err != nil {
  2436  		c.Fatal(err)
  2437  	}
  2438  
  2439  	out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2440  	out = strings.Trim(out, "\n")
  2441  	if hostPid != out {
  2442  		c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  2443  	}
  2444  
  2445  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2446  	out = strings.Trim(out, "\n")
  2447  	if hostPid == out {
  2448  		c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  2449  	}
  2450  }
  2451  
  2452  func (s *DockerSuite) TestRunModeUTSHost(c *testing.T) {
  2453  	// Not applicable on Windows as uses Unix-specific capabilities
  2454  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  2455  
  2456  	hostUTS, err := os.Readlink("/proc/1/ns/uts")
  2457  	if err != nil {
  2458  		c.Fatal(err)
  2459  	}
  2460  
  2461  	out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  2462  	out = strings.Trim(out, "\n")
  2463  	if hostUTS != out {
  2464  		c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  2465  	}
  2466  
  2467  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  2468  	out = strings.Trim(out, "\n")
  2469  	if hostUTS == out {
  2470  		c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  2471  	}
  2472  
  2473  	out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps")
  2474  	assert.Assert(c, strings.Contains(out, runconfig.ErrConflictUTSHostname.Error()))
  2475  }
  2476  
  2477  func (s *DockerSuite) TestRunTLSVerify(c *testing.T) {
  2478  	// Remote daemons use TLS and this test is not applicable when TLS is required.
  2479  	testRequires(c, testEnv.IsLocalDaemon)
  2480  	if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  2481  		c.Fatalf("Should have worked: %v:\n%v", err, out)
  2482  	}
  2483  
  2484  	// Regardless of whether we specify true or false we need to
  2485  	// test to make sure tls is turned on if --tlsverify is specified at all
  2486  	result := dockerCmdWithResult("--tlsverify=false", "ps")
  2487  	result.Assert(c, icmd.Expected{ExitCode: 1, Err: "error during connect"})
  2488  
  2489  	result = dockerCmdWithResult("--tlsverify=true", "ps")
  2490  	result.Assert(c, icmd.Expected{ExitCode: 1, Err: "cert"})
  2491  }
  2492  
  2493  func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *testing.T) {
  2494  	// TODO Windows. Once moved to libnetwork/CNM, this may be able to be
  2495  	// re-instated.
  2496  	testRequires(c, DaemonIsLinux)
  2497  	// first find allocator current position
  2498  	out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2499  
  2500  	id := strings.TrimSpace(out)
  2501  	out, _ = dockerCmd(c, "port", id)
  2502  
  2503  	out = strings.TrimSpace(out)
  2504  	if out == "" {
  2505  		c.Fatal("docker port command output is empty")
  2506  	}
  2507  	out = strings.Split(out, ":")[1]
  2508  	lastPort, err := strconv.Atoi(out)
  2509  	if err != nil {
  2510  		c.Fatal(err)
  2511  	}
  2512  	port := lastPort + 1
  2513  	l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2514  	if err != nil {
  2515  		c.Fatal(err)
  2516  	}
  2517  	defer l.Close()
  2518  
  2519  	out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2520  
  2521  	id = strings.TrimSpace(out)
  2522  	dockerCmd(c, "port", id)
  2523  }
  2524  
  2525  func (s *DockerSuite) TestRunTTYWithPipe(c *testing.T) {
  2526  	errChan := make(chan error, 1)
  2527  	go func() {
  2528  		defer close(errChan)
  2529  
  2530  		cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2531  		if _, err := cmd.StdinPipe(); err != nil {
  2532  			errChan <- err
  2533  			return
  2534  		}
  2535  
  2536  		expected := "the input device is not a TTY"
  2537  		if runtime.GOOS == "windows" {
  2538  			expected += ".  If you are using mintty, try prefixing the command with 'winpty'"
  2539  		}
  2540  		if out, _, err := runCommandWithOutput(cmd); err == nil {
  2541  			errChan <- fmt.Errorf("run should have failed")
  2542  			return
  2543  		} else if !strings.Contains(out, expected) {
  2544  			errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2545  			return
  2546  		}
  2547  	}()
  2548  
  2549  	select {
  2550  	case err := <-errChan:
  2551  		assert.NilError(c, err)
  2552  	case <-time.After(30 * time.Second):
  2553  		c.Fatal("container is running but should have failed")
  2554  	}
  2555  }
  2556  
  2557  func (s *DockerSuite) TestRunNonLocalMacAddress(c *testing.T) {
  2558  	addr := "00:16:3E:08:00:50"
  2559  	args := []string{"run", "--mac-address", addr}
  2560  	expected := addr
  2561  
  2562  	if testEnv.OSType != "windows" {
  2563  		args = append(args, "busybox", "ifconfig")
  2564  	} else {
  2565  		args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all")
  2566  		expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
  2567  	}
  2568  
  2569  	if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
  2570  		c.Fatalf("Output should have contained %q: %s", expected, out)
  2571  	}
  2572  }
  2573  
  2574  func (s *DockerSuite) TestRunNetHost(c *testing.T) {
  2575  	// Not applicable on Windows as uses Unix-specific capabilities
  2576  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2577  
  2578  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2579  	if err != nil {
  2580  		c.Fatal(err)
  2581  	}
  2582  
  2583  	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2584  	out = strings.Trim(out, "\n")
  2585  	if hostNet != out {
  2586  		c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  2587  	}
  2588  
  2589  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  2590  	out = strings.Trim(out, "\n")
  2591  	if hostNet == out {
  2592  		c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  2593  	}
  2594  }
  2595  
  2596  func (s *DockerSuite) TestRunNetHostTwiceSameName(c *testing.T) {
  2597  	// TODO Windows. As Windows networking evolves and converges towards
  2598  	// CNM, this test may be possible to enable on Windows.
  2599  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2600  
  2601  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2602  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2603  }
  2604  
  2605  func (s *DockerSuite) TestRunNetContainerWhichHost(c *testing.T) {
  2606  	// Not applicable on Windows as uses Unix-specific capabilities
  2607  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  2608  
  2609  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2610  	if err != nil {
  2611  		c.Fatal(err)
  2612  	}
  2613  
  2614  	dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2615  
  2616  	out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2617  	out = strings.Trim(out, "\n")
  2618  	if hostNet != out {
  2619  		c.Fatalf("Container should have host network namespace")
  2620  	}
  2621  }
  2622  
  2623  func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *testing.T) {
  2624  	// TODO Windows. This may be possible to enable in the future. However,
  2625  	// Windows does not currently support --expose, or populate the network
  2626  	// settings seen through inspect.
  2627  	testRequires(c, DaemonIsLinux)
  2628  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2629  
  2630  	id := strings.TrimSpace(out)
  2631  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2632  
  2633  	var ports nat.PortMap
  2634  	err := json.Unmarshal([]byte(portstr), &ports)
  2635  	assert.NilError(c, err, "failed to unmarshal: %v", portstr)
  2636  	for port, binding := range ports {
  2637  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2638  		if portnum < 3000 || portnum > 3003 {
  2639  			c.Fatalf("Port %d is out of range ", portnum)
  2640  		}
  2641  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2642  			c.Fatal("Port is not mapped for the port "+port, out)
  2643  		}
  2644  	}
  2645  }
  2646  
  2647  func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *testing.T) {
  2648  	runSleepingContainer(c, "--name=testrunsetdefaultrestartpolicy")
  2649  	out := inspectField(c, "testrunsetdefaultrestartpolicy", "HostConfig.RestartPolicy.Name")
  2650  	if out != "no" {
  2651  		c.Fatalf("Set default restart policy failed")
  2652  	}
  2653  }
  2654  
  2655  func (s *DockerSuite) TestRunRestartMaxRetries(c *testing.T) {
  2656  	out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  2657  	timeout := 10 * time.Second
  2658  	if testEnv.OSType == "windows" {
  2659  		timeout = 120 * time.Second
  2660  	}
  2661  
  2662  	id := strings.TrimSpace(out)
  2663  	if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
  2664  		c.Fatal(err)
  2665  	}
  2666  
  2667  	count := inspectField(c, id, "RestartCount")
  2668  	if count != "3" {
  2669  		c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2670  	}
  2671  
  2672  	MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2673  	if MaximumRetryCount != "3" {
  2674  		c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2675  	}
  2676  }
  2677  
  2678  func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *testing.T) {
  2679  	dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  2680  }
  2681  
  2682  func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *testing.T) {
  2683  	// Not applicable on Windows which does not support --read-only
  2684  	testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  2685  
  2686  	testPriv := true
  2687  	// don't test privileged mode subtest if user namespaces enabled
  2688  	if root := os.Getenv("DOCKER_REMAP_ROOT"); root != "" {
  2689  		testPriv = false
  2690  	}
  2691  	testReadOnlyFile(c, testPriv, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname")
  2692  }
  2693  
  2694  func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) {
  2695  	// Not applicable on Windows due to use of Unix specific functionality, plus
  2696  	// the use of --read-only which is not supported.
  2697  	testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  2698  
  2699  	// Ensure we have not broken writing /dev/pts
  2700  	out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  2701  	if status != 0 {
  2702  		c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  2703  	}
  2704  	expected := "type devpts (rw,"
  2705  	if !strings.Contains(out, expected) {
  2706  		c.Fatalf("expected output to contain %s but contains %s", expected, out)
  2707  	}
  2708  }
  2709  
  2710  func testReadOnlyFile(c *testing.T, testPriv bool, filenames ...string) {
  2711  	touch := "touch " + strings.Join(filenames, " ")
  2712  	out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch)
  2713  	assert.ErrorContains(c, err, "")
  2714  
  2715  	for _, f := range filenames {
  2716  		expected := "touch: " + f + ": Read-only file system"
  2717  		assert.Assert(c, strings.Contains(out, expected))
  2718  	}
  2719  
  2720  	if !testPriv {
  2721  		return
  2722  	}
  2723  
  2724  	out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch)
  2725  	assert.ErrorContains(c, err, "")
  2726  
  2727  	for _, f := range filenames {
  2728  		expected := "touch: " + f + ": Read-only file system"
  2729  		assert.Assert(c, strings.Contains(out, expected))
  2730  	}
  2731  }
  2732  
  2733  func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *testing.T) {
  2734  	// Not applicable on Windows which does not support --link
  2735  	testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  2736  
  2737  	dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  2738  
  2739  	out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  2740  	if !strings.Contains(out, "testlinked") {
  2741  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  2742  	}
  2743  }
  2744  
  2745  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *testing.T) {
  2746  	// Not applicable on Windows which does not support either --read-only or --dns.
  2747  	testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  2748  
  2749  	out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  2750  	if !strings.Contains(out, "1.1.1.1") {
  2751  		c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  2752  	}
  2753  }
  2754  
  2755  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *testing.T) {
  2756  	// Not applicable on Windows which does not support --read-only
  2757  	testRequires(c, DaemonIsLinux, UserNamespaceROMount)
  2758  
  2759  	out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  2760  	if !strings.Contains(out, "testreadonly") {
  2761  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  2762  	}
  2763  }
  2764  
  2765  func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *testing.T) {
  2766  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2767  	runSleepingContainer(c, "--name=voltest", "-v", prefix+"/foo")
  2768  	runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest")
  2769  
  2770  	// Remove the main volume container and restart the consuming container
  2771  	dockerCmd(c, "rm", "-f", "voltest")
  2772  
  2773  	// This should not fail since the volumes-from were already applied
  2774  	dockerCmd(c, "restart", "restarter")
  2775  }
  2776  
  2777  // run container with --rm should remove container if exit code != 0
  2778  func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *testing.T) {
  2779  	existingContainers := ExistingContainerIDs(c)
  2780  	name := "flowers"
  2781  	cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "ls", "/notexists")).Assert(c, icmd.Expected{
  2782  		ExitCode: 1,
  2783  	})
  2784  
  2785  	out := cli.DockerCmd(c, "ps", "-q", "-a").Combined()
  2786  	out = RemoveOutputForExistingElements(out, existingContainers)
  2787  	if out != "" {
  2788  		c.Fatal("Expected not to have containers", out)
  2789  	}
  2790  }
  2791  
  2792  func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *testing.T) {
  2793  	existingContainers := ExistingContainerIDs(c)
  2794  	name := "sparkles"
  2795  	cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "commandNotFound")).Assert(c, icmd.Expected{
  2796  		ExitCode: 127,
  2797  	})
  2798  	out := cli.DockerCmd(c, "ps", "-q", "-a").Combined()
  2799  	out = RemoveOutputForExistingElements(out, existingContainers)
  2800  	if out != "" {
  2801  		c.Fatal("Expected not to have containers", out)
  2802  	}
  2803  }
  2804  
  2805  func (s *DockerSuite) TestRunPIDHostWithChildIsKillable(c *testing.T) {
  2806  	// Not applicable on Windows as uses Unix specific functionality
  2807  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2808  	name := "ibuildthecloud"
  2809  	dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2810  
  2811  	assert.Assert(c, waitRun(name) == nil)
  2812  
  2813  	errchan := make(chan error, 1)
  2814  	go func() {
  2815  		if out, _, err := dockerCmdWithError("kill", name); err != nil {
  2816  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  2817  		}
  2818  		close(errchan)
  2819  	}()
  2820  	select {
  2821  	case err := <-errchan:
  2822  		assert.NilError(c, err)
  2823  	case <-time.After(5 * time.Second):
  2824  		c.Fatal("Kill container timed out")
  2825  	}
  2826  }
  2827  
  2828  func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *testing.T) {
  2829  	// TODO Windows. This may be possible to enable once Windows supports
  2830  	// memory limits on containers
  2831  	testRequires(c, DaemonIsLinux)
  2832  	// this memory limit is 1 byte less than the min, which is 4MB
  2833  	// https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  2834  	out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  2835  	if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2836  		c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2837  	}
  2838  }
  2839  
  2840  func (s *DockerSuite) TestRunWriteToProcAsound(c *testing.T) {
  2841  	// Not applicable on Windows as uses Unix specific functionality
  2842  	testRequires(c, DaemonIsLinux)
  2843  	_, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2844  	if err == nil || code == 0 {
  2845  		c.Fatal("standard container should not be able to write to /proc/asound")
  2846  	}
  2847  }
  2848  
  2849  func (s *DockerSuite) TestRunReadProcTimer(c *testing.T) {
  2850  	// Not applicable on Windows as uses Unix specific functionality
  2851  	testRequires(c, DaemonIsLinux)
  2852  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  2853  	if code != 0 {
  2854  		return
  2855  	}
  2856  	if err != nil {
  2857  		c.Fatal(err)
  2858  	}
  2859  	if strings.Trim(out, "\n ") != "" {
  2860  		c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2861  	}
  2862  }
  2863  
  2864  func (s *DockerSuite) TestRunReadProcLatency(c *testing.T) {
  2865  	// Not applicable on Windows as uses Unix specific functionality
  2866  	testRequires(c, DaemonIsLinux)
  2867  	// some kernels don't have this configured so skip the test if this file is not found
  2868  	// on the host running the tests.
  2869  	if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2870  		c.Skip("kernel doesn't have latency_stats configured")
  2871  		return
  2872  	}
  2873  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  2874  	if code != 0 {
  2875  		return
  2876  	}
  2877  	if err != nil {
  2878  		c.Fatal(err)
  2879  	}
  2880  	if strings.Trim(out, "\n ") != "" {
  2881  		c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2882  	}
  2883  }
  2884  
  2885  func (s *DockerSuite) TestRunReadFilteredProc(c *testing.T) {
  2886  	// Not applicable on Windows as uses Unix specific functionality
  2887  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  2888  
  2889  	testReadPaths := []string{
  2890  		"/proc/latency_stats",
  2891  		"/proc/timer_stats",
  2892  		"/proc/kcore",
  2893  	}
  2894  	for i, filePath := range testReadPaths {
  2895  		name := fmt.Sprintf("procsieve-%d", i)
  2896  		shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2897  
  2898  		out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2899  		if exitCode != 0 {
  2900  			return
  2901  		}
  2902  		if err != nil {
  2903  			c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2904  		}
  2905  	}
  2906  }
  2907  
  2908  func (s *DockerSuite) TestMountIntoProc(c *testing.T) {
  2909  	// Not applicable on Windows as uses Unix specific functionality
  2910  	testRequires(c, DaemonIsLinux)
  2911  	_, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  2912  	if err == nil || code == 0 {
  2913  		c.Fatal("container should not be able to mount into /proc")
  2914  	}
  2915  }
  2916  
  2917  func (s *DockerSuite) TestMountIntoSys(c *testing.T) {
  2918  	// Not applicable on Windows as uses Unix specific functionality
  2919  	testRequires(c, DaemonIsLinux)
  2920  	testRequires(c, NotUserNamespace)
  2921  	dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2922  }
  2923  
  2924  func (s *DockerSuite) TestRunUnshareProc(c *testing.T) {
  2925  	// Not applicable on Windows as uses Unix specific functionality
  2926  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  2927  
  2928  	// In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run.
  2929  	errChan := make(chan error)
  2930  
  2931  	go func() {
  2932  		name := "acidburn"
  2933  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount")
  2934  		if err == nil ||
  2935  			!(strings.Contains(strings.ToLower(out), "permission denied") ||
  2936  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  2937  			errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err)
  2938  		} else {
  2939  			errChan <- nil
  2940  		}
  2941  	}()
  2942  
  2943  	go func() {
  2944  		name := "cereal"
  2945  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
  2946  		if err == nil ||
  2947  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  2948  				strings.Contains(strings.ToLower(out), "permission denied") ||
  2949  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  2950  			errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  2951  		} else {
  2952  			errChan <- nil
  2953  		}
  2954  	}()
  2955  
  2956  	/* Ensure still fails if running privileged with the default policy */
  2957  	go func() {
  2958  		name := "crashoverride"
  2959  		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")
  2960  		if err == nil ||
  2961  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  2962  				strings.Contains(strings.ToLower(out), "permission denied") ||
  2963  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  2964  			errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  2965  		} else {
  2966  			errChan <- nil
  2967  		}
  2968  	}()
  2969  
  2970  	var retErr error
  2971  	for i := 0; i < 3; i++ {
  2972  		err := <-errChan
  2973  		if retErr == nil && err != nil {
  2974  			retErr = err
  2975  		}
  2976  	}
  2977  	if retErr != nil {
  2978  		c.Fatal(retErr)
  2979  	}
  2980  }
  2981  
  2982  func (s *DockerSuite) TestRunPublishPort(c *testing.T) {
  2983  	// TODO Windows: This may be possible once Windows moves to libnetwork and CNM
  2984  	testRequires(c, DaemonIsLinux)
  2985  	dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2986  	out, _ := dockerCmd(c, "port", "test")
  2987  	out = strings.Trim(out, "\r\n")
  2988  	if out != "" {
  2989  		c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2990  	}
  2991  }
  2992  
  2993  // Issue #10184.
  2994  func (s *DockerSuite) TestDevicePermissions(c *testing.T) {
  2995  	// Not applicable on Windows as uses Unix specific functionality
  2996  	testRequires(c, DaemonIsLinux)
  2997  	const permissions = "crw-rw-rw-"
  2998  	out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2999  	if status != 0 {
  3000  		c.Fatalf("expected status 0, got %d", status)
  3001  	}
  3002  	if !strings.HasPrefix(out, permissions) {
  3003  		c.Fatalf("output should begin with %q, got %q", permissions, out)
  3004  	}
  3005  }
  3006  
  3007  func (s *DockerSuite) TestRunCapAddCHOWN(c *testing.T) {
  3008  	// Not applicable on Windows as uses Unix specific functionality
  3009  	testRequires(c, DaemonIsLinux)
  3010  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  3011  
  3012  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  3013  		c.Fatalf("expected output ok received %s", actual)
  3014  	}
  3015  }
  3016  
  3017  // https://github.com/docker/docker/pull/14498
  3018  func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *testing.T) {
  3019  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  3020  
  3021  	dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true")
  3022  
  3023  	dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  3024  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  3025  
  3026  	if testEnv.OSType != "windows" {
  3027  		mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test")
  3028  		assert.NilError(c, err, "failed to inspect mount point")
  3029  		if mRO.RW {
  3030  			c.Fatalf("Expected RO volume was RW")
  3031  		}
  3032  	}
  3033  
  3034  	mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test")
  3035  	assert.NilError(c, err, "failed to inspect mount point")
  3036  	if !mRW.RW {
  3037  		c.Fatalf("Expected RW volume was RO")
  3038  	}
  3039  }
  3040  
  3041  func (s *DockerSuite) TestRunWriteFilteredProc(c *testing.T) {
  3042  	// Not applicable on Windows as uses Unix specific functionality
  3043  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  3044  
  3045  	testWritePaths := []string{
  3046  		/* modprobe and core_pattern should both be denied by generic
  3047  		 * policy of denials for /proc/sys/kernel. These files have been
  3048  		 * picked to be checked as they are particularly sensitive to writes */
  3049  		"/proc/sys/kernel/modprobe",
  3050  		"/proc/sys/kernel/core_pattern",
  3051  		"/proc/sysrq-trigger",
  3052  		"/proc/kcore",
  3053  	}
  3054  	for i, filePath := range testWritePaths {
  3055  		name := fmt.Sprintf("writeprocsieve-%d", i)
  3056  
  3057  		shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  3058  		out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  3059  		if code != 0 {
  3060  			return
  3061  		}
  3062  		if err != nil {
  3063  			c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  3064  		}
  3065  	}
  3066  }
  3067  
  3068  func (s *DockerSuite) TestRunNetworkFilesBindMount(c *testing.T) {
  3069  	// Not applicable on Windows as uses Unix specific functionality
  3070  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  3071  
  3072  	expected := "test123"
  3073  
  3074  	filename := createTmpFile(c, expected)
  3075  	defer os.Remove(filename)
  3076  
  3077  	// for user namespaced test runs, the temp file must be accessible to unprivileged root
  3078  	if err := os.Chmod(filename, 0646); err != nil {
  3079  		c.Fatalf("error modifying permissions of %s: %v", filename, err)
  3080  	}
  3081  
  3082  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3083  
  3084  	for i := range nwfiles {
  3085  		actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  3086  		if actual != expected {
  3087  			c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  3088  		}
  3089  	}
  3090  }
  3091  
  3092  func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *testing.T) {
  3093  	// Not applicable on Windows as uses Unix specific functionality
  3094  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  3095  
  3096  	filename := createTmpFile(c, "test123")
  3097  	defer os.Remove(filename)
  3098  
  3099  	// for user namespaced test runs, the temp file must be accessible to unprivileged root
  3100  	if err := os.Chmod(filename, 0646); err != nil {
  3101  		c.Fatalf("error modifying permissions of %s: %v", filename, err)
  3102  	}
  3103  
  3104  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3105  
  3106  	for i := range nwfiles {
  3107  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  3108  		if err == nil || exitCode == 0 {
  3109  			c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  3110  		}
  3111  	}
  3112  }
  3113  
  3114  func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *testing.T) {
  3115  	// Not applicable on Windows as uses Unix specific functionality
  3116  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, UserNamespaceROMount)
  3117  
  3118  	filename := createTmpFile(c, "test123")
  3119  	defer os.Remove(filename)
  3120  
  3121  	// for user namespaced test runs, the temp file must be accessible to unprivileged root
  3122  	if err := os.Chmod(filename, 0646); err != nil {
  3123  		c.Fatalf("error modifying permissions of %s: %v", filename, err)
  3124  	}
  3125  
  3126  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3127  
  3128  	for i := range nwfiles {
  3129  		_, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  3130  		if exitCode != 0 {
  3131  			c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3132  		}
  3133  	}
  3134  
  3135  	for i := range nwfiles {
  3136  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  3137  		if err == nil || exitCode == 0 {
  3138  			c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3139  		}
  3140  	}
  3141  }
  3142  
  3143  func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *testing.T) {
  3144  	// Not applicable on Windows as uses Unix specific functionality
  3145  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  3146  
  3147  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  3148  	id := strings.TrimSpace(out)
  3149  	assert.NilError(c, waitRun(id))
  3150  	pid1 := inspectField(c, id, "State.Pid")
  3151  
  3152  	_, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  3153  	if err != nil {
  3154  		c.Fatal(err)
  3155  	}
  3156  }
  3157  
  3158  func (s *DockerSuite) TestAppArmorDeniesPtrace(c *testing.T) {
  3159  	// Not applicable on Windows as uses Unix specific functionality
  3160  	testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux)
  3161  
  3162  	// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  3163  	// itself, but pid>1 should not be able to trace pid1.
  3164  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net")
  3165  	if exitCode == 0 {
  3166  		c.Fatal("ptrace was not successfully restricted by AppArmor")
  3167  	}
  3168  }
  3169  
  3170  func (s *DockerSuite) TestAppArmorTraceSelf(c *testing.T) {
  3171  	// Not applicable on Windows as uses Unix specific functionality
  3172  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, Apparmor)
  3173  
  3174  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  3175  	if exitCode != 0 {
  3176  		c.Fatal("ptrace of self failed.")
  3177  	}
  3178  }
  3179  
  3180  func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *testing.T) {
  3181  	// Not applicable on Windows as uses Unix specific functionality
  3182  	testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux, NotUserNamespace)
  3183  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  3184  	if exitCode == 0 {
  3185  		// If our test failed, attempt to repair the host system...
  3186  		_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  3187  		if exitCode == 0 {
  3188  			c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  3189  		}
  3190  	}
  3191  }
  3192  
  3193  func (s *DockerSuite) TestRunCapAddSYSTIME(c *testing.T) {
  3194  	// Not applicable on Windows as uses Unix specific functionality
  3195  	testRequires(c, DaemonIsLinux)
  3196  
  3197  	dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  3198  }
  3199  
  3200  // run create container failed should clean up the container
  3201  func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *testing.T) {
  3202  	// TODO Windows. This may be possible to enable once link is supported
  3203  	testRequires(c, DaemonIsLinux)
  3204  	name := "unique_name"
  3205  	_, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  3206  	assert.Assert(c, err != nil, "Expected docker run to fail!")
  3207  
  3208  	containerID, err := inspectFieldWithError(name, "Id")
  3209  	assert.Assert(c, err != nil, "Expected not to have this container: %s!", containerID)
  3210  	assert.Equal(c, containerID, "", fmt.Sprintf("Expected not to have this container: %s!", containerID))
  3211  }
  3212  
  3213  func (s *DockerSuite) TestRunNamedVolume(c *testing.T) {
  3214  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  3215  	testRequires(c, DaemonIsLinux)
  3216  	dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar")
  3217  
  3218  	out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3219  	assert.Equal(c, strings.TrimSpace(out), "hello")
  3220  
  3221  	out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3222  	assert.Equal(c, strings.TrimSpace(out), "hello")
  3223  }
  3224  
  3225  func (s *DockerSuite) TestRunWithUlimits(c *testing.T) {
  3226  	// Not applicable on Windows as uses Unix specific functionality
  3227  	testRequires(c, DaemonIsLinux)
  3228  
  3229  	out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
  3230  	ul := strings.TrimSpace(out)
  3231  	if ul != "42" {
  3232  		c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
  3233  	}
  3234  }
  3235  
  3236  func (s *DockerSuite) TestRunContainerWithCgroupParent(c *testing.T) {
  3237  	// Not applicable on Windows as uses Unix specific functionality
  3238  	testRequires(c, DaemonIsLinux)
  3239  
  3240  	// cgroup-parent relative path
  3241  	testRunContainerWithCgroupParent(c, "test", "cgroup-test")
  3242  
  3243  	// cgroup-parent absolute path
  3244  	testRunContainerWithCgroupParent(c, "/cgroup-parent/test", "cgroup-test-absolute")
  3245  }
  3246  
  3247  func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) {
  3248  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3249  	if err != nil {
  3250  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
  3251  	}
  3252  	cgroupPaths := ParseCgroupPaths(out)
  3253  	if len(cgroupPaths) == 0 {
  3254  		c.Fatalf("unexpected output - %q", out)
  3255  	}
  3256  	id := getIDByName(c, name)
  3257  	expectedCgroup := path.Join(cgroupParent, id)
  3258  	found := false
  3259  	for _, path := range cgroupPaths {
  3260  		if strings.HasSuffix(path, expectedCgroup) {
  3261  			found = true
  3262  			break
  3263  		}
  3264  	}
  3265  	if !found {
  3266  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3267  	}
  3268  }
  3269  
  3270  // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
  3271  func (s *DockerSuite) TestRunInvalidCgroupParent(c *testing.T) {
  3272  	// Not applicable on Windows as uses Unix specific functionality
  3273  	testRequires(c, DaemonIsLinux)
  3274  
  3275  	testRunInvalidCgroupParent(c, "../../../../../../../../SHOULD_NOT_EXIST", "SHOULD_NOT_EXIST", "cgroup-invalid-test")
  3276  
  3277  	testRunInvalidCgroupParent(c, "/../../../../../../../../SHOULD_NOT_EXIST", "/SHOULD_NOT_EXIST", "cgroup-absolute-invalid-test")
  3278  }
  3279  
  3280  func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, name string) {
  3281  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3282  	if err != nil {
  3283  		// XXX: This may include a daemon crash.
  3284  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err)
  3285  	}
  3286  
  3287  	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
  3288  	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
  3289  		c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
  3290  	}
  3291  
  3292  	cgroupPaths := ParseCgroupPaths(out)
  3293  	if len(cgroupPaths) == 0 {
  3294  		c.Fatalf("unexpected output - %q", out)
  3295  	}
  3296  	id := getIDByName(c, name)
  3297  	expectedCgroup := path.Join(cleanCgroupParent, id)
  3298  	found := false
  3299  	for _, path := range cgroupPaths {
  3300  		if strings.HasSuffix(path, expectedCgroup) {
  3301  			found = true
  3302  			break
  3303  		}
  3304  	}
  3305  	if !found {
  3306  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3307  	}
  3308  }
  3309  
  3310  func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *testing.T) {
  3311  	// Not applicable on Windows as uses Unix specific functionality
  3312  	// --read-only + userns has remount issues
  3313  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3314  
  3315  	filename := "/sys/fs/cgroup/devices/test123"
  3316  	out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
  3317  	if err == nil {
  3318  		c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
  3319  	}
  3320  	expected := "Read-only file system"
  3321  	if !strings.Contains(out, expected) {
  3322  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  3323  	}
  3324  }
  3325  
  3326  func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *testing.T) {
  3327  	// Not applicable on Windows which does not support --net=container
  3328  	testRequires(c, DaemonIsLinux)
  3329  	out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
  3330  	if err == nil || !strings.Contains(out, "cannot join own network") {
  3331  		c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
  3332  	}
  3333  }
  3334  
  3335  func (s *DockerSuite) TestRunContainerNetModeWithDNSMacHosts(c *testing.T) {
  3336  	// Not applicable on Windows which does not support --net=container
  3337  	testRequires(c, DaemonIsLinux)
  3338  	out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
  3339  	if err != nil {
  3340  		c.Fatalf("failed to run container: %v, output: %q", err, out)
  3341  	}
  3342  
  3343  	out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
  3344  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) {
  3345  		c.Fatalf("run --net=container with --dns should error out")
  3346  	}
  3347  
  3348  	out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
  3349  	if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) {
  3350  		c.Fatalf("run --net=container with --mac-address should error out")
  3351  	}
  3352  
  3353  	out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
  3354  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) {
  3355  		c.Fatalf("run --net=container with --add-host should error out")
  3356  	}
  3357  }
  3358  
  3359  func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *testing.T) {
  3360  	// Not applicable on Windows which does not support --net=container
  3361  	testRequires(c, DaemonIsLinux)
  3362  	dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  3363  
  3364  	out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
  3365  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3366  		c.Fatalf("run --net=container with -p should error out")
  3367  	}
  3368  
  3369  	out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
  3370  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3371  		c.Fatalf("run --net=container with -P should error out")
  3372  	}
  3373  
  3374  	out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
  3375  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) {
  3376  		c.Fatalf("run --net=container with --expose should error out")
  3377  	}
  3378  }
  3379  
  3380  func (s *DockerSuite) TestRunLinkToContainerNetMode(c *testing.T) {
  3381  	// Not applicable on Windows which does not support --net=container or --link
  3382  	testRequires(c, DaemonIsLinux)
  3383  	dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
  3384  	dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  3385  	dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
  3386  	dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  3387  	dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
  3388  }
  3389  
  3390  func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *testing.T) {
  3391  	// TODO Windows: This may be possible to convert.
  3392  	testRequires(c, DaemonIsLinux)
  3393  	out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  3394  
  3395  	var (
  3396  		count = 0
  3397  		parts = strings.Split(out, "\n")
  3398  	)
  3399  
  3400  	for _, l := range parts {
  3401  		if l != "" {
  3402  			count++
  3403  		}
  3404  	}
  3405  
  3406  	if count != 1 {
  3407  		c.Fatalf("Wrong interface count in container %d", count)
  3408  	}
  3409  
  3410  	if !strings.HasPrefix(out, "1: lo") {
  3411  		c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  3412  	}
  3413  }
  3414  
  3415  // Issue #4681
  3416  func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *testing.T) {
  3417  	if testEnv.OSType == "windows" {
  3418  		dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1")
  3419  	} else {
  3420  		dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  3421  	}
  3422  }
  3423  
  3424  func (s *DockerSuite) TestRunModeNetContainerHostname(c *testing.T) {
  3425  	// Windows does not support --net=container
  3426  	testRequires(c, DaemonIsLinux)
  3427  
  3428  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  3429  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
  3430  	out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  3431  
  3432  	if out1 != out {
  3433  		c.Fatal("containers with shared net namespace should have same hostname")
  3434  	}
  3435  }
  3436  
  3437  func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) {
  3438  	// TODO Windows: Network settings are not currently propagated. This may
  3439  	// be resolved in the future with the move to libnetwork and CNM.
  3440  	testRequires(c, DaemonIsLinux)
  3441  	out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  3442  	id := strings.TrimSpace(out)
  3443  	res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress")
  3444  	if res != "" {
  3445  		c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  3446  	}
  3447  }
  3448  
  3449  func (s *DockerSuite) TestTwoContainersInNetHost(c *testing.T) {
  3450  	// Not applicable as Windows does not support --net=host
  3451  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace)
  3452  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3453  	dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
  3454  	dockerCmd(c, "stop", "first")
  3455  	dockerCmd(c, "stop", "second")
  3456  }
  3457  
  3458  func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *testing.T) {
  3459  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3460  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork")
  3461  	dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top")
  3462  	assert.Assert(c, waitRun("first") == nil)
  3463  	dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first")
  3464  }
  3465  
  3466  func (s *DockerSuite) TestContainersInMultipleNetworks(c *testing.T) {
  3467  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3468  	// Create 2 networks using bridge driver
  3469  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3470  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3471  	// Run and connect containers to testnetwork1
  3472  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3473  	assert.Assert(c, waitRun("first") == nil)
  3474  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3475  	assert.Assert(c, waitRun("second") == nil)
  3476  	// Check connectivity between containers in testnetwork2
  3477  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3478  	// Connect containers to testnetwork2
  3479  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3480  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3481  	// Check connectivity between containers
  3482  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3483  }
  3484  
  3485  func (s *DockerSuite) TestContainersNetworkIsolation(c *testing.T) {
  3486  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3487  	// Create 2 networks using bridge driver
  3488  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3489  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3490  	// Run 1 container in testnetwork1 and another in testnetwork2
  3491  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3492  	assert.Assert(c, waitRun("first") == nil)
  3493  	dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top")
  3494  	assert.Assert(c, waitRun("second") == nil)
  3495  
  3496  	// Check Isolation between containers : ping must fail
  3497  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3498  	assert.ErrorContains(c, err, "")
  3499  	// Connect first container to testnetwork2
  3500  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3501  	// ping must succeed now
  3502  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3503  	assert.NilError(c, err)
  3504  
  3505  	// Disconnect first container from testnetwork2
  3506  	dockerCmd(c, "network", "disconnect", "testnetwork2", "first")
  3507  	// ping must fail again
  3508  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3509  	assert.ErrorContains(c, err, "")
  3510  }
  3511  
  3512  func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *testing.T) {
  3513  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3514  	// Create 2 networks using bridge driver
  3515  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3516  	// Run and connect containers to testnetwork1
  3517  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3518  	assert.Assert(c, waitRun("first") == nil)
  3519  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3520  	assert.Assert(c, waitRun("second") == nil)
  3521  	// Network delete with active containers must fail
  3522  	_, _, err := dockerCmdWithError("network", "rm", "testnetwork1")
  3523  	assert.ErrorContains(c, err, "")
  3524  
  3525  	dockerCmd(c, "stop", "first")
  3526  	_, _, err = dockerCmdWithError("network", "rm", "testnetwork1")
  3527  	assert.ErrorContains(c, err, "")
  3528  }
  3529  
  3530  func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *testing.T) {
  3531  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3532  	// Create 2 networks using bridge driver
  3533  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3534  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3535  
  3536  	// Run and connect containers to testnetwork1
  3537  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3538  	assert.Assert(c, waitRun("first") == nil)
  3539  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3540  	assert.Assert(c, waitRun("second") == nil)
  3541  	// Check connectivity between containers in testnetwork2
  3542  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3543  	// Connect containers to testnetwork2
  3544  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3545  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3546  	// Check connectivity between containers
  3547  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3548  
  3549  	// Stop second container and test ping failures on both networks
  3550  	dockerCmd(c, "stop", "second")
  3551  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3552  	assert.ErrorContains(c, err, "")
  3553  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2")
  3554  	assert.ErrorContains(c, err, "")
  3555  
  3556  	// Start second container and connectivity must be restored on both networks
  3557  	dockerCmd(c, "start", "second")
  3558  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3559  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3560  }
  3561  
  3562  func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *testing.T) {
  3563  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3564  	// Run a container with --net=host
  3565  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3566  	assert.Assert(c, waitRun("first") == nil)
  3567  
  3568  	// Create a network using bridge driver
  3569  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3570  
  3571  	// Connecting to the user defined network must fail
  3572  	_, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3573  	assert.ErrorContains(c, err, "")
  3574  }
  3575  
  3576  func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *testing.T) {
  3577  	testRequires(c, DaemonIsLinux)
  3578  	dockerCmd(c, "run", "-d", "--name=first", "busybox", "top")
  3579  	assert.Assert(c, waitRun("first") == nil)
  3580  	// Run second container in first container's network namespace
  3581  	dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top")
  3582  	assert.Assert(c, waitRun("second") == nil)
  3583  
  3584  	// Create a network using bridge driver
  3585  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3586  
  3587  	// Connecting to the user defined network must fail
  3588  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second")
  3589  	assert.ErrorContains(c, err, "")
  3590  	assert.Assert(c, strings.Contains(out, runconfig.ErrConflictSharedNetwork.Error()))
  3591  }
  3592  
  3593  func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *testing.T) {
  3594  	testRequires(c, DaemonIsLinux)
  3595  	dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top")
  3596  	assert.Assert(c, waitRun("first") == nil)
  3597  
  3598  	// Create a network using bridge driver
  3599  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3600  
  3601  	// Connecting to the user defined network must fail
  3602  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3603  	assert.ErrorContains(c, err, "")
  3604  	assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNoNetwork.Error()))
  3605  	// create a container connected to testnetwork1
  3606  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3607  	assert.Assert(c, waitRun("second") == nil)
  3608  
  3609  	// Connect second container to none network. it must fail as well
  3610  	_, _, err = dockerCmdWithError("network", "connect", "none", "second")
  3611  	assert.ErrorContains(c, err, "")
  3612  }
  3613  
  3614  // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited
  3615  func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *testing.T) {
  3616  	cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true")
  3617  	in, err := cmd.StdinPipe()
  3618  	assert.NilError(c, err)
  3619  	defer in.Close()
  3620  	stdout := bytes.NewBuffer(nil)
  3621  	cmd.Stdout = stdout
  3622  	cmd.Stderr = stdout
  3623  	assert.Assert(c, cmd.Start() == nil)
  3624  
  3625  	waitChan := make(chan error, 1)
  3626  	go func() {
  3627  		waitChan <- cmd.Wait()
  3628  	}()
  3629  
  3630  	select {
  3631  	case err := <-waitChan:
  3632  		assert.Assert(c, err == nil, stdout.String())
  3633  	case <-time.After(30 * time.Second):
  3634  		c.Fatal("timeout waiting for command to exit")
  3635  	}
  3636  }
  3637  
  3638  func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *testing.T) {
  3639  	// TODO Windows: This needs validation (error out) in the daemon.
  3640  	testRequires(c, DaemonIsLinux)
  3641  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true")
  3642  	assert.ErrorContains(c, err, "")
  3643  	expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n"
  3644  	if !(strings.Contains(out, expected) || exitCode == 125) {
  3645  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  3646  	}
  3647  }
  3648  
  3649  func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *testing.T) {
  3650  	// TODO Windows: This needs validation (error out) in the daemon.
  3651  	testRequires(c, DaemonIsLinux)
  3652  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true")
  3653  	assert.ErrorContains(c, err, "")
  3654  	expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n"
  3655  	if !(strings.Contains(out, expected) || exitCode == 125) {
  3656  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  3657  	}
  3658  }
  3659  
  3660  // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127'
  3661  func (s *DockerSuite) TestRunNonExecutableCmd(c *testing.T) {
  3662  	name := "testNonExecutableCmd"
  3663  	icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "foo").Assert(c, icmd.Expected{
  3664  		ExitCode: 127,
  3665  		Error:    "exit status 127",
  3666  	})
  3667  }
  3668  
  3669  // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127.
  3670  func (s *DockerSuite) TestRunNonExistingCmd(c *testing.T) {
  3671  	name := "testNonExistingCmd"
  3672  	icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/bin/foo").Assert(c, icmd.Expected{
  3673  		ExitCode: 127,
  3674  		Error:    "exit status 127",
  3675  	})
  3676  }
  3677  
  3678  // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or
  3679  // 127 on Windows. The difference is that in Windows, the container must be started
  3680  // as that's when the check is made (and yes, by its design...)
  3681  func (s *DockerSuite) TestCmdCannotBeInvoked(c *testing.T) {
  3682  	expected := 126
  3683  	if testEnv.OSType == "windows" {
  3684  		expected = 127
  3685  	}
  3686  	name := "testCmdCannotBeInvoked"
  3687  	icmd.RunCommand(dockerBinary, "run", "--name", name, "busybox", "/etc").Assert(c, icmd.Expected{
  3688  		ExitCode: expected,
  3689  		Error:    fmt.Sprintf("exit status %d", expected),
  3690  	})
  3691  }
  3692  
  3693  // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains  'Unable to find image'
  3694  // FIXME(vdemeester) should be a unit test
  3695  func (s *DockerSuite) TestRunNonExistingImage(c *testing.T) {
  3696  	icmd.RunCommand(dockerBinary, "run", "foo").Assert(c, icmd.Expected{
  3697  		ExitCode: 125,
  3698  		Err:      "Unable to find image",
  3699  	})
  3700  }
  3701  
  3702  // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed
  3703  // FIXME(vdemeester) should be a unit test
  3704  func (s *DockerSuite) TestDockerFails(c *testing.T) {
  3705  	icmd.RunCommand(dockerBinary, "run", "-foo", "busybox").Assert(c, icmd.Expected{
  3706  		ExitCode: 125,
  3707  		Error:    "exit status 125",
  3708  	})
  3709  }
  3710  
  3711  // TestRunInvalidReference invokes docker run with a bad reference.
  3712  func (s *DockerSuite) TestRunInvalidReference(c *testing.T) {
  3713  	out, exit, _ := dockerCmdWithError("run", "busybox@foo")
  3714  	if exit == 0 {
  3715  		c.Fatalf("expected non-zero exist code; received %d", exit)
  3716  	}
  3717  
  3718  	if !strings.Contains(out, "invalid reference format") {
  3719  		c.Fatalf(`Expected "invalid reference format" in output; got: %s`, out)
  3720  	}
  3721  }
  3722  
  3723  // Test fix for issue #17854
  3724  func (s *DockerSuite) TestRunInitLayerPathOwnership(c *testing.T) {
  3725  	// Not applicable on Windows as it does not support Linux uid/gid ownership
  3726  	testRequires(c, DaemonIsLinux)
  3727  	name := "testetcfileownership"
  3728  	buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox
  3729  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  3730  		RUN echo 'dockerio:x:1001:' >> /etc/group
  3731  		RUN chown dockerio:dockerio /etc`))
  3732  
  3733  	// Test that dockerio ownership of /etc is retained at runtime
  3734  	out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc")
  3735  	out = strings.TrimSpace(out)
  3736  	if out != "dockerio:dockerio" {
  3737  		c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out)
  3738  	}
  3739  }
  3740  
  3741  func (s *DockerSuite) TestRunWithOomScoreAdj(c *testing.T) {
  3742  	testRequires(c, DaemonIsLinux)
  3743  
  3744  	expected := "642"
  3745  	out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj")
  3746  	oomScoreAdj := strings.TrimSpace(out)
  3747  	if oomScoreAdj != "642" {
  3748  		c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj)
  3749  	}
  3750  }
  3751  
  3752  func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *testing.T) {
  3753  	testRequires(c, DaemonIsLinux)
  3754  
  3755  	out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true")
  3756  	assert.ErrorContains(c, err, "")
  3757  	expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]."
  3758  	if !strings.Contains(out, expected) {
  3759  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  3760  	}
  3761  	out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true")
  3762  	assert.ErrorContains(c, err, "")
  3763  	expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]."
  3764  	if !strings.Contains(out, expected) {
  3765  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  3766  	}
  3767  }
  3768  
  3769  func (s *DockerSuite) TestRunVolumesMountedAsShared(c *testing.T) {
  3770  	// Volume propagation is linux only. Also it creates directories for
  3771  	// bind mounting, so needs to be same host.
  3772  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace)
  3773  
  3774  	// Prepare a source directory to bind mount
  3775  	tmpDir, err := ioutil.TempDir("", "volume-source")
  3776  	if err != nil {
  3777  		c.Fatal(err)
  3778  	}
  3779  	defer os.RemoveAll(tmpDir)
  3780  
  3781  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  3782  		c.Fatal(err)
  3783  	}
  3784  
  3785  	// Convert this directory into a shared mount point so that we do
  3786  	// not rely on propagation properties of parent mount.
  3787  	icmd.RunCommand("mount", "--bind", tmpDir, tmpDir).Assert(c, icmd.Success)
  3788  	icmd.RunCommand("mount", "--make-private", "--make-shared", tmpDir).Assert(c, icmd.Success)
  3789  
  3790  	dockerCmd(c, "run", "--privileged", "-v", fmt.Sprintf("%s:/volume-dest:shared", tmpDir), "busybox", "mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1")
  3791  
  3792  	// Make sure a bind mount under a shared volume propagated to host.
  3793  	if mounted, _ := mountinfo.Mounted(path.Join(tmpDir, "mnt1")); !mounted {
  3794  		c.Fatalf("Bind mount under shared volume did not propagate to host")
  3795  	}
  3796  
  3797  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  3798  }
  3799  
  3800  func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *testing.T) {
  3801  	// Volume propagation is linux only. Also it creates directories for
  3802  	// bind mounting, so needs to be same host.
  3803  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace)
  3804  
  3805  	// Prepare a source directory to bind mount
  3806  	tmpDir, err := ioutil.TempDir("", "volume-source")
  3807  	if err != nil {
  3808  		c.Fatal(err)
  3809  	}
  3810  	defer os.RemoveAll(tmpDir)
  3811  
  3812  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  3813  		c.Fatal(err)
  3814  	}
  3815  
  3816  	// Prepare a source directory with file in it. We will bind mount this
  3817  	// directory and see if file shows up.
  3818  	tmpDir2, err := ioutil.TempDir("", "volume-source2")
  3819  	if err != nil {
  3820  		c.Fatal(err)
  3821  	}
  3822  	defer os.RemoveAll(tmpDir2)
  3823  
  3824  	if err := ioutil.WriteFile(path.Join(tmpDir2, "slave-testfile"), []byte("Test"), 0644); err != nil {
  3825  		c.Fatal(err)
  3826  	}
  3827  
  3828  	// Convert this directory into a shared mount point so that we do
  3829  	// not rely on propagation properties of parent mount.
  3830  	icmd.RunCommand("mount", "--bind", tmpDir, tmpDir).Assert(c, icmd.Success)
  3831  	icmd.RunCommand("mount", "--make-private", "--make-shared", tmpDir).Assert(c, icmd.Success)
  3832  
  3833  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "-v", fmt.Sprintf("%s:/volume-dest:slave", tmpDir), "busybox", "top")
  3834  
  3835  	// Bind mount tmpDir2/ onto tmpDir/mnt1. If mount propagates inside
  3836  	// container then contents of tmpDir2/slave-testfile should become
  3837  	// visible at "/volume-dest/mnt1/slave-testfile"
  3838  	icmd.RunCommand("mount", "--bind", tmpDir2, path.Join(tmpDir, "mnt1")).Assert(c, icmd.Success)
  3839  
  3840  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/volume-dest/mnt1/slave-testfile")
  3841  
  3842  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  3843  
  3844  	if out != "Test" {
  3845  		c.Fatalf("Bind mount under slave volume did not propagate to container")
  3846  	}
  3847  }
  3848  
  3849  func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *testing.T) {
  3850  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3851  	out, exitCode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile")
  3852  	assert.Assert(c, exitCode != 0)
  3853  	assert.Assert(c, strings.Contains(out, "invalid mount config"))
  3854  }
  3855  
  3856  func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *testing.T) {
  3857  	testRequires(c, DaemonIsLinux)
  3858  
  3859  	testImg := "testvolumecopy"
  3860  	buildImageSuccessfully(c, testImg, build.WithDockerfile(`
  3861  	FROM busybox
  3862  	RUN mkdir -p /foo && echo hello > /foo/hello
  3863  	`))
  3864  
  3865  	dockerCmd(c, "run", "-v", "foo:/foo", testImg)
  3866  	out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello")
  3867  	assert.Equal(c, strings.TrimSpace(out), "hello")
  3868  }
  3869  
  3870  func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *testing.T) {
  3871  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  3872  
  3873  	dockerCmd(c, "volume", "create", "test")
  3874  
  3875  	dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  3876  	dockerCmd(c, "volume", "inspect", "test")
  3877  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  3878  	assert.Assert(c, strings.Contains(out, "test"))
  3879  
  3880  	dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  3881  	dockerCmd(c, "rm", "-fv", "test")
  3882  	dockerCmd(c, "volume", "inspect", "test")
  3883  	out, _ = dockerCmd(c, "volume", "ls", "-q")
  3884  	assert.Assert(c, strings.Contains(out, "test"))
  3885  }
  3886  
  3887  func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) {
  3888  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  3889  
  3890  	dockerCmd(c, "volume", "create", "test")
  3891  	cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  3892  	dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true")
  3893  
  3894  	cli, err := client.NewClientWithOpts(client.FromEnv)
  3895  	assert.NilError(c, err)
  3896  	defer cli.Close()
  3897  
  3898  	container, err := cli.ContainerInspect(context.Background(), strings.TrimSpace(cid))
  3899  	assert.NilError(c, err)
  3900  	var vname string
  3901  	for _, v := range container.Mounts {
  3902  		if v.Name != "test" {
  3903  			vname = v.Name
  3904  		}
  3905  	}
  3906  	assert.Assert(c, vname != "")
  3907  
  3908  	// Remove the parent so there are not other references to the volumes
  3909  	dockerCmd(c, "rm", "-f", "parent")
  3910  	// now remove the child and ensure the named volume (and only the named volume) still exists
  3911  	dockerCmd(c, "rm", "-fv", "child")
  3912  	dockerCmd(c, "volume", "inspect", "test")
  3913  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  3914  	assert.Assert(c, strings.Contains(out, "test"))
  3915  	assert.Assert(c, !strings.Contains(strings.TrimSpace(out), vname))
  3916  }
  3917  
  3918  func (s *DockerSuite) TestRunAttachFailedNoLeak(c *testing.T) {
  3919  	nroutines, err := getGoroutineNumber()
  3920  	assert.NilError(c, err)
  3921  
  3922  	runSleepingContainer(c, "--name=test", "-p", "8000:8000")
  3923  
  3924  	// Wait until container is fully up and running
  3925  	assert.Assert(c, waitRun("test") == nil)
  3926  
  3927  	out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true")
  3928  	// We will need the following `inspect` to diagnose the issue if test fails (#21247)
  3929  	out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test")
  3930  	out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail")
  3931  	assert.Assert(c, err != nil, "Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2)
  3932  	// check for windows error as well
  3933  	// TODO Windows Post TP5. Fix the error message string
  3934  	outLowerCase := strings.ToLower(out)
  3935  	assert.Assert(c, strings.Contains(outLowerCase, "port is already allocated") ||
  3936  		strings.Contains(outLowerCase, "were not connected because a duplicate name exists") ||
  3937  		strings.Contains(outLowerCase, "the specified port already exists") ||
  3938  		strings.Contains(outLowerCase, "hns failed with error : failed to create endpoint") ||
  3939  		strings.Contains(outLowerCase, "hns failed with error : the object already exists"), fmt.Sprintf("Output: %s", out))
  3940  	dockerCmd(c, "rm", "-f", "test")
  3941  
  3942  	// NGoroutines is not updated right away, so we need to wait before failing
  3943  	assert.Assert(c, waitForGoroutines(nroutines) == nil)
  3944  }
  3945  
  3946  // Test for one character directory name case (#20122)
  3947  func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *testing.T) {
  3948  	testRequires(c, DaemonIsLinux)
  3949  
  3950  	out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo")
  3951  	assert.Equal(c, strings.TrimSpace(out), "/foo")
  3952  }
  3953  
  3954  func (s *DockerSuite) TestRunVolumeCopyFlag(c *testing.T) {
  3955  	testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume
  3956  	buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox
  3957  		RUN mkdir /foo && echo hello > /foo/bar
  3958  		CMD cat /foo/bar`))
  3959  	dockerCmd(c, "volume", "create", "test")
  3960  
  3961  	// test with the nocopy flag
  3962  	out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy")
  3963  	assert.ErrorContains(c, err, "", out)
  3964  	// test default behavior which is to copy for non-binds
  3965  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  3966  	assert.Equal(c, strings.TrimSpace(out), "hello")
  3967  	// error out when the volume is already populated
  3968  	out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy")
  3969  	assert.ErrorContains(c, err, "", out)
  3970  	// do not error out when copy isn't explicitly set even though it's already populated
  3971  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  3972  	assert.Equal(c, strings.TrimSpace(out), "hello")
  3973  
  3974  	// do not allow copy modes on volumes-from
  3975  	dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true")
  3976  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true")
  3977  	assert.ErrorContains(c, err, "", out)
  3978  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true")
  3979  	assert.ErrorContains(c, err, "", out)
  3980  
  3981  	// do not allow copy modes on binds
  3982  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true")
  3983  	assert.ErrorContains(c, err, "", out)
  3984  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true")
  3985  	assert.ErrorContains(c, err, "", out)
  3986  }
  3987  
  3988  // Test case for #21976
  3989  func (s *DockerSuite) TestRunDNSInHostMode(c *testing.T) {
  3990  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3991  
  3992  	expectedOutput := "nameserver 127.0.0.1"
  3993  	expectedWarning := "Localhost DNS setting"
  3994  	cli.DockerCmd(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
  3995  		Out: expectedOutput,
  3996  		Err: expectedWarning,
  3997  	})
  3998  
  3999  	expectedOutput = "nameserver 1.2.3.4"
  4000  	cli.DockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
  4001  		Out: expectedOutput,
  4002  	})
  4003  
  4004  	expectedOutput = "search example.com"
  4005  	cli.DockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
  4006  		Out: expectedOutput,
  4007  	})
  4008  
  4009  	expectedOutput = "options timeout:3"
  4010  	cli.DockerCmd(c, "run", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf").Assert(c, icmd.Expected{
  4011  		Out: expectedOutput,
  4012  	})
  4013  
  4014  	expectedOutput1 := "nameserver 1.2.3.4"
  4015  	expectedOutput2 := "search example.com"
  4016  	expectedOutput3 := "options timeout:3"
  4017  	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()
  4018  	assert.Assert(c, strings.Contains(out, expectedOutput1), "Expected '%s', but got %q", expectedOutput1, out)
  4019  	assert.Assert(c, strings.Contains(out, expectedOutput2), "Expected '%s', but got %q", expectedOutput2, out)
  4020  	assert.Assert(c, strings.Contains(out, expectedOutput3), "Expected '%s', but got %q", expectedOutput3, out)
  4021  }
  4022  
  4023  // Test case for #21976
  4024  func (s *DockerSuite) TestRunAddHostInHostMode(c *testing.T) {
  4025  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4026  
  4027  	expectedOutput := "1.2.3.4\textra"
  4028  	out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts")
  4029  	assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out)
  4030  }
  4031  
  4032  func (s *DockerSuite) TestRunRmAndWait(c *testing.T) {
  4033  	dockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2")
  4034  
  4035  	out, code, err := dockerCmdWithError("wait", "test")
  4036  	assert.Assert(c, err == nil, "out: %s; exit code: %d", out, code)
  4037  	assert.Equal(c, out, "2\n", "exit code: %d", code)
  4038  	assert.Equal(c, code, 0)
  4039  }
  4040  
  4041  // Test that auto-remove is performed by the daemon (API 1.25 and above)
  4042  func (s *DockerSuite) TestRunRm(c *testing.T) {
  4043  	name := "miss-me-when-im-gone"
  4044  	cli.DockerCmd(c, "run", "--name="+name, "--rm", "busybox")
  4045  
  4046  	cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{
  4047  		ExitCode: 1,
  4048  		Err:      "No such object: " + name,
  4049  	})
  4050  }
  4051  
  4052  // Test that auto-remove is performed by the client on API versions that do not support daemon-side api-remove (API < 1.25)
  4053  func (s *DockerSuite) TestRunRmPre125Api(c *testing.T) {
  4054  	name := "miss-me-when-im-gone"
  4055  	envs := appendBaseEnv(os.Getenv("DOCKER_TLS_VERIFY") != "", "DOCKER_API_VERSION=1.24")
  4056  	cli.Docker(cli.Args("run", "--name="+name, "--rm", "busybox"), cli.WithEnvironmentVariables(envs...)).Assert(c, icmd.Success)
  4057  
  4058  	cli.Docker(cli.Inspect(name), cli.Format(".name")).Assert(c, icmd.Expected{
  4059  		ExitCode: 1,
  4060  		Err:      "No such object: " + name,
  4061  	})
  4062  }
  4063  
  4064  // Test case for #23498
  4065  func (s *DockerSuite) TestRunUnsetEntrypoint(c *testing.T) {
  4066  	testRequires(c, DaemonIsLinux)
  4067  	name := "test-entrypoint"
  4068  	dockerfile := `FROM busybox
  4069  ADD entrypoint.sh /entrypoint.sh
  4070  RUN chmod 755 /entrypoint.sh
  4071  ENTRYPOINT ["/entrypoint.sh"]
  4072  CMD echo foobar`
  4073  
  4074  	ctx := fakecontext.New(c, "",
  4075  		fakecontext.WithDockerfile(dockerfile),
  4076  		fakecontext.WithFiles(map[string]string{
  4077  			"entrypoint.sh": `#!/bin/sh
  4078  echo "I am an entrypoint"
  4079  exec "$@"`,
  4080  		}))
  4081  	defer ctx.Close()
  4082  
  4083  	cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx))
  4084  
  4085  	out := cli.DockerCmd(c, "run", "--entrypoint=", "-t", name, "echo", "foo").Combined()
  4086  	assert.Equal(c, strings.TrimSpace(out), "foo")
  4087  
  4088  	// CMD will be reset as well (the same as setting a custom entrypoint)
  4089  	cli.Docker(cli.Args("run", "--entrypoint=", "-t", name)).Assert(c, icmd.Expected{
  4090  		ExitCode: 125,
  4091  		Err:      "No command specified",
  4092  	})
  4093  }
  4094  
  4095  func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *testing.T) {
  4096  	s.d.StartWithBusybox(c, "--debug", "--default-ulimit=nofile=65535")
  4097  
  4098  	name := "test-A"
  4099  	_, err := s.d.Cmd("run", "--name", name, "-d", "busybox", "top")
  4100  	assert.NilError(c, err)
  4101  	assert.NilError(c, s.d.WaitRun(name))
  4102  
  4103  	out, err := s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name)
  4104  	assert.NilError(c, err)
  4105  	assert.Assert(c, strings.Contains(out, "[nofile=65535:65535]"))
  4106  	name = "test-B"
  4107  	_, err = s.d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top")
  4108  	assert.NilError(c, err)
  4109  	assert.NilError(c, s.d.WaitRun(name))
  4110  
  4111  	out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name)
  4112  	assert.NilError(c, err)
  4113  	assert.Assert(c, strings.Contains(out, "[nofile=42:42]"))
  4114  }
  4115  
  4116  func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *testing.T) {
  4117  	nroutines, err := getGoroutineNumber()
  4118  	assert.NilError(c, err)
  4119  
  4120  	out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true")
  4121  	assert.ErrorContains(c, err, "")
  4122  	assert.Assert(c, strings.Contains(out, "failed to initialize logging driver"), "error should be about logging driver, got output %s", out)
  4123  	// NGoroutines is not updated right away, so we need to wait before failing
  4124  	assert.Assert(c, waitForGoroutines(nroutines) == nil)
  4125  }
  4126  
  4127  // Handles error conditions for --credentialspec. Validating E2E success cases
  4128  // requires additional infrastructure (AD for example) on CI servers.
  4129  func (s *DockerSuite) TestRunCredentialSpecFailures(c *testing.T) {
  4130  	testRequires(c, DaemonIsWindows)
  4131  
  4132  	attempts := []struct{ value, expectedError string }{
  4133  		{"rubbish", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
  4134  		{"rubbish://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
  4135  		{"file://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
  4136  		{"registry://", "invalid credential spec security option - value must be prefixed by 'file://', 'registry://', or 'raw://' followed by a non-empty value"},
  4137  		{`file://c:\blah.txt`, "path cannot be absolute"},
  4138  		{`file://doesnotexist.txt`, "The system cannot find the file specified"},
  4139  	}
  4140  	for _, attempt := range attempts {
  4141  		_, _, err := dockerCmdWithError("run", "--security-opt=credentialspec="+attempt.value, "busybox", "true")
  4142  		assert.Assert(c, err != nil, "%s expected non-nil err", attempt.value)
  4143  		assert.Assert(c, strings.Contains(err.Error(), attempt.expectedError), "%s expected %s got %s", attempt.value, attempt.expectedError, err)
  4144  	}
  4145  }
  4146  
  4147  // Windows specific test to validate credential specs with a well-formed spec.
  4148  func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *testing.T) {
  4149  	testRequires(c, DaemonIsWindows, testEnv.IsLocalDaemon)
  4150  
  4151  	validCredSpecs := readFile(`fixtures\credentialspecs\valid.json`, c)
  4152  	writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCredSpecs, c)
  4153  
  4154  	for _, value := range []string{"file://valid.json", "raw://" + validCredSpecs} {
  4155  		// `nltest /PARENTDOMAIN` simply reads the local config, and does not require having an AD
  4156  		// controller handy
  4157  		out, _ := dockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN")
  4158  
  4159  		assert.Assert(c, strings.Contains(out, "hyperv.local."))
  4160  		assert.Assert(c, strings.Contains(out, "The command completed successfully"))
  4161  	}
  4162  }
  4163  
  4164  func (s *DockerSuite) TestRunDuplicateMount(c *testing.T) {
  4165  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  4166  
  4167  	tmpFile, err := ioutil.TempFile("", "touch-me")
  4168  	assert.NilError(c, err)
  4169  	defer tmpFile.Close()
  4170  
  4171  	data := "touch-me-foo-bar\n"
  4172  	if _, err := tmpFile.Write([]byte(data)); err != nil {
  4173  		c.Fatal(err)
  4174  	}
  4175  
  4176  	name := "test"
  4177  	out, _ := dockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /")
  4178  	assert.Assert(c, !strings.Contains(out, "tmp:"))
  4179  	assert.Assert(c, strings.Contains(out, data))
  4180  	out = inspectFieldJSON(c, name, "Config.Volumes")
  4181  	assert.Assert(c, strings.Contains(out, "null"))
  4182  }
  4183  
  4184  func (s *DockerSuite) TestRunWindowsWithCPUCount(c *testing.T) {
  4185  	testRequires(c, DaemonIsWindows)
  4186  
  4187  	out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing")
  4188  	assert.Equal(c, strings.TrimSpace(out), "testing")
  4189  
  4190  	out = inspectField(c, "test", "HostConfig.CPUCount")
  4191  	assert.Equal(c, out, "1")
  4192  }
  4193  
  4194  func (s *DockerSuite) TestRunWindowsWithCPUShares(c *testing.T) {
  4195  	testRequires(c, DaemonIsWindows)
  4196  
  4197  	out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing")
  4198  	assert.Equal(c, strings.TrimSpace(out), "testing")
  4199  
  4200  	out = inspectField(c, "test", "HostConfig.CPUShares")
  4201  	assert.Equal(c, out, "1000")
  4202  }
  4203  
  4204  func (s *DockerSuite) TestRunWindowsWithCPUPercent(c *testing.T) {
  4205  	testRequires(c, DaemonIsWindows)
  4206  
  4207  	out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
  4208  	assert.Equal(c, strings.TrimSpace(out), "testing")
  4209  
  4210  	out = inspectField(c, "test", "HostConfig.CPUPercent")
  4211  	assert.Equal(c, out, "80")
  4212  }
  4213  
  4214  func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) {
  4215  	testRequires(c, IsolationIsProcess)
  4216  
  4217  	out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
  4218  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU shares on Windows Server Containers. CPU shares discarded"))
  4219  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU percent on Windows Server Containers. CPU percent discarded"))
  4220  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing"))
  4221  	out = inspectField(c, "test", "HostConfig.CPUCount")
  4222  	assert.Equal(c, out, "1")
  4223  
  4224  	out = inspectField(c, "test", "HostConfig.CPUShares")
  4225  	assert.Equal(c, out, "0")
  4226  
  4227  	out = inspectField(c, "test", "HostConfig.CPUPercent")
  4228  	assert.Equal(c, out, "0")
  4229  }
  4230  
  4231  func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) {
  4232  	testRequires(c, IsolationIsHyperv)
  4233  
  4234  	out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing")
  4235  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing"))
  4236  	out = inspectField(c, "test", "HostConfig.CPUCount")
  4237  	assert.Equal(c, out, "1")
  4238  
  4239  	out = inspectField(c, "test", "HostConfig.CPUShares")
  4240  	assert.Equal(c, out, "1000")
  4241  
  4242  	out = inspectField(c, "test", "HostConfig.CPUPercent")
  4243  	assert.Equal(c, out, "80")
  4244  }
  4245  
  4246  // Test for #25099
  4247  func (s *DockerSuite) TestRunEmptyEnv(c *testing.T) {
  4248  	testRequires(c, DaemonIsLinux)
  4249  
  4250  	expectedOutput := "invalid environment variable:"
  4251  
  4252  	out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true")
  4253  	assert.ErrorContains(c, err, "")
  4254  	assert.Assert(c, strings.Contains(out, expectedOutput))
  4255  
  4256  	out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true")
  4257  	assert.ErrorContains(c, err, "")
  4258  	assert.Assert(c, strings.Contains(out, expectedOutput))
  4259  
  4260  	out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true")
  4261  	assert.ErrorContains(c, err, "")
  4262  	assert.Assert(c, strings.Contains(out, expectedOutput))
  4263  }
  4264  
  4265  // #28658
  4266  func (s *DockerSuite) TestSlowStdinClosing(c *testing.T) {
  4267  	name := "testslowstdinclosing"
  4268  	repeat := 3 // regression happened 50% of the time
  4269  	for i := 0; i < repeat; i++ {
  4270  		cmd := icmd.Cmd{
  4271  			Command: []string{dockerBinary, "run", "--rm", "--name", name, "-i", "busybox", "cat"},
  4272  			Stdin:   &delayedReader{},
  4273  		}
  4274  		done := make(chan error, 1)
  4275  		go func() {
  4276  			err := icmd.RunCmd(cmd).Error
  4277  			done <- err
  4278  		}()
  4279  
  4280  		select {
  4281  		case <-time.After(30 * time.Second):
  4282  			c.Fatal("running container timed out") // cleanup in teardown
  4283  		case err := <-done:
  4284  			assert.NilError(c, err)
  4285  		}
  4286  	}
  4287  }
  4288  
  4289  type delayedReader struct{}
  4290  
  4291  func (s *delayedReader) Read([]byte) (int, error) {
  4292  	time.Sleep(500 * time.Millisecond)
  4293  	return 0, io.EOF
  4294  }
  4295  
  4296  // #28823 (originally #28639)
  4297  func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *testing.T) {
  4298  	testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace)
  4299  	emptyDir, err := ioutil.TempDir("", "test-read-only-dev-shm")
  4300  	assert.NilError(c, err)
  4301  	defer os.RemoveAll(emptyDir)
  4302  	out, _, err := dockerCmdWithError("run", "--rm", "--read-only",
  4303  		"-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir),
  4304  		"busybox", "touch", "/dev/shm/foo")
  4305  	assert.ErrorContains(c, err, "", out)
  4306  	assert.Assert(c, strings.Contains(out, "Read-only file system"))
  4307  }
  4308  
  4309  func (s *DockerSuite) TestRunMount(c *testing.T) {
  4310  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace)
  4311  
  4312  	// mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases
  4313  	tmpDir, err := ioutil.TempDir("", "mount")
  4314  	if err != nil {
  4315  		c.Fatal(err)
  4316  	}
  4317  	defer os.RemoveAll(tmpDir)
  4318  	mnt1, mnt2 := path.Join(tmpDir, "mnt1"), path.Join(tmpDir, "mnt2")
  4319  	if err := os.Mkdir(mnt1, 0755); err != nil {
  4320  		c.Fatal(err)
  4321  	}
  4322  	if err := os.Mkdir(mnt2, 0755); err != nil {
  4323  		c.Fatal(err)
  4324  	}
  4325  	if err := ioutil.WriteFile(path.Join(mnt1, "test1"), []byte("test1"), 0644); err != nil {
  4326  		c.Fatal(err)
  4327  	}
  4328  	if err := ioutil.WriteFile(path.Join(mnt2, "test2"), []byte("test2"), 0644); err != nil {
  4329  		c.Fatal(err)
  4330  	}
  4331  	testCatFooBar := func(cName string) error {
  4332  		out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1")
  4333  		if out != "test1" {
  4334  			return fmt.Errorf("%s not mounted on /foo", mnt1)
  4335  		}
  4336  		out, _ = dockerCmd(c, "exec", cName, "cat", "/bar/test2")
  4337  		if out != "test2" {
  4338  			return fmt.Errorf("%s not mounted on /bar", mnt2)
  4339  		}
  4340  		return nil
  4341  	}
  4342  
  4343  	type testCase struct {
  4344  		equivalents [][]string
  4345  		valid       bool
  4346  		// fn should be nil if valid==false
  4347  		fn func(cName string) error
  4348  	}
  4349  	cases := []testCase{
  4350  		{
  4351  			equivalents: [][]string{
  4352  				{
  4353  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4354  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/bar", mnt2),
  4355  				},
  4356  				{
  4357  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4358  					"--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2),
  4359  				},
  4360  				{
  4361  					"--volume", mnt1 + ":/foo",
  4362  					"--mount", fmt.Sprintf("type=bind,src=%s,target=/bar", mnt2),
  4363  				},
  4364  			},
  4365  			valid: true,
  4366  			fn:    testCatFooBar,
  4367  		},
  4368  		{
  4369  			equivalents: [][]string{
  4370  				{
  4371  					"--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1),
  4372  					"--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2),
  4373  				},
  4374  				{
  4375  					"--mount", fmt.Sprintf("type=volume,src=%s,dst=/foo", mnt1),
  4376  					"--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2),
  4377  				},
  4378  			},
  4379  			valid: false,
  4380  		},
  4381  		{
  4382  			equivalents: [][]string{
  4383  				{
  4384  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4385  					"--mount", fmt.Sprintf("type=volume,src=%s,dst=/bar", mnt2),
  4386  				},
  4387  				{
  4388  					"--volume", mnt1 + ":/foo",
  4389  					"--mount", fmt.Sprintf("type=volume,src=%s,target=/bar", mnt2),
  4390  				},
  4391  			},
  4392  			valid: false,
  4393  			fn:    testCatFooBar,
  4394  		},
  4395  		{
  4396  			equivalents: [][]string{
  4397  				{
  4398  					"--read-only",
  4399  					"--mount", "type=volume,dst=/bar",
  4400  				},
  4401  			},
  4402  			valid: true,
  4403  			fn: func(cName string) error {
  4404  				_, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere")
  4405  				return err
  4406  			},
  4407  		},
  4408  		{
  4409  			equivalents: [][]string{
  4410  				{
  4411  					"--read-only",
  4412  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4413  					"--mount", "type=volume,dst=/bar",
  4414  				},
  4415  				{
  4416  					"--read-only",
  4417  					"--volume", fmt.Sprintf("%s:/foo", mnt1),
  4418  					"--mount", "type=volume,dst=/bar",
  4419  				},
  4420  			},
  4421  			valid: true,
  4422  			fn: func(cName string) error {
  4423  				out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1")
  4424  				if out != "test1" {
  4425  					return fmt.Errorf("%s not mounted on /foo", mnt1)
  4426  				}
  4427  				_, _, err := dockerCmdWithError("exec", cName, "touch", "/bar/icanwritehere")
  4428  				return err
  4429  			},
  4430  		},
  4431  		{
  4432  			equivalents: [][]string{
  4433  				{
  4434  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4435  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt2),
  4436  				},
  4437  				{
  4438  					"--mount", fmt.Sprintf("type=bind,src=%s,dst=/foo", mnt1),
  4439  					"--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2),
  4440  				},
  4441  				{
  4442  					"--volume", fmt.Sprintf("%s:/foo", mnt1),
  4443  					"--mount", fmt.Sprintf("type=bind,src=%s,target=/foo", mnt2),
  4444  				},
  4445  			},
  4446  			valid: false,
  4447  		},
  4448  		{
  4449  			equivalents: [][]string{
  4450  				{
  4451  					"--volume", fmt.Sprintf("%s:/foo", mnt1),
  4452  					"--mount", fmt.Sprintf("type=volume,src=%s,target=/foo", mnt2),
  4453  				},
  4454  			},
  4455  			valid: false,
  4456  		},
  4457  		{
  4458  			equivalents: [][]string{
  4459  				{
  4460  					"--mount", "type=volume,target=/foo",
  4461  					"--mount", "type=volume,target=/foo",
  4462  				},
  4463  			},
  4464  			valid: false,
  4465  		},
  4466  	}
  4467  
  4468  	for i, testCase := range cases {
  4469  		for j, opts := range testCase.equivalents {
  4470  			cName := fmt.Sprintf("mount-%d-%d", i, j)
  4471  			_, _, err := dockerCmdWithError(append([]string{"run", "-i", "-d", "--name", cName},
  4472  				append(opts, []string{"busybox", "top"}...)...)...)
  4473  			if testCase.valid {
  4474  				assert.Assert(c, err == nil, "got error while creating a container with %v (%s)", opts, cName)
  4475  				assert.Assert(c, testCase.fn(cName) == nil, "got error while executing test for %v (%s)", opts, cName)
  4476  				dockerCmd(c, "rm", "-f", cName)
  4477  			} else {
  4478  				assert.Assert(c, err != nil, "got nil while creating a container with %v (%s)", opts, cName)
  4479  			}
  4480  		}
  4481  	}
  4482  }
  4483  
  4484  // Test that passing a FQDN as hostname properly sets hostname, and
  4485  // /etc/hostname. Test case for 29100
  4486  func (s *DockerSuite) TestRunHostnameFQDN(c *testing.T) {
  4487  	testRequires(c, DaemonIsLinux)
  4488  
  4489  	expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com"
  4490  	out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`)
  4491  	assert.Equal(c, strings.TrimSpace(out), expectedOutput)
  4492  
  4493  	out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`)
  4494  	expectedOutput = "foobar.example.com foobar"
  4495  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput))
  4496  }
  4497  
  4498  // Test case for 29129
  4499  func (s *DockerSuite) TestRunHostnameInHostMode(c *testing.T) {
  4500  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4501  
  4502  	expectedOutput := "foobar\nfoobar"
  4503  	out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`)
  4504  	assert.Equal(c, strings.TrimSpace(out), expectedOutput)
  4505  }
  4506  
  4507  func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *testing.T) {
  4508  	testRequires(c, DaemonIsLinux)
  4509  
  4510  	deviceRule := "c 7:128 rwm"
  4511  
  4512  	out, _ := dockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list")
  4513  	if strings.Contains(out, deviceRule) {
  4514  		c.Fatalf("%s shouldn't been in the device.list", deviceRule)
  4515  	}
  4516  
  4517  	out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list")
  4518  	assert.Equal(c, strings.TrimSpace(out), deviceRule)
  4519  }
  4520  
  4521  // Verifies that running as local system is operating correctly on Windows
  4522  func (s *DockerSuite) TestWindowsRunAsSystem(c *testing.T) {
  4523  	testRequires(c, DaemonIsWindowsAtLeastBuild(osversion.RS3))
  4524  	out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`)
  4525  	assert.Equal(c, strings.TrimSpace(out), "XYZZY$")
  4526  }