github.com/dpiddy/docker@v1.12.2-rc1/integration-cli/docker_cli_run_test.go (about)

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