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