github.com/vvnotw/moby@v1.13.1/integration-cli/docker_cli_run_test.go (about)

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