github.com/noxiouz/docker@v0.7.3-0.20160629055221-3d231c78e8c5/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  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  2038  	if err != nil {
  2039  		c.Fatal(err)
  2040  	}
  2041  	defer os.RemoveAll(tmpDir)
  2042  	tmpCidFile := path.Join(tmpDir, "cid")
  2043  
  2044  	image := "emptyfs"
  2045  	if daemonPlatform == "windows" {
  2046  		// Windows can't support an emptyfs image. Just use the regular Windows image
  2047  		image = WindowsBaseImage
  2048  	}
  2049  	out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image)
  2050  	if err == nil {
  2051  		c.Fatalf("Run without command must fail. out=%s", out)
  2052  	} else if !strings.Contains(out, "No command specified") {
  2053  		c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  2054  	}
  2055  
  2056  	if _, err := os.Stat(tmpCidFile); err == nil {
  2057  		c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  2058  	}
  2059  }
  2060  
  2061  // #2098 - Docker cidFiles only contain short version of the containerId
  2062  //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  2063  // TestRunCidFile tests that run --cidfile returns the longid
  2064  func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  2065  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  2066  	if err != nil {
  2067  		c.Fatal(err)
  2068  	}
  2069  	tmpCidFile := path.Join(tmpDir, "cid")
  2070  	defer os.RemoveAll(tmpDir)
  2071  
  2072  	out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  2073  
  2074  	id := strings.TrimSpace(out)
  2075  	buffer, err := ioutil.ReadFile(tmpCidFile)
  2076  	if err != nil {
  2077  		c.Fatal(err)
  2078  	}
  2079  	cid := string(buffer)
  2080  	if len(cid) != 64 {
  2081  		c.Fatalf("--cidfile should be a long id, not %q", id)
  2082  	}
  2083  	if cid != id {
  2084  		c.Fatalf("cid must be equal to %s, got %s", id, cid)
  2085  	}
  2086  }
  2087  
  2088  func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  2089  	mac := "12:34:56:78:9a:bc"
  2090  	var out string
  2091  	if daemonPlatform == "windows" {
  2092  		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
  2093  		mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
  2094  	} else {
  2095  		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}'")
  2096  	}
  2097  
  2098  	actualMac := strings.TrimSpace(out)
  2099  	if actualMac != mac {
  2100  		c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  2101  	}
  2102  }
  2103  
  2104  func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  2105  	// TODO Windows. Network settings are not propagated back to inspect.
  2106  	testRequires(c, DaemonIsLinux)
  2107  	mac := "12:34:56:78:9a:bc"
  2108  	out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  2109  
  2110  	id := strings.TrimSpace(out)
  2111  	inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress")
  2112  	if inspectedMac != mac {
  2113  		c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  2114  	}
  2115  }
  2116  
  2117  // test docker run use an invalid mac address
  2118  func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  2119  	out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  2120  	//use an invalid mac address should with an error out
  2121  	if err == nil || !strings.Contains(out, "is not a valid mac address") {
  2122  		c.Fatalf("run with an invalid --mac-address should with error out")
  2123  	}
  2124  }
  2125  
  2126  func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  2127  	// TODO Windows. Network settings are not propagated back to inspect.
  2128  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2129  
  2130  	out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  2131  
  2132  	id := strings.TrimSpace(out)
  2133  	ip := inspectField(c, id, "NetworkSettings.Networks.bridge.IPAddress")
  2134  	iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  2135  		"!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  2136  	out, _, err := runCommandWithOutput(iptCmd)
  2137  	if err != nil {
  2138  		c.Fatal(err, out)
  2139  	}
  2140  	if err := deleteContainer(id); err != nil {
  2141  		c.Fatal(err)
  2142  	}
  2143  
  2144  	dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  2145  }
  2146  
  2147  func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  2148  	// TODO Windows. The duplicate NAT message returned by Windows will be
  2149  	// changing as is currently completely undecipherable. Does need modifying
  2150  	// to run sh rather than top though as top isn't in Windows busybox.
  2151  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2152  
  2153  	port := "1234"
  2154  	dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  2155  
  2156  	out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  2157  	if err == nil {
  2158  		c.Fatalf("Binding on used port must fail")
  2159  	}
  2160  	if !strings.Contains(out, "port is already allocated") {
  2161  		c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  2162  	}
  2163  }
  2164  
  2165  // https://github.com/docker/docker/issues/12148
  2166  func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  2167  	// TODO Windows. -P is not yet supported
  2168  	testRequires(c, DaemonIsLinux)
  2169  	// allocate a dynamic port to get the most recent
  2170  	out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  2171  
  2172  	id := strings.TrimSpace(out)
  2173  	out, _ = dockerCmd(c, "port", id, "80")
  2174  
  2175  	strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  2176  	port, err := strconv.ParseInt(strPort, 10, 64)
  2177  	if err != nil {
  2178  		c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  2179  	}
  2180  
  2181  	// allocate a static port and a dynamic port together, with static port
  2182  	// takes the next recent port in dynamic port range.
  2183  	dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  2184  }
  2185  
  2186  // Regression test for #7792
  2187  func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  2188  	// TODO Windows: Post TP5. Updated, but Windows does not support nested mounts currently.
  2189  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2190  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2191  
  2192  	tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  2193  	if err != nil {
  2194  		c.Fatal(err)
  2195  	}
  2196  	defer os.RemoveAll(tmpDir)
  2197  
  2198  	tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  2199  	if err != nil {
  2200  		c.Fatal(err)
  2201  	}
  2202  	defer os.RemoveAll(tmpDir2)
  2203  
  2204  	// Create a temporary tmpfs mounc.
  2205  	fooDir := filepath.Join(tmpDir, "foo")
  2206  	if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  2207  		c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  2208  	}
  2209  
  2210  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  2211  		c.Fatal(err)
  2212  	}
  2213  
  2214  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  2215  		c.Fatal(err)
  2216  	}
  2217  
  2218  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  2219  		c.Fatal(err)
  2220  	}
  2221  
  2222  	dockerCmd(c, "run",
  2223  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir),
  2224  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir),
  2225  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2),
  2226  		"-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2/foo", fooDir),
  2227  		"busybox:latest", "sh", "-c",
  2228  		"ls "+prefix+"/tmp/touch-me && ls "+prefix+"/tmp/foo/touch-me && ls "+prefix+"/tmp/tmp2/touch-me && ls "+prefix+"/tmp/tmp2/foo/touch-me")
  2229  }
  2230  
  2231  // Regression test for https://github.com/docker/docker/issues/8259
  2232  func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  2233  	// Not applicable on Windows as Windows does not support volumes
  2234  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2235  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2236  
  2237  	tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  2238  	if err != nil {
  2239  		c.Fatal(err)
  2240  	}
  2241  	defer os.RemoveAll(tmpDir)
  2242  
  2243  	linkPath := os.TempDir() + "/testlink2"
  2244  	if err := os.Symlink(tmpDir, linkPath); err != nil {
  2245  		c.Fatal(err)
  2246  	}
  2247  	defer os.RemoveAll(linkPath)
  2248  
  2249  	// Create first container
  2250  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
  2251  
  2252  	// Create second container with same symlinked path
  2253  	// This will fail if the referenced issue is hit with a "Volume exists" error
  2254  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test")
  2255  }
  2256  
  2257  //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  2258  func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  2259  	// While Windows supports volumes, it does not support --add-host hence
  2260  	// this test is not applicable on Windows.
  2261  	testRequires(c, DaemonIsLinux)
  2262  	out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  2263  	if !strings.Contains(out, "nameserver 127.0.0.1") {
  2264  		c.Fatal("/etc volume mount hides /etc/resolv.conf")
  2265  	}
  2266  
  2267  	out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  2268  	if !strings.Contains(out, "test123") {
  2269  		c.Fatal("/etc volume mount hides /etc/hostname")
  2270  	}
  2271  
  2272  	out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  2273  	out = strings.Replace(out, "\n", " ", -1)
  2274  	if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  2275  		c.Fatal("/etc volume mount hides /etc/hosts")
  2276  	}
  2277  }
  2278  
  2279  func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  2280  	// TODO Windows (Post TP5). Windows does not support volumes which
  2281  	// are pre-populated such as is built in the dockerfile used in this test.
  2282  	testRequires(c, DaemonIsLinux)
  2283  	if _, err := buildImage("dataimage",
  2284  		`FROM busybox
  2285  		RUN mkdir -p /foo
  2286  		RUN touch /foo/bar`,
  2287  		true); err != nil {
  2288  		c.Fatal(err)
  2289  	}
  2290  
  2291  	dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  2292  
  2293  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2294  		c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  2295  	}
  2296  
  2297  	tmpDir := randomTmpDirPath("docker_test_bind_mount_copy_data", daemonPlatform)
  2298  	if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2299  		c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  2300  	}
  2301  }
  2302  
  2303  func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  2304  	// just run with unknown image
  2305  	cmd := exec.Command(dockerBinary, "run", "asdfsg")
  2306  	stdout := bytes.NewBuffer(nil)
  2307  	cmd.Stdout = stdout
  2308  	if err := cmd.Run(); err == nil {
  2309  		c.Fatal("Run with unknown image should fail")
  2310  	}
  2311  	if stdout.Len() != 0 {
  2312  		c.Fatalf("Stdout contains output from pull: %s", stdout)
  2313  	}
  2314  }
  2315  
  2316  func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  2317  	testRequires(c, SameHostDaemon)
  2318  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  2319  	if _, err := buildImage("run_volumes_clean_paths",
  2320  		`FROM busybox
  2321  		VOLUME `+prefix+`/foo/`,
  2322  		true); err != nil {
  2323  		c.Fatal(err)
  2324  	}
  2325  
  2326  	dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  2327  
  2328  	out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash)
  2329  	if err != errMountNotFound {
  2330  		c.Fatalf("Found unexpected volume entry for '%s/foo/' in volumes\n%q", prefix, out)
  2331  	}
  2332  
  2333  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`)
  2334  	c.Assert(err, check.IsNil)
  2335  	if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) {
  2336  		c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out)
  2337  	}
  2338  
  2339  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar"+slash)
  2340  	if err != errMountNotFound {
  2341  		c.Fatalf("Found unexpected volume entry for '%s/bar/' in volumes\n%q", prefix, out)
  2342  	}
  2343  
  2344  	out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar")
  2345  	c.Assert(err, check.IsNil)
  2346  	if !strings.Contains(strings.ToLower(out), strings.ToLower(volumesConfigPath)) {
  2347  		c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out)
  2348  	}
  2349  }
  2350  
  2351  // Regression test for #3631
  2352  func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  2353  	// TODO Windows: This should be able to run on Windows if can find an
  2354  	// alternate to /dev/zero and /dev/stdout.
  2355  	testRequires(c, DaemonIsLinux)
  2356  	cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  2357  
  2358  	stdout, err := cont.StdoutPipe()
  2359  	if err != nil {
  2360  		c.Fatal(err)
  2361  	}
  2362  
  2363  	if err := cont.Start(); err != nil {
  2364  		c.Fatal(err)
  2365  	}
  2366  	n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2367  	if err != nil {
  2368  		c.Fatal(err)
  2369  	}
  2370  
  2371  	expected := 2 * 1024 * 2000
  2372  	if n != expected {
  2373  		c.Fatalf("Expected %d, got %d", expected, n)
  2374  	}
  2375  }
  2376  
  2377  func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  2378  	// TODO Windows: -P is not currently supported. Also network
  2379  	// settings are not propagated back.
  2380  	testRequires(c, DaemonIsLinux)
  2381  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2382  
  2383  	id := strings.TrimSpace(out)
  2384  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2385  	var ports nat.PortMap
  2386  	if err := unmarshalJSON([]byte(portstr), &ports); err != nil {
  2387  		c.Fatal(err)
  2388  	}
  2389  	for port, binding := range ports {
  2390  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2391  		if portnum < 3000 || portnum > 3003 {
  2392  			c.Fatalf("Port %d is out of range ", portnum)
  2393  		}
  2394  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2395  			c.Fatalf("Port is not mapped for the port %s", port)
  2396  		}
  2397  	}
  2398  }
  2399  
  2400  func (s *DockerSuite) TestRunExposePort(c *check.C) {
  2401  	out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  2402  	c.Assert(err, checker.NotNil, check.Commentf("--expose with an invalid port should error out"))
  2403  	c.Assert(out, checker.Contains, "invalid range format for --expose")
  2404  }
  2405  
  2406  func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  2407  	out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  2408  
  2409  	cID := strings.TrimSpace(out)
  2410  	_, _, err := dockerCmdWithError("start", cID)
  2411  
  2412  	// Windows and Linux are different here by architectural design. Linux will
  2413  	// fail to start the container, so an error is expected. Windows will
  2414  	// successfully start the container, and once started attempt to execute
  2415  	// the command which will fail.
  2416  	if daemonPlatform == "windows" {
  2417  		// Wait for it to exit.
  2418  		waitExited(cID, 30*time.Second)
  2419  		c.Assert(err, check.IsNil)
  2420  	} else {
  2421  		c.Assert(err, check.NotNil)
  2422  	}
  2423  
  2424  	rc := inspectField(c, cID, "State.ExitCode")
  2425  	if rc == "0" {
  2426  		c.Fatalf("ExitCode(%v) cannot be 0", rc)
  2427  	}
  2428  }
  2429  
  2430  func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  2431  	// Not applicable on Windows as uses Unix-specific capabilities
  2432  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2433  
  2434  	hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2435  	if err != nil {
  2436  		c.Fatal(err)
  2437  	}
  2438  
  2439  	out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2440  	out = strings.Trim(out, "\n")
  2441  	if hostIpc != out {
  2442  		c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  2443  	}
  2444  
  2445  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2446  	out = strings.Trim(out, "\n")
  2447  	if hostIpc == out {
  2448  		c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  2449  	}
  2450  }
  2451  
  2452  func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  2453  	// Not applicable on Windows as uses Unix-specific capabilities
  2454  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2455  
  2456  	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top")
  2457  
  2458  	id := strings.TrimSpace(out)
  2459  	state := inspectField(c, id, "State.Running")
  2460  	if state != "true" {
  2461  		c.Fatal("Container state is 'not running'")
  2462  	}
  2463  	pid1 := inspectField(c, id, "State.Pid")
  2464  
  2465  	parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  2466  	if err != nil {
  2467  		c.Fatal(err)
  2468  	}
  2469  
  2470  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  2471  	out = strings.Trim(out, "\n")
  2472  	if parentContainerIpc != out {
  2473  		c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  2474  	}
  2475  
  2476  	catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test")
  2477  	if catOutput != "test" {
  2478  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput)
  2479  	}
  2480  
  2481  	// check that /dev/mqueue is actually of mqueue type
  2482  	grepOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "grep", "/dev/mqueue", "/proc/mounts")
  2483  	if !strings.HasPrefix(grepOutput, "mqueue /dev/mqueue mqueue rw") {
  2484  		c.Fatalf("Output of 'grep /proc/mounts' expected 'mqueue /dev/mqueue mqueue rw' but found: %s", grepOutput)
  2485  	}
  2486  
  2487  	lsOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "ls", "/dev/mqueue")
  2488  	lsOutput = strings.Trim(lsOutput, "\n")
  2489  	if lsOutput != "toto" {
  2490  		c.Fatalf("Output of 'ls /dev/mqueue' expected 'toto' but found: %s", lsOutput)
  2491  	}
  2492  }
  2493  
  2494  func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  2495  	// Not applicable on Windows as uses Unix-specific capabilities
  2496  	testRequires(c, DaemonIsLinux)
  2497  	out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  2498  	if !strings.Contains(out, "abcd1234") || err == nil {
  2499  		c.Fatalf("run IPC from a non exists container should with correct error out")
  2500  	}
  2501  }
  2502  
  2503  func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  2504  	// Not applicable on Windows as uses Unix-specific capabilities
  2505  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2506  
  2507  	out, _ := dockerCmd(c, "create", "busybox")
  2508  
  2509  	id := strings.TrimSpace(out)
  2510  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  2511  	if err == nil {
  2512  		c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  2513  	}
  2514  }
  2515  
  2516  func (s *DockerSuite) TestRunModePidContainer(c *check.C) {
  2517  	// Not applicable on Windows as uses Unix-specific capabilities
  2518  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2519  
  2520  	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top")
  2521  
  2522  	id := strings.TrimSpace(out)
  2523  	state := inspectField(c, id, "State.Running")
  2524  	if state != "true" {
  2525  		c.Fatal("Container state is 'not running'")
  2526  	}
  2527  	pid1 := inspectField(c, id, "State.Pid")
  2528  
  2529  	parentContainerPid, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/pid", pid1))
  2530  	if err != nil {
  2531  		c.Fatal(err)
  2532  	}
  2533  
  2534  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid")
  2535  	out = strings.Trim(out, "\n")
  2536  	if parentContainerPid != out {
  2537  		c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out)
  2538  	}
  2539  }
  2540  
  2541  func (s *DockerSuite) TestRunModePidContainerNotExists(c *check.C) {
  2542  	// Not applicable on Windows as uses Unix-specific capabilities
  2543  	testRequires(c, DaemonIsLinux)
  2544  	out, _, err := dockerCmdWithError("run", "-d", "--pid", "container:abcd1234", "busybox", "top")
  2545  	if !strings.Contains(out, "abcd1234") || err == nil {
  2546  		c.Fatalf("run PID from a non exists container should with correct error out")
  2547  	}
  2548  }
  2549  
  2550  func (s *DockerSuite) TestRunModePidContainerNotRunning(c *check.C) {
  2551  	// Not applicable on Windows as uses Unix-specific capabilities
  2552  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2553  
  2554  	out, _ := dockerCmd(c, "create", "busybox")
  2555  
  2556  	id := strings.TrimSpace(out)
  2557  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox")
  2558  	if err == nil {
  2559  		c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err)
  2560  	}
  2561  }
  2562  
  2563  func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) {
  2564  	// Not applicable on Windows as uses Unix-specific capabilities
  2565  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2566  
  2567  	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")
  2568  	defer os.Remove("/dev/mqueue/toto")
  2569  	defer os.Remove("/dev/shm/test")
  2570  	volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm")
  2571  	c.Assert(err, checker.IsNil)
  2572  	if volPath != "/dev/shm" {
  2573  		c.Fatalf("volumePath should have been /dev/shm, was %s", volPath)
  2574  	}
  2575  
  2576  	out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test")
  2577  	if out != "test" {
  2578  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", out)
  2579  	}
  2580  
  2581  	// Check that the mq was created
  2582  	if _, err := os.Stat("/dev/mqueue/toto"); err != nil {
  2583  		c.Fatalf("Failed to confirm '/dev/mqueue/toto' presence on host: %s", err.Error())
  2584  	}
  2585  }
  2586  
  2587  func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  2588  	// Not applicable on Windows as uses Unix-specific capabilities
  2589  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2590  
  2591  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2592  	id := strings.TrimSpace(out)
  2593  	c.Assert(waitRun(id), check.IsNil)
  2594  	pid1 := inspectField(c, id, "State.Pid")
  2595  
  2596  	parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2597  	if err != nil {
  2598  		c.Fatal(err)
  2599  	}
  2600  
  2601  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2602  	out = strings.Trim(out, "\n")
  2603  	if parentContainerNet != out {
  2604  		c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  2605  	}
  2606  }
  2607  
  2608  func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  2609  	// Not applicable on Windows as uses Unix-specific capabilities
  2610  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2611  
  2612  	hostPid, err := os.Readlink("/proc/1/ns/pid")
  2613  	if err != nil {
  2614  		c.Fatal(err)
  2615  	}
  2616  
  2617  	out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2618  	out = strings.Trim(out, "\n")
  2619  	if hostPid != out {
  2620  		c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  2621  	}
  2622  
  2623  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2624  	out = strings.Trim(out, "\n")
  2625  	if hostPid == out {
  2626  		c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  2627  	}
  2628  }
  2629  
  2630  func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  2631  	// Not applicable on Windows as uses Unix-specific capabilities
  2632  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2633  
  2634  	hostUTS, err := os.Readlink("/proc/1/ns/uts")
  2635  	if err != nil {
  2636  		c.Fatal(err)
  2637  	}
  2638  
  2639  	out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  2640  	out = strings.Trim(out, "\n")
  2641  	if hostUTS != out {
  2642  		c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  2643  	}
  2644  
  2645  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  2646  	out = strings.Trim(out, "\n")
  2647  	if hostUTS == out {
  2648  		c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  2649  	}
  2650  
  2651  	out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps")
  2652  	c.Assert(out, checker.Contains, runconfig.ErrConflictUTSHostname.Error())
  2653  }
  2654  
  2655  func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  2656  	// Remote daemons use TLS and this test is not applicable when TLS is required.
  2657  	testRequires(c, SameHostDaemon)
  2658  	if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  2659  		c.Fatalf("Should have worked: %v:\n%v", err, out)
  2660  	}
  2661  
  2662  	// Regardless of whether we specify true or false we need to
  2663  	// test to make sure tls is turned on if --tlsverify is specified at all
  2664  	out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  2665  	if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  2666  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2667  	}
  2668  
  2669  	out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  2670  	if err == nil || code == 0 || !strings.Contains(out, "cert") {
  2671  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2672  	}
  2673  }
  2674  
  2675  func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  2676  	// TODO Windows. Once moved to libnetwork/CNM, this may be able to be
  2677  	// re-instated.
  2678  	testRequires(c, DaemonIsLinux)
  2679  	// first find allocator current position
  2680  	out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2681  
  2682  	id := strings.TrimSpace(out)
  2683  	out, _ = dockerCmd(c, "port", id)
  2684  
  2685  	out = strings.TrimSpace(out)
  2686  	if out == "" {
  2687  		c.Fatal("docker port command output is empty")
  2688  	}
  2689  	out = strings.Split(out, ":")[1]
  2690  	lastPort, err := strconv.Atoi(out)
  2691  	if err != nil {
  2692  		c.Fatal(err)
  2693  	}
  2694  	port := lastPort + 1
  2695  	l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2696  	if err != nil {
  2697  		c.Fatal(err)
  2698  	}
  2699  	defer l.Close()
  2700  
  2701  	out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2702  
  2703  	id = strings.TrimSpace(out)
  2704  	dockerCmd(c, "port", id)
  2705  }
  2706  
  2707  func (s *DockerSuite) TestRunTTYWithPipe(c *check.C) {
  2708  	errChan := make(chan error)
  2709  	go func() {
  2710  		defer close(errChan)
  2711  
  2712  		cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2713  		if _, err := cmd.StdinPipe(); err != nil {
  2714  			errChan <- err
  2715  			return
  2716  		}
  2717  
  2718  		expected := "the input device is not a TTY"
  2719  		if runtime.GOOS == "windows" {
  2720  			expected += ".  If you are using mintty, try prefixing the command with 'winpty'"
  2721  		}
  2722  		if out, _, err := runCommandWithOutput(cmd); err == nil {
  2723  			errChan <- fmt.Errorf("run should have failed")
  2724  			return
  2725  		} else if !strings.Contains(out, expected) {
  2726  			errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2727  			return
  2728  		}
  2729  	}()
  2730  
  2731  	select {
  2732  	case err := <-errChan:
  2733  		c.Assert(err, check.IsNil)
  2734  	case <-time.After(30 * time.Second):
  2735  		c.Fatal("container is running but should have failed")
  2736  	}
  2737  }
  2738  
  2739  func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  2740  	addr := "00:16:3E:08:00:50"
  2741  	args := []string{"run", "--mac-address", addr}
  2742  	expected := addr
  2743  
  2744  	if daemonPlatform != "windows" {
  2745  		args = append(args, "busybox", "ifconfig")
  2746  	} else {
  2747  		args = append(args, WindowsBaseImage, "ipconfig", "/all")
  2748  		expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
  2749  	}
  2750  
  2751  	if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
  2752  		c.Fatalf("Output should have contained %q: %s", expected, out)
  2753  	}
  2754  }
  2755  
  2756  func (s *DockerSuite) TestRunNetHost(c *check.C) {
  2757  	// Not applicable on Windows as uses Unix-specific capabilities
  2758  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2759  
  2760  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2761  	if err != nil {
  2762  		c.Fatal(err)
  2763  	}
  2764  
  2765  	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2766  	out = strings.Trim(out, "\n")
  2767  	if hostNet != out {
  2768  		c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  2769  	}
  2770  
  2771  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  2772  	out = strings.Trim(out, "\n")
  2773  	if hostNet == out {
  2774  		c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  2775  	}
  2776  }
  2777  
  2778  func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  2779  	// TODO Windows. As Windows networking evolves and converges towards
  2780  	// CNM, this test may be possible to enable on Windows.
  2781  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2782  
  2783  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2784  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2785  }
  2786  
  2787  func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  2788  	// Not applicable on Windows as uses Unix-specific capabilities
  2789  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2790  
  2791  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2792  	if err != nil {
  2793  		c.Fatal(err)
  2794  	}
  2795  
  2796  	dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2797  
  2798  	out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2799  	out = strings.Trim(out, "\n")
  2800  	if hostNet != out {
  2801  		c.Fatalf("Container should have host network namespace")
  2802  	}
  2803  }
  2804  
  2805  func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  2806  	// TODO Windows. This may be possible to enable in the future. However,
  2807  	// Windows does not currently support --expose, or populate the network
  2808  	// settings seen through inspect.
  2809  	testRequires(c, DaemonIsLinux)
  2810  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2811  
  2812  	id := strings.TrimSpace(out)
  2813  	portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports")
  2814  
  2815  	var ports nat.PortMap
  2816  	err := unmarshalJSON([]byte(portstr), &ports)
  2817  	c.Assert(err, checker.IsNil, check.Commentf("failed to unmarshal: %v", portstr))
  2818  	for port, binding := range ports {
  2819  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2820  		if portnum < 3000 || portnum > 3003 {
  2821  			c.Fatalf("Port %d is out of range ", portnum)
  2822  		}
  2823  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2824  			c.Fatal("Port is not mapped for the port "+port, out)
  2825  		}
  2826  	}
  2827  }
  2828  
  2829  func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  2830  	runSleepingContainer(c, "--name=testrunsetdefaultrestartpolicy")
  2831  	out := inspectField(c, "testrunsetdefaultrestartpolicy", "HostConfig.RestartPolicy.Name")
  2832  	if out != "no" {
  2833  		c.Fatalf("Set default restart policy failed")
  2834  	}
  2835  }
  2836  
  2837  func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  2838  	out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  2839  	timeout := 10 * time.Second
  2840  	if daemonPlatform == "windows" {
  2841  		timeout = 120 * time.Second
  2842  	}
  2843  
  2844  	id := strings.TrimSpace(string(out))
  2845  	if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
  2846  		c.Fatal(err)
  2847  	}
  2848  
  2849  	count := inspectField(c, id, "RestartCount")
  2850  	if count != "3" {
  2851  		c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2852  	}
  2853  
  2854  	MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2855  	if MaximumRetryCount != "3" {
  2856  		c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2857  	}
  2858  }
  2859  
  2860  func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  2861  	dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  2862  }
  2863  
  2864  func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  2865  	// Not applicable on Windows which does not support --read-only
  2866  	testRequires(c, DaemonIsLinux)
  2867  
  2868  	testReadOnlyFile(c, "/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me")
  2869  }
  2870  
  2871  func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  2872  	// Not applicable on Windows due to use of Unix specific functionality, plus
  2873  	// the use of --read-only which is not supported.
  2874  	// --read-only + userns has remount issues
  2875  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2876  
  2877  	// Ensure we have not broken writing /dev/pts
  2878  	out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  2879  	if status != 0 {
  2880  		c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  2881  	}
  2882  	expected := "type devpts (rw,"
  2883  	if !strings.Contains(string(out), expected) {
  2884  		c.Fatalf("expected output to contain %s but contains %s", expected, out)
  2885  	}
  2886  }
  2887  
  2888  func testReadOnlyFile(c *check.C, filenames ...string) {
  2889  	// Not applicable on Windows which does not support --read-only
  2890  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2891  	touch := "touch " + strings.Join(filenames, " ")
  2892  	out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch)
  2893  	c.Assert(err, checker.NotNil)
  2894  
  2895  	for _, f := range filenames {
  2896  		expected := "touch: " + f + ": Read-only file system"
  2897  		c.Assert(out, checker.Contains, expected)
  2898  	}
  2899  
  2900  	out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--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  
  2909  func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  2910  	// Not applicable on Windows which does not support --link
  2911  	// --read-only + userns has remount issues
  2912  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2913  
  2914  	dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  2915  
  2916  	out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  2917  	if !strings.Contains(string(out), "testlinked") {
  2918  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  2919  	}
  2920  }
  2921  
  2922  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *check.C) {
  2923  	// Not applicable on Windows which does not support either --read-only or --dns.
  2924  	// --read-only + userns has remount issues
  2925  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2926  
  2927  	out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  2928  	if !strings.Contains(string(out), "1.1.1.1") {
  2929  		c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  2930  	}
  2931  }
  2932  
  2933  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  2934  	// Not applicable on Windows which does not support --read-only
  2935  	// --read-only + userns has remount issues
  2936  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2937  
  2938  	out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  2939  	if !strings.Contains(string(out), "testreadonly") {
  2940  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  2941  	}
  2942  }
  2943  
  2944  func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  2945  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  2946  	runSleepingContainer(c, "--name=voltest", "-v", prefix+"/foo")
  2947  	runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest")
  2948  
  2949  	// Remove the main volume container and restart the consuming container
  2950  	dockerCmd(c, "rm", "-f", "voltest")
  2951  
  2952  	// This should not fail since the volumes-from were already applied
  2953  	dockerCmd(c, "restart", "restarter")
  2954  }
  2955  
  2956  // run container with --rm should remove container if exit code != 0
  2957  func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2958  	name := "flowers"
  2959  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2960  	if err == nil {
  2961  		c.Fatal("Expected docker run to fail", out, err)
  2962  	}
  2963  
  2964  	out, err = getAllContainers()
  2965  	if err != nil {
  2966  		c.Fatal(out, err)
  2967  	}
  2968  
  2969  	if out != "" {
  2970  		c.Fatal("Expected not to have containers", out)
  2971  	}
  2972  }
  2973  
  2974  func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2975  	name := "sparkles"
  2976  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  2977  	if err == nil {
  2978  		c.Fatal("Expected docker run to fail", out, err)
  2979  	}
  2980  
  2981  	out, err = getAllContainers()
  2982  	if err != nil {
  2983  		c.Fatal(out, err)
  2984  	}
  2985  
  2986  	if out != "" {
  2987  		c.Fatal("Expected not to have containers", out)
  2988  	}
  2989  }
  2990  
  2991  func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2992  	// Not applicable on Windows as uses Unix specific functionality
  2993  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2994  	name := "ibuildthecloud"
  2995  	dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2996  
  2997  	c.Assert(waitRun(name), check.IsNil)
  2998  
  2999  	errchan := make(chan error)
  3000  	go func() {
  3001  		if out, _, err := dockerCmdWithError("kill", name); err != nil {
  3002  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  3003  		}
  3004  		close(errchan)
  3005  	}()
  3006  	select {
  3007  	case err := <-errchan:
  3008  		c.Assert(err, check.IsNil)
  3009  	case <-time.After(5 * time.Second):
  3010  		c.Fatal("Kill container timed out")
  3011  	}
  3012  }
  3013  
  3014  func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  3015  	// TODO Windows. This may be possible to enable once Windows supports
  3016  	// memory limits on containers
  3017  	testRequires(c, DaemonIsLinux)
  3018  	// this memory limit is 1 byte less than the min, which is 4MB
  3019  	// https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  3020  	out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  3021  	if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  3022  		c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  3023  	}
  3024  }
  3025  
  3026  func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  3027  	// Not applicable on Windows as uses Unix specific functionality
  3028  	testRequires(c, DaemonIsLinux)
  3029  	_, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  3030  	if err == nil || code == 0 {
  3031  		c.Fatal("standard container should not be able to write to /proc/asound")
  3032  	}
  3033  }
  3034  
  3035  func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  3036  	// Not applicable on Windows as uses Unix specific functionality
  3037  	testRequires(c, DaemonIsLinux)
  3038  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  3039  	if code != 0 {
  3040  		return
  3041  	}
  3042  	if err != nil {
  3043  		c.Fatal(err)
  3044  	}
  3045  	if strings.Trim(out, "\n ") != "" {
  3046  		c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  3047  	}
  3048  }
  3049  
  3050  func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  3051  	// Not applicable on Windows as uses Unix specific functionality
  3052  	testRequires(c, DaemonIsLinux)
  3053  	// some kernels don't have this configured so skip the test if this file is not found
  3054  	// on the host running the tests.
  3055  	if _, err := os.Stat("/proc/latency_stats"); err != nil {
  3056  		c.Skip("kernel doesn't have latency_stats configured")
  3057  		return
  3058  	}
  3059  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  3060  	if code != 0 {
  3061  		return
  3062  	}
  3063  	if err != nil {
  3064  		c.Fatal(err)
  3065  	}
  3066  	if strings.Trim(out, "\n ") != "" {
  3067  		c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  3068  	}
  3069  }
  3070  
  3071  func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  3072  	// Not applicable on Windows as uses Unix specific functionality
  3073  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  3074  
  3075  	testReadPaths := []string{
  3076  		"/proc/latency_stats",
  3077  		"/proc/timer_stats",
  3078  		"/proc/kcore",
  3079  	}
  3080  	for i, filePath := range testReadPaths {
  3081  		name := fmt.Sprintf("procsieve-%d", i)
  3082  		shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  3083  
  3084  		out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  3085  		if exitCode != 0 {
  3086  			return
  3087  		}
  3088  		if err != nil {
  3089  			c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  3090  		}
  3091  	}
  3092  }
  3093  
  3094  func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  3095  	// Not applicable on Windows as uses Unix specific functionality
  3096  	testRequires(c, DaemonIsLinux)
  3097  	_, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  3098  	if err == nil || code == 0 {
  3099  		c.Fatal("container should not be able to mount into /proc")
  3100  	}
  3101  }
  3102  
  3103  func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  3104  	// Not applicable on Windows as uses Unix specific functionality
  3105  	testRequires(c, DaemonIsLinux)
  3106  	testRequires(c, NotUserNamespace)
  3107  	dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  3108  }
  3109  
  3110  func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  3111  	// Not applicable on Windows as uses Unix specific functionality
  3112  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  3113  
  3114  	// In this test goroutines are used to run test cases in parallel to prevent the test from taking a long time to run.
  3115  	errChan := make(chan error)
  3116  
  3117  	go func() {
  3118  		name := "acidburn"
  3119  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount")
  3120  		if err == nil ||
  3121  			!(strings.Contains(strings.ToLower(out), "permission denied") ||
  3122  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  3123  			errChan <- fmt.Errorf("unshare with --mount-proc should have failed with 'permission denied' or 'operation not permitted', got: %s, %v", out, err)
  3124  		} else {
  3125  			errChan <- nil
  3126  		}
  3127  	}()
  3128  
  3129  	go func() {
  3130  		name := "cereal"
  3131  		out, _, err := dockerCmdWithError("run", "--name", name, "--security-opt", "seccomp=unconfined", "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc")
  3132  		if err == nil ||
  3133  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  3134  				strings.Contains(strings.ToLower(out), "permission denied") ||
  3135  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  3136  			errChan <- fmt.Errorf("unshare and mount of /proc should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  3137  		} else {
  3138  			errChan <- nil
  3139  		}
  3140  	}()
  3141  
  3142  	/* Ensure still fails if running privileged with the default policy */
  3143  	go func() {
  3144  		name := "crashoverride"
  3145  		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")
  3146  		if err == nil ||
  3147  			!(strings.Contains(strings.ToLower(out), "mount: cannot mount none") ||
  3148  				strings.Contains(strings.ToLower(out), "permission denied") ||
  3149  				strings.Contains(strings.ToLower(out), "operation not permitted")) {
  3150  			errChan <- fmt.Errorf("privileged unshare with apparmor should have failed with 'mount: cannot mount none' or 'permission denied', got: %s, %v", out, err)
  3151  		} else {
  3152  			errChan <- nil
  3153  		}
  3154  	}()
  3155  
  3156  	for i := 0; i < 3; i++ {
  3157  		err := <-errChan
  3158  		if err != nil {
  3159  			c.Fatal(err)
  3160  		}
  3161  	}
  3162  }
  3163  
  3164  func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  3165  	// TODO Windows: This may be possible once Windows moves to libnetwork and CNM
  3166  	testRequires(c, DaemonIsLinux)
  3167  	dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  3168  	out, _ := dockerCmd(c, "port", "test")
  3169  	out = strings.Trim(out, "\r\n")
  3170  	if out != "" {
  3171  		c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  3172  	}
  3173  }
  3174  
  3175  // Issue #10184.
  3176  func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  3177  	// Not applicable on Windows as uses Unix specific functionality
  3178  	testRequires(c, DaemonIsLinux)
  3179  	const permissions = "crw-rw-rw-"
  3180  	out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  3181  	if status != 0 {
  3182  		c.Fatalf("expected status 0, got %d", status)
  3183  	}
  3184  	if !strings.HasPrefix(out, permissions) {
  3185  		c.Fatalf("output should begin with %q, got %q", permissions, out)
  3186  	}
  3187  }
  3188  
  3189  func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  3190  	// Not applicable on Windows as uses Unix specific functionality
  3191  	testRequires(c, DaemonIsLinux)
  3192  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  3193  
  3194  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  3195  		c.Fatalf("expected output ok received %s", actual)
  3196  	}
  3197  }
  3198  
  3199  // https://github.com/docker/docker/pull/14498
  3200  func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  3201  	prefix, slash := getPrefixAndSlashFromDaemonPlatform()
  3202  
  3203  	dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true")
  3204  
  3205  	// TODO Windows: Temporary check - remove once TP5 support is dropped
  3206  	if daemonPlatform != "windows" || windowsDaemonKV >= 14350 {
  3207  		dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  3208  	}
  3209  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  3210  
  3211  	if daemonPlatform != "windows" {
  3212  		mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test")
  3213  		c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point"))
  3214  		if mRO.RW {
  3215  			c.Fatalf("Expected RO volume was RW")
  3216  		}
  3217  	}
  3218  
  3219  	mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test")
  3220  	c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point"))
  3221  	if !mRW.RW {
  3222  		c.Fatalf("Expected RW volume was RO")
  3223  	}
  3224  }
  3225  
  3226  func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  3227  	// Not applicable on Windows as uses Unix specific functionality
  3228  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  3229  
  3230  	testWritePaths := []string{
  3231  		/* modprobe and core_pattern should both be denied by generic
  3232  		 * policy of denials for /proc/sys/kernel. These files have been
  3233  		 * picked to be checked as they are particularly sensitive to writes */
  3234  		"/proc/sys/kernel/modprobe",
  3235  		"/proc/sys/kernel/core_pattern",
  3236  		"/proc/sysrq-trigger",
  3237  		"/proc/kcore",
  3238  	}
  3239  	for i, filePath := range testWritePaths {
  3240  		name := fmt.Sprintf("writeprocsieve-%d", i)
  3241  
  3242  		shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  3243  		out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor=docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  3244  		if code != 0 {
  3245  			return
  3246  		}
  3247  		if err != nil {
  3248  			c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  3249  		}
  3250  	}
  3251  }
  3252  
  3253  func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  3254  	// Not applicable on Windows as uses Unix specific functionality
  3255  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  3256  
  3257  	expected := "test123"
  3258  
  3259  	filename := createTmpFile(c, expected)
  3260  	defer os.Remove(filename)
  3261  
  3262  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3263  
  3264  	for i := range nwfiles {
  3265  		actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  3266  		if actual != expected {
  3267  			c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  3268  		}
  3269  	}
  3270  }
  3271  
  3272  func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  3273  	// Not applicable on Windows as uses Unix specific functionality
  3274  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  3275  
  3276  	filename := createTmpFile(c, "test123")
  3277  	defer os.Remove(filename)
  3278  
  3279  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3280  
  3281  	for i := range nwfiles {
  3282  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  3283  		if err == nil || exitCode == 0 {
  3284  			c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  3285  		}
  3286  	}
  3287  }
  3288  
  3289  func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  3290  	// Not applicable on Windows as uses Unix specific functionality
  3291  	// --read-only + userns has remount issues
  3292  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  3293  
  3294  	filename := createTmpFile(c, "test123")
  3295  	defer os.Remove(filename)
  3296  
  3297  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  3298  
  3299  	for i := range nwfiles {
  3300  		_, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  3301  		if exitCode != 0 {
  3302  			c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3303  		}
  3304  	}
  3305  
  3306  	for i := range nwfiles {
  3307  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  3308  		if err == nil || exitCode == 0 {
  3309  			c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  3310  		}
  3311  	}
  3312  }
  3313  
  3314  func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  3315  	// Windows does not support this functionality
  3316  	testRequires(c, DaemonIsLinux)
  3317  	repoName := s.setupTrustedImage(c, "trusted-run")
  3318  
  3319  	// Try run
  3320  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3321  	s.trustedCmd(runCmd)
  3322  	out, _, err := runCommandWithOutput(runCmd)
  3323  	if err != nil {
  3324  		c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  3325  	}
  3326  
  3327  	if !strings.Contains(string(out), "Tagging") {
  3328  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3329  	}
  3330  
  3331  	dockerCmd(c, "rmi", repoName)
  3332  
  3333  	// Try untrusted run to ensure we pushed the tag to the registry
  3334  	runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  3335  	s.trustedCmd(runCmd)
  3336  	out, _, err = runCommandWithOutput(runCmd)
  3337  	if err != nil {
  3338  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  3339  	}
  3340  
  3341  	if !strings.Contains(string(out), "Status: Downloaded") {
  3342  		c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  3343  	}
  3344  }
  3345  
  3346  func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  3347  	// Windows does not support this functionality
  3348  	testRequires(c, DaemonIsLinux)
  3349  	repoName := fmt.Sprintf("%v/dockercliuntrusted/runtest:latest", privateRegistryURL)
  3350  	// tag the image and upload it to the private registry
  3351  	dockerCmd(c, "tag", "busybox", repoName)
  3352  	dockerCmd(c, "push", repoName)
  3353  	dockerCmd(c, "rmi", repoName)
  3354  
  3355  	// Try trusted run on untrusted tag
  3356  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3357  	s.trustedCmd(runCmd)
  3358  	out, _, err := runCommandWithOutput(runCmd)
  3359  	if err == nil {
  3360  		c.Fatalf("Error expected when running trusted run with:\n%s", out)
  3361  	}
  3362  
  3363  	if !strings.Contains(string(out), "does not have trust data for") {
  3364  		c.Fatalf("Missing expected output on trusted run:\n%s", out)
  3365  	}
  3366  }
  3367  
  3368  func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  3369  	// Windows does not support this functionality
  3370  	testRequires(c, DaemonIsLinux)
  3371  	c.Skip("Currently changes system time, causing instability")
  3372  	repoName := s.setupTrustedImage(c, "trusted-run-expired")
  3373  
  3374  	// Certificates have 10 years of expiration
  3375  	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  3376  
  3377  	runAtDifferentDate(elevenYearsFromNow, func() {
  3378  		// Try run
  3379  		runCmd := exec.Command(dockerBinary, "run", repoName)
  3380  		s.trustedCmd(runCmd)
  3381  		out, _, err := runCommandWithOutput(runCmd)
  3382  		if err == nil {
  3383  			c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  3384  		}
  3385  
  3386  		if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  3387  			c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  3388  		}
  3389  	})
  3390  
  3391  	runAtDifferentDate(elevenYearsFromNow, func() {
  3392  		// Try run
  3393  		runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  3394  		s.trustedCmd(runCmd)
  3395  		out, _, err := runCommandWithOutput(runCmd)
  3396  		if err != nil {
  3397  			c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  3398  		}
  3399  
  3400  		if !strings.Contains(string(out), "Status: Downloaded") {
  3401  			c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  3402  		}
  3403  	})
  3404  }
  3405  
  3406  func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  3407  	// Windows does not support this functionality
  3408  	testRequires(c, DaemonIsLinux)
  3409  	repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  3410  	evilLocalConfigDir, err := ioutil.TempDir("", "evilrun-local-config-dir")
  3411  	if err != nil {
  3412  		c.Fatalf("Failed to create local temp dir")
  3413  	}
  3414  
  3415  	// tag the image and upload it to the private registry
  3416  	dockerCmd(c, "tag", "busybox", repoName)
  3417  
  3418  	pushCmd := exec.Command(dockerBinary, "push", repoName)
  3419  	s.trustedCmd(pushCmd)
  3420  	out, _, err := runCommandWithOutput(pushCmd)
  3421  	if err != nil {
  3422  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3423  	}
  3424  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3425  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3426  	}
  3427  
  3428  	dockerCmd(c, "rmi", repoName)
  3429  
  3430  	// Try run
  3431  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3432  	s.trustedCmd(runCmd)
  3433  	out, _, err = runCommandWithOutput(runCmd)
  3434  	if err != nil {
  3435  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  3436  	}
  3437  
  3438  	if !strings.Contains(string(out), "Tagging") {
  3439  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3440  	}
  3441  
  3442  	dockerCmd(c, "rmi", repoName)
  3443  
  3444  	// Kill the notary server, start a new "evil" one.
  3445  	s.not.Close()
  3446  	s.not, err = newTestNotary(c)
  3447  	if err != nil {
  3448  		c.Fatalf("Restarting notary server failed.")
  3449  	}
  3450  
  3451  	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  3452  	// tag an image and upload it to the private registry
  3453  	dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  3454  
  3455  	// Push up to the new server
  3456  	pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  3457  	s.trustedCmd(pushCmd)
  3458  	out, _, err = runCommandWithOutput(pushCmd)
  3459  	if err != nil {
  3460  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3461  	}
  3462  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3463  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3464  	}
  3465  
  3466  	// Now, try running with the original client from this new trust server. This should fallback to our cached timestamp and metadata.
  3467  	runCmd = exec.Command(dockerBinary, "run", repoName)
  3468  	s.trustedCmd(runCmd)
  3469  	out, _, err = runCommandWithOutput(runCmd)
  3470  
  3471  	if err != nil {
  3472  		c.Fatalf("Error falling back to cached trust data: %s\n%s", err, out)
  3473  	}
  3474  	if !strings.Contains(string(out), "Error while downloading remote metadata, using cached timestamp") {
  3475  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3476  	}
  3477  }
  3478  
  3479  func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  3480  	// Not applicable on Windows as uses Unix specific functionality
  3481  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3482  
  3483  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  3484  	id := strings.TrimSpace(out)
  3485  	c.Assert(waitRun(id), check.IsNil)
  3486  	pid1 := inspectField(c, id, "State.Pid")
  3487  
  3488  	_, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  3489  	if err != nil {
  3490  		c.Fatal(err)
  3491  	}
  3492  }
  3493  
  3494  func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  3495  	// Not applicable on Windows as uses Unix specific functionality
  3496  	testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotGCCGO)
  3497  
  3498  	// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  3499  	// itself, but pid>1 should not be able to trace pid1.
  3500  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "sh -c readlink /proc/1/ns/net")
  3501  	if exitCode == 0 {
  3502  		c.Fatal("ptrace was not successfully restricted by AppArmor")
  3503  	}
  3504  }
  3505  
  3506  func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  3507  	// Not applicable on Windows as uses Unix specific functionality
  3508  	testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor)
  3509  
  3510  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  3511  	if exitCode != 0 {
  3512  		c.Fatal("ptrace of self failed.")
  3513  	}
  3514  }
  3515  
  3516  func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
  3517  	// Not applicable on Windows as uses Unix specific functionality
  3518  	testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace)
  3519  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  3520  	if exitCode == 0 {
  3521  		// If our test failed, attempt to repair the host system...
  3522  		_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  3523  		if exitCode == 0 {
  3524  			c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  3525  		}
  3526  	}
  3527  }
  3528  
  3529  func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  3530  	// Not applicable on Windows as uses Unix specific functionality
  3531  	testRequires(c, DaemonIsLinux)
  3532  
  3533  	dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  3534  }
  3535  
  3536  // run create container failed should clean up the container
  3537  func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  3538  	// TODO Windows. This may be possible to enable once link is supported
  3539  	testRequires(c, DaemonIsLinux)
  3540  	name := "unique_name"
  3541  	_, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  3542  	c.Assert(err, check.NotNil, check.Commentf("Expected docker run to fail!"))
  3543  
  3544  	containerID, err := inspectFieldWithError(name, "Id")
  3545  	c.Assert(err, checker.NotNil, check.Commentf("Expected not to have this container: %s!", containerID))
  3546  	c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  3547  }
  3548  
  3549  func (s *DockerSuite) TestRunNamedVolume(c *check.C) {
  3550  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  3551  	testRequires(c, DaemonIsLinux)
  3552  	dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar")
  3553  
  3554  	out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3555  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3556  
  3557  	out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar")
  3558  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3559  }
  3560  
  3561  func (s *DockerSuite) TestRunWithUlimits(c *check.C) {
  3562  	// Not applicable on Windows as uses Unix specific functionality
  3563  	testRequires(c, DaemonIsLinux)
  3564  
  3565  	out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
  3566  	ul := strings.TrimSpace(out)
  3567  	if ul != "42" {
  3568  		c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
  3569  	}
  3570  }
  3571  
  3572  func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) {
  3573  	// Not applicable on Windows as uses Unix specific functionality
  3574  	testRequires(c, DaemonIsLinux)
  3575  
  3576  	cgroupParent := "test"
  3577  	name := "cgroup-test"
  3578  
  3579  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3580  	if err != nil {
  3581  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3582  	}
  3583  	cgroupPaths := parseCgroupPaths(string(out))
  3584  	if len(cgroupPaths) == 0 {
  3585  		c.Fatalf("unexpected output - %q", string(out))
  3586  	}
  3587  	id, err := getIDByName(name)
  3588  	c.Assert(err, check.IsNil)
  3589  	expectedCgroup := path.Join(cgroupParent, id)
  3590  	found := false
  3591  	for _, path := range cgroupPaths {
  3592  		if strings.HasSuffix(path, expectedCgroup) {
  3593  			found = true
  3594  			break
  3595  		}
  3596  	}
  3597  	if !found {
  3598  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3599  	}
  3600  }
  3601  
  3602  func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) {
  3603  	// Not applicable on Windows as uses Unix specific functionality
  3604  	testRequires(c, DaemonIsLinux)
  3605  
  3606  	cgroupParent := "/cgroup-parent/test"
  3607  	name := "cgroup-test"
  3608  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3609  	if err != nil {
  3610  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3611  	}
  3612  	cgroupPaths := parseCgroupPaths(string(out))
  3613  	if len(cgroupPaths) == 0 {
  3614  		c.Fatalf("unexpected output - %q", string(out))
  3615  	}
  3616  	id, err := getIDByName(name)
  3617  	c.Assert(err, check.IsNil)
  3618  	expectedCgroup := path.Join(cgroupParent, id)
  3619  	found := false
  3620  	for _, path := range cgroupPaths {
  3621  		if strings.HasSuffix(path, expectedCgroup) {
  3622  			found = true
  3623  			break
  3624  		}
  3625  	}
  3626  	if !found {
  3627  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3628  	}
  3629  }
  3630  
  3631  // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
  3632  func (s *DockerSuite) TestRunInvalidCgroupParent(c *check.C) {
  3633  	// Not applicable on Windows as uses Unix specific functionality
  3634  	testRequires(c, DaemonIsLinux)
  3635  
  3636  	cgroupParent := "../../../../../../../../SHOULD_NOT_EXIST"
  3637  	cleanCgroupParent := "SHOULD_NOT_EXIST"
  3638  	name := "cgroup-invalid-test"
  3639  
  3640  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3641  	if err != nil {
  3642  		// XXX: This may include a daemon crash.
  3643  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3644  	}
  3645  
  3646  	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
  3647  	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
  3648  		c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!")
  3649  	}
  3650  
  3651  	cgroupPaths := parseCgroupPaths(string(out))
  3652  	if len(cgroupPaths) == 0 {
  3653  		c.Fatalf("unexpected output - %q", string(out))
  3654  	}
  3655  	id, err := getIDByName(name)
  3656  	c.Assert(err, check.IsNil)
  3657  	expectedCgroup := path.Join(cleanCgroupParent, id)
  3658  	found := false
  3659  	for _, path := range cgroupPaths {
  3660  		if strings.HasSuffix(path, expectedCgroup) {
  3661  			found = true
  3662  			break
  3663  		}
  3664  	}
  3665  	if !found {
  3666  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3667  	}
  3668  }
  3669  
  3670  // TestRunInvalidCgroupParent checks that a specially-crafted cgroup parent doesn't cause Docker to crash or start modifying /.
  3671  func (s *DockerSuite) TestRunAbsoluteInvalidCgroupParent(c *check.C) {
  3672  	// Not applicable on Windows as uses Unix specific functionality
  3673  	testRequires(c, DaemonIsLinux)
  3674  
  3675  	cgroupParent := "/../../../../../../../../SHOULD_NOT_EXIST"
  3676  	cleanCgroupParent := "/SHOULD_NOT_EXIST"
  3677  	name := "cgroup-absolute-invalid-test"
  3678  
  3679  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3680  	if err != nil {
  3681  		// XXX: This may include a daemon crash.
  3682  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3683  	}
  3684  
  3685  	// We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue.
  3686  	if _, err := os.Stat("/SHOULD_NOT_EXIST"); err == nil || !os.IsNotExist(err) {
  3687  		c.Fatalf("SECURITY: --cgroup-parent with /../../ garbage paths cause files to be created in the host (this is bad) !!")
  3688  	}
  3689  
  3690  	cgroupPaths := parseCgroupPaths(string(out))
  3691  	if len(cgroupPaths) == 0 {
  3692  		c.Fatalf("unexpected output - %q", string(out))
  3693  	}
  3694  	id, err := getIDByName(name)
  3695  	c.Assert(err, check.IsNil)
  3696  	expectedCgroup := path.Join(cleanCgroupParent, id)
  3697  	found := false
  3698  	for _, path := range cgroupPaths {
  3699  		if strings.HasSuffix(path, expectedCgroup) {
  3700  			found = true
  3701  			break
  3702  		}
  3703  	}
  3704  	if !found {
  3705  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3706  	}
  3707  }
  3708  
  3709  func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
  3710  	// Not applicable on Windows as uses Unix specific functionality
  3711  	// --read-only + userns has remount issues
  3712  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3713  
  3714  	filename := "/sys/fs/cgroup/devices/test123"
  3715  	out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
  3716  	if err == nil {
  3717  		c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
  3718  	}
  3719  	expected := "Read-only file system"
  3720  	if !strings.Contains(out, expected) {
  3721  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  3722  	}
  3723  }
  3724  
  3725  func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) {
  3726  	// Not applicable on Windows which does not support --net=container
  3727  	testRequires(c, DaemonIsLinux)
  3728  	out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
  3729  	if err == nil || !strings.Contains(out, "cannot join own network") {
  3730  		c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
  3731  	}
  3732  }
  3733  
  3734  func (s *DockerSuite) TestRunContainerNetModeWithDNSMacHosts(c *check.C) {
  3735  	// Not applicable on Windows which does not support --net=container
  3736  	testRequires(c, DaemonIsLinux)
  3737  	out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
  3738  	if err != nil {
  3739  		c.Fatalf("failed to run container: %v, output: %q", err, out)
  3740  	}
  3741  
  3742  	out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
  3743  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error()) {
  3744  		c.Fatalf("run --net=container with --dns should error out")
  3745  	}
  3746  
  3747  	out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
  3748  	if err == nil || !strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error()) {
  3749  		c.Fatalf("run --net=container with --mac-address should error out")
  3750  	}
  3751  
  3752  	out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
  3753  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error()) {
  3754  		c.Fatalf("run --net=container with --add-host should error out")
  3755  	}
  3756  }
  3757  
  3758  func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) {
  3759  	// Not applicable on Windows which does not support --net=container
  3760  	testRequires(c, DaemonIsLinux)
  3761  	dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  3762  
  3763  	out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
  3764  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3765  		c.Fatalf("run --net=container with -p should error out")
  3766  	}
  3767  
  3768  	out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
  3769  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) {
  3770  		c.Fatalf("run --net=container with -P should error out")
  3771  	}
  3772  
  3773  	out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
  3774  	if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error()) {
  3775  		c.Fatalf("run --net=container with --expose should error out")
  3776  	}
  3777  }
  3778  
  3779  func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
  3780  	// Not applicable on Windows which does not support --net=container or --link
  3781  	testRequires(c, DaemonIsLinux)
  3782  	dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
  3783  	dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  3784  	dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
  3785  	dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  3786  	dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
  3787  }
  3788  
  3789  func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
  3790  	// TODO Windows: This may be possible to convert.
  3791  	testRequires(c, DaemonIsLinux)
  3792  	out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  3793  
  3794  	var (
  3795  		count = 0
  3796  		parts = strings.Split(out, "\n")
  3797  	)
  3798  
  3799  	for _, l := range parts {
  3800  		if l != "" {
  3801  			count++
  3802  		}
  3803  	}
  3804  
  3805  	if count != 1 {
  3806  		c.Fatalf("Wrong interface count in container %d", count)
  3807  	}
  3808  
  3809  	if !strings.HasPrefix(out, "1: lo") {
  3810  		c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  3811  	}
  3812  }
  3813  
  3814  // Issue #4681
  3815  func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
  3816  	if daemonPlatform == "windows" {
  3817  		dockerCmd(c, "run", "--net=none", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1")
  3818  	} else {
  3819  		dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  3820  	}
  3821  }
  3822  
  3823  func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
  3824  	// Windows does not support --net=container
  3825  	testRequires(c, DaemonIsLinux, ExecSupport)
  3826  
  3827  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  3828  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
  3829  	out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  3830  
  3831  	if out1 != out {
  3832  		c.Fatal("containers with shared net namespace should have same hostname")
  3833  	}
  3834  }
  3835  
  3836  func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
  3837  	// TODO Windows: Network settings are not currently propagated. This may
  3838  	// be resolved in the future with the move to libnetwork and CNM.
  3839  	testRequires(c, DaemonIsLinux)
  3840  	out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  3841  	id := strings.TrimSpace(out)
  3842  	res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress")
  3843  	if res != "" {
  3844  		c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  3845  	}
  3846  }
  3847  
  3848  func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) {
  3849  	// Not applicable as Windows does not support --net=host
  3850  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace)
  3851  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3852  	dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
  3853  	dockerCmd(c, "stop", "first")
  3854  	dockerCmd(c, "stop", "second")
  3855  }
  3856  
  3857  func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *check.C) {
  3858  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3859  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork")
  3860  	dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top")
  3861  	c.Assert(waitRun("first"), check.IsNil)
  3862  	dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first")
  3863  }
  3864  
  3865  func (s *DockerSuite) TestContainersInMultipleNetworks(c *check.C) {
  3866  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3867  	// Create 2 networks using bridge driver
  3868  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3869  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3870  	// Run and connect containers to testnetwork1
  3871  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3872  	c.Assert(waitRun("first"), check.IsNil)
  3873  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3874  	c.Assert(waitRun("second"), check.IsNil)
  3875  	// Check connectivity between containers in testnetwork2
  3876  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3877  	// Connect containers to testnetwork2
  3878  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3879  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3880  	// Check connectivity between containers
  3881  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3882  }
  3883  
  3884  func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) {
  3885  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3886  	// Create 2 networks using bridge driver
  3887  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3888  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3889  	// Run 1 container in testnetwork1 and another in testnetwork2
  3890  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3891  	c.Assert(waitRun("first"), check.IsNil)
  3892  	dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top")
  3893  	c.Assert(waitRun("second"), check.IsNil)
  3894  
  3895  	// Check Isolation between containers : ping must fail
  3896  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3897  	c.Assert(err, check.NotNil)
  3898  	// Connect first container to testnetwork2
  3899  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3900  	// ping must succeed now
  3901  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3902  	c.Assert(err, check.IsNil)
  3903  
  3904  	// Disconnect first container from testnetwork2
  3905  	dockerCmd(c, "network", "disconnect", "testnetwork2", "first")
  3906  	// ping must fail again
  3907  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3908  	c.Assert(err, check.NotNil)
  3909  }
  3910  
  3911  func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) {
  3912  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3913  	// Create 2 networks using bridge driver
  3914  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3915  	// Run and connect containers to testnetwork1
  3916  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3917  	c.Assert(waitRun("first"), check.IsNil)
  3918  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3919  	c.Assert(waitRun("second"), check.IsNil)
  3920  	// Network delete with active containers must fail
  3921  	_, _, err := dockerCmdWithError("network", "rm", "testnetwork1")
  3922  	c.Assert(err, check.NotNil)
  3923  
  3924  	dockerCmd(c, "stop", "first")
  3925  	_, _, err = dockerCmdWithError("network", "rm", "testnetwork1")
  3926  	c.Assert(err, check.NotNil)
  3927  }
  3928  
  3929  func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) {
  3930  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
  3931  	// Create 2 networks using bridge driver
  3932  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3933  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3934  
  3935  	// Run and connect containers to testnetwork1
  3936  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3937  	c.Assert(waitRun("first"), check.IsNil)
  3938  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3939  	c.Assert(waitRun("second"), check.IsNil)
  3940  	// Check connectivity between containers in testnetwork2
  3941  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3942  	// Connect containers to testnetwork2
  3943  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3944  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3945  	// Check connectivity between containers
  3946  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3947  
  3948  	// Stop second container and test ping failures on both networks
  3949  	dockerCmd(c, "stop", "second")
  3950  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3951  	c.Assert(err, check.NotNil)
  3952  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2")
  3953  	c.Assert(err, check.NotNil)
  3954  
  3955  	// Start second container and connectivity must be restored on both networks
  3956  	dockerCmd(c, "start", "second")
  3957  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3958  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3959  }
  3960  
  3961  func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) {
  3962  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3963  	// Run a container with --net=host
  3964  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3965  	c.Assert(waitRun("first"), check.IsNil)
  3966  
  3967  	// Create a network using bridge driver
  3968  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3969  
  3970  	// Connecting to the user defined network must fail
  3971  	_, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3972  	c.Assert(err, check.NotNil)
  3973  }
  3974  
  3975  func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) {
  3976  	testRequires(c, DaemonIsLinux)
  3977  	dockerCmd(c, "run", "-d", "--name=first", "busybox", "top")
  3978  	c.Assert(waitRun("first"), check.IsNil)
  3979  	// Run second container in first container's network namespace
  3980  	dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top")
  3981  	c.Assert(waitRun("second"), check.IsNil)
  3982  
  3983  	// Create a network using bridge driver
  3984  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3985  
  3986  	// Connecting to the user defined network must fail
  3987  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second")
  3988  	c.Assert(err, check.NotNil)
  3989  	c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error())
  3990  }
  3991  
  3992  func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) {
  3993  	testRequires(c, DaemonIsLinux)
  3994  	dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top")
  3995  	c.Assert(waitRun("first"), check.IsNil)
  3996  
  3997  	// Create a network using bridge driver
  3998  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3999  
  4000  	// Connecting to the user defined network must fail
  4001  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  4002  	c.Assert(err, check.NotNil)
  4003  	c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error())
  4004  
  4005  	// create a container connected to testnetwork1
  4006  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  4007  	c.Assert(waitRun("second"), check.IsNil)
  4008  
  4009  	// Connect second container to none network. it must fail as well
  4010  	_, _, err = dockerCmdWithError("network", "connect", "none", "second")
  4011  	c.Assert(err, check.NotNil)
  4012  }
  4013  
  4014  // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited
  4015  func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) {
  4016  	cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true")
  4017  	in, err := cmd.StdinPipe()
  4018  	c.Assert(err, check.IsNil)
  4019  	defer in.Close()
  4020  	stdout := bytes.NewBuffer(nil)
  4021  	cmd.Stdout = stdout
  4022  	cmd.Stderr = stdout
  4023  	c.Assert(cmd.Start(), check.IsNil)
  4024  
  4025  	waitChan := make(chan error)
  4026  	go func() {
  4027  		waitChan <- cmd.Wait()
  4028  	}()
  4029  
  4030  	select {
  4031  	case err := <-waitChan:
  4032  		c.Assert(err, check.IsNil, check.Commentf(stdout.String()))
  4033  	case <-time.After(30 * time.Second):
  4034  		c.Fatal("timeout waiting for command to exit")
  4035  	}
  4036  }
  4037  
  4038  func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) {
  4039  	// TODO Windows: This needs validation (error out) in the daemon.
  4040  	testRequires(c, DaemonIsLinux)
  4041  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true")
  4042  	c.Assert(err, check.NotNil)
  4043  	expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n"
  4044  	if !(strings.Contains(out, expected) || exitCode == 125) {
  4045  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  4046  	}
  4047  }
  4048  
  4049  func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) {
  4050  	// TODO Windows: This needs validation (error out) in the daemon.
  4051  	testRequires(c, DaemonIsLinux)
  4052  	out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true")
  4053  	c.Assert(err, check.NotNil)
  4054  	expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n"
  4055  	if !(strings.Contains(out, expected) || exitCode == 125) {
  4056  		c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode)
  4057  	}
  4058  }
  4059  
  4060  // TestRunNonExecutableCmd checks that 'docker run busybox foo' exits with error code 127'
  4061  func (s *DockerSuite) TestRunNonExecutableCmd(c *check.C) {
  4062  	name := "testNonExecutableCmd"
  4063  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "foo")
  4064  	_, exit, _ := runCommandWithOutput(runCmd)
  4065  	stateExitCode := findContainerExitCode(c, name)
  4066  	if !(exit == 127 && strings.Contains(stateExitCode, "127")) {
  4067  		c.Fatalf("Run non-executable command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode)
  4068  	}
  4069  }
  4070  
  4071  // TestRunNonExistingCmd checks that 'docker run busybox /bin/foo' exits with code 127.
  4072  func (s *DockerSuite) TestRunNonExistingCmd(c *check.C) {
  4073  	name := "testNonExistingCmd"
  4074  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/bin/foo")
  4075  	_, exit, _ := runCommandWithOutput(runCmd)
  4076  	stateExitCode := findContainerExitCode(c, name)
  4077  	if !(exit == 127 && strings.Contains(stateExitCode, "127")) {
  4078  		c.Fatalf("Run non-existing command should have errored with exit code 127, but we got exit: %d, State.ExitCode: %s", exit, stateExitCode)
  4079  	}
  4080  }
  4081  
  4082  // TestCmdCannotBeInvoked checks that 'docker run busybox /etc' exits with 126, or
  4083  // 127 on Windows. The difference is that in Windows, the container must be started
  4084  // as that's when the check is made (and yes, by it's design...)
  4085  func (s *DockerSuite) TestCmdCannotBeInvoked(c *check.C) {
  4086  	expected := 126
  4087  	if daemonPlatform == "windows" {
  4088  		expected = 127
  4089  	}
  4090  	name := "testCmdCannotBeInvoked"
  4091  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "busybox", "/etc")
  4092  	_, exit, _ := runCommandWithOutput(runCmd)
  4093  	stateExitCode := findContainerExitCode(c, name)
  4094  	if !(exit == expected && strings.Contains(stateExitCode, strconv.Itoa(expected))) {
  4095  		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)
  4096  	}
  4097  }
  4098  
  4099  // TestRunNonExistingImage checks that 'docker run foo' exits with error msg 125 and contains  'Unable to find image'
  4100  func (s *DockerSuite) TestRunNonExistingImage(c *check.C) {
  4101  	runCmd := exec.Command(dockerBinary, "run", "foo")
  4102  	out, exit, err := runCommandWithOutput(runCmd)
  4103  	if !(err != nil && exit == 125 && strings.Contains(out, "Unable to find image")) {
  4104  		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)
  4105  	}
  4106  }
  4107  
  4108  // TestDockerFails checks that 'docker run -foo busybox' exits with 125 to signal docker run failed
  4109  func (s *DockerSuite) TestDockerFails(c *check.C) {
  4110  	runCmd := exec.Command(dockerBinary, "run", "-foo", "busybox")
  4111  	out, exit, err := runCommandWithOutput(runCmd)
  4112  	if !(err != nil && exit == 125) {
  4113  		c.Fatalf("Docker run with flag not defined should exit with 125, but we got out: %s, exit: %d, err: %s", out, exit, err)
  4114  	}
  4115  }
  4116  
  4117  // TestRunInvalidReference invokes docker run with a bad reference.
  4118  func (s *DockerSuite) TestRunInvalidReference(c *check.C) {
  4119  	out, exit, _ := dockerCmdWithError("run", "busybox@foo")
  4120  	if exit == 0 {
  4121  		c.Fatalf("expected non-zero exist code; received %d", exit)
  4122  	}
  4123  
  4124  	if !strings.Contains(out, "Error parsing reference") {
  4125  		c.Fatalf(`Expected "Error parsing reference" in output; got: %s`, out)
  4126  	}
  4127  }
  4128  
  4129  // Test fix for issue #17854
  4130  func (s *DockerSuite) TestRunInitLayerPathOwnership(c *check.C) {
  4131  	// Not applicable on Windows as it does not support Linux uid/gid ownership
  4132  	testRequires(c, DaemonIsLinux)
  4133  	name := "testetcfileownership"
  4134  	_, err := buildImage(name,
  4135  		`FROM busybox
  4136  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  4137  		RUN echo 'dockerio:x:1001:' >> /etc/group
  4138  		RUN chown dockerio:dockerio /etc`,
  4139  		true)
  4140  	if err != nil {
  4141  		c.Fatal(err)
  4142  	}
  4143  
  4144  	// Test that dockerio ownership of /etc is retained at runtime
  4145  	out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc")
  4146  	out = strings.TrimSpace(out)
  4147  	if out != "dockerio:dockerio" {
  4148  		c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out)
  4149  	}
  4150  }
  4151  
  4152  func (s *DockerSuite) TestRunWithOomScoreAdj(c *check.C) {
  4153  	testRequires(c, DaemonIsLinux)
  4154  
  4155  	expected := "642"
  4156  	out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj")
  4157  	oomScoreAdj := strings.TrimSpace(out)
  4158  	if oomScoreAdj != "642" {
  4159  		c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj)
  4160  	}
  4161  }
  4162  
  4163  func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) {
  4164  	testRequires(c, DaemonIsLinux)
  4165  
  4166  	out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true")
  4167  	c.Assert(err, check.NotNil)
  4168  	expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]."
  4169  	if !strings.Contains(out, expected) {
  4170  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  4171  	}
  4172  	out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true")
  4173  	c.Assert(err, check.NotNil)
  4174  	expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]."
  4175  	if !strings.Contains(out, expected) {
  4176  		c.Fatalf("Expected output to contain %q, got %q instead", expected, out)
  4177  	}
  4178  }
  4179  
  4180  func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) {
  4181  	// Volume propagation is linux only. Also it creates directories for
  4182  	// bind mounting, so needs to be same host.
  4183  	testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace)
  4184  
  4185  	// Prepare a source directory to bind mount
  4186  	tmpDir, err := ioutil.TempDir("", "volume-source")
  4187  	if err != nil {
  4188  		c.Fatal(err)
  4189  	}
  4190  	defer os.RemoveAll(tmpDir)
  4191  
  4192  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  4193  		c.Fatal(err)
  4194  	}
  4195  
  4196  	// Convert this directory into a shared mount point so that we do
  4197  	// not rely on propagation properties of parent mount.
  4198  	cmd := exec.Command("mount", "--bind", tmpDir, tmpDir)
  4199  	if _, err = runCommand(cmd); err != nil {
  4200  		c.Fatal(err)
  4201  	}
  4202  
  4203  	cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir)
  4204  	if _, err = runCommand(cmd); err != nil {
  4205  		c.Fatal(err)
  4206  	}
  4207  
  4208  	dockerCmd(c, "run", "--privileged", "-v", fmt.Sprintf("%s:/volume-dest:shared", tmpDir), "busybox", "mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1")
  4209  
  4210  	// Make sure a bind mount under a shared volume propagated to host.
  4211  	if mounted, _ := mount.Mounted(path.Join(tmpDir, "mnt1")); !mounted {
  4212  		c.Fatalf("Bind mount under shared volume did not propagate to host")
  4213  	}
  4214  
  4215  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  4216  }
  4217  
  4218  func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) {
  4219  	// Volume propagation is linux only. Also it creates directories for
  4220  	// bind mounting, so needs to be same host.
  4221  	testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace)
  4222  
  4223  	// Prepare a source directory to bind mount
  4224  	tmpDir, err := ioutil.TempDir("", "volume-source")
  4225  	if err != nil {
  4226  		c.Fatal(err)
  4227  	}
  4228  	defer os.RemoveAll(tmpDir)
  4229  
  4230  	if err := os.Mkdir(path.Join(tmpDir, "mnt1"), 0755); err != nil {
  4231  		c.Fatal(err)
  4232  	}
  4233  
  4234  	// Prepare a source directory with file in it. We will bind mount this
  4235  	// direcotry and see if file shows up.
  4236  	tmpDir2, err := ioutil.TempDir("", "volume-source2")
  4237  	if err != nil {
  4238  		c.Fatal(err)
  4239  	}
  4240  	defer os.RemoveAll(tmpDir2)
  4241  
  4242  	if err := ioutil.WriteFile(path.Join(tmpDir2, "slave-testfile"), []byte("Test"), 0644); err != nil {
  4243  		c.Fatal(err)
  4244  	}
  4245  
  4246  	// Convert this directory into a shared mount point so that we do
  4247  	// not rely on propagation properties of parent mount.
  4248  	cmd := exec.Command("mount", "--bind", tmpDir, tmpDir)
  4249  	if _, err = runCommand(cmd); err != nil {
  4250  		c.Fatal(err)
  4251  	}
  4252  
  4253  	cmd = exec.Command("mount", "--make-private", "--make-shared", tmpDir)
  4254  	if _, err = runCommand(cmd); err != nil {
  4255  		c.Fatal(err)
  4256  	}
  4257  
  4258  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "-v", fmt.Sprintf("%s:/volume-dest:slave", tmpDir), "busybox", "top")
  4259  
  4260  	// Bind mount tmpDir2/ onto tmpDir/mnt1. If mount propagates inside
  4261  	// container then contents of tmpDir2/slave-testfile should become
  4262  	// visible at "/volume-dest/mnt1/slave-testfile"
  4263  	cmd = exec.Command("mount", "--bind", tmpDir2, path.Join(tmpDir, "mnt1"))
  4264  	if _, err = runCommand(cmd); err != nil {
  4265  		c.Fatal(err)
  4266  	}
  4267  
  4268  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/volume-dest/mnt1/slave-testfile")
  4269  
  4270  	mount.Unmount(path.Join(tmpDir, "mnt1"))
  4271  
  4272  	if out != "Test" {
  4273  		c.Fatalf("Bind mount under slave volume did not propagate to container")
  4274  	}
  4275  }
  4276  
  4277  func (s *DockerSuite) TestRunNamedVolumesMountedAsShared(c *check.C) {
  4278  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4279  	out, exitcode, _ := dockerCmdWithError("run", "-v", "foo:/test:shared", "busybox", "touch", "/test/somefile")
  4280  
  4281  	if exitcode == 0 {
  4282  		c.Fatalf("expected non-zero exit code; received %d", exitcode)
  4283  	}
  4284  
  4285  	if expected := "Invalid volume specification"; !strings.Contains(out, expected) {
  4286  		c.Fatalf(`Expected %q in output; got: %s`, expected, out)
  4287  	}
  4288  }
  4289  
  4290  func (s *DockerSuite) TestRunNamedVolumeCopyImageData(c *check.C) {
  4291  	testRequires(c, DaemonIsLinux)
  4292  
  4293  	testImg := "testvolumecopy"
  4294  	_, err := buildImage(testImg, `
  4295  	FROM busybox
  4296  	RUN mkdir -p /foo && echo hello > /foo/hello
  4297  	`, true)
  4298  	c.Assert(err, check.IsNil)
  4299  
  4300  	dockerCmd(c, "run", "-v", "foo:/foo", testImg)
  4301  	out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello")
  4302  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  4303  }
  4304  
  4305  func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *check.C) {
  4306  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  4307  
  4308  	dockerCmd(c, "volume", "create", "--name", "test")
  4309  
  4310  	dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4311  	dockerCmd(c, "volume", "inspect", "test")
  4312  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  4313  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4314  
  4315  	dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4316  	dockerCmd(c, "rm", "-fv", "test")
  4317  	dockerCmd(c, "volume", "inspect", "test")
  4318  	out, _ = dockerCmd(c, "volume", "ls", "-q")
  4319  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4320  }
  4321  
  4322  func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) {
  4323  	prefix, _ := getPrefixAndSlashFromDaemonPlatform()
  4324  
  4325  	dockerCmd(c, "volume", "create", "--name", "test")
  4326  	dockerCmd(c, "run", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true")
  4327  	dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true")
  4328  
  4329  	// Remove the parent so there are not other references to the volumes
  4330  	dockerCmd(c, "rm", "-f", "parent")
  4331  	// now remove the child and ensure the named volume (and only the named volume) still exists
  4332  	dockerCmd(c, "rm", "-fv", "child")
  4333  	dockerCmd(c, "volume", "inspect", "test")
  4334  	out, _ := dockerCmd(c, "volume", "ls", "-q")
  4335  	c.Assert(strings.TrimSpace(out), checker.Equals, "test")
  4336  }
  4337  
  4338  func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) {
  4339  	nroutines, err := getGoroutineNumber()
  4340  	c.Assert(err, checker.IsNil)
  4341  
  4342  	runSleepingContainer(c, "--name=test", "-p", "8000:8000")
  4343  
  4344  	// Wait until container is fully up and running
  4345  	c.Assert(waitRun("test"), check.IsNil)
  4346  
  4347  	out, _, err := dockerCmdWithError("run", "--name=fail", "-p", "8000:8000", "busybox", "true")
  4348  	// We will need the following `inspect` to diagnose the issue if test fails (#21247)
  4349  	out1, err1 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "test")
  4350  	out2, err2 := dockerCmd(c, "inspect", "--format", "{{json .State}}", "fail")
  4351  	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))
  4352  	// check for windows error as well
  4353  	// TODO Windows Post TP5. Fix the error message string
  4354  	c.Assert(strings.Contains(string(out), "port is already allocated") ||
  4355  		strings.Contains(string(out), "were not connected because a duplicate name exists") ||
  4356  		strings.Contains(string(out), "HNS failed with error : Failed to create endpoint") ||
  4357  		strings.Contains(string(out), "HNS failed with error : The object already exists"), checker.Equals, true, check.Commentf("Output: %s", out))
  4358  	dockerCmd(c, "rm", "-f", "test")
  4359  
  4360  	// NGoroutines is not updated right away, so we need to wait before failing
  4361  	c.Assert(waitForGoroutines(nroutines), checker.IsNil)
  4362  }
  4363  
  4364  // Test for one character directory name case (#20122)
  4365  func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *check.C) {
  4366  	testRequires(c, DaemonIsLinux)
  4367  
  4368  	out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo")
  4369  	c.Assert(strings.TrimSpace(out), checker.Equals, "/foo")
  4370  }
  4371  
  4372  func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) {
  4373  	testRequires(c, DaemonIsLinux) // Windows does not support copying data from image to the volume
  4374  	_, err := buildImage("volumecopy",
  4375  		`FROM busybox
  4376  		RUN mkdir /foo && echo hello > /foo/bar
  4377  		CMD cat /foo/bar`,
  4378  		true,
  4379  	)
  4380  	c.Assert(err, checker.IsNil)
  4381  
  4382  	dockerCmd(c, "volume", "create", "--name=test")
  4383  
  4384  	// test with the nocopy flag
  4385  	out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy")
  4386  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4387  	// test default behavior which is to copy for non-binds
  4388  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  4389  	c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  4390  	// error out when the volume is already populated
  4391  	out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy")
  4392  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4393  	// do not error out when copy isn't explicitly set even though it's already populated
  4394  	out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy")
  4395  	c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
  4396  
  4397  	// do not allow copy modes on volumes-from
  4398  	dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true")
  4399  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true")
  4400  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4401  	out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true")
  4402  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4403  
  4404  	// do not allow copy modes on binds
  4405  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true")
  4406  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4407  	out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true")
  4408  	c.Assert(err, checker.NotNil, check.Commentf(out))
  4409  }
  4410  
  4411  func (s *DockerSuite) TestRunTooLongHostname(c *check.C) {
  4412  	// Test case in #21445
  4413  	hostname1 := "this-is-a-way-too-long-hostname-but-it-should-give-a-nice-error.local"
  4414  	out, _, err := dockerCmdWithError("run", "--hostname", hostname1, "busybox", "echo", "test")
  4415  	c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!"))
  4416  	c.Assert(out, checker.Contains, "invalid hostname format:", check.Commentf("Expected to have 'invalid hostname format:' in the output, get: %s!", out))
  4417  
  4418  	// Additional test cases
  4419  	validHostnames := map[string]string{
  4420  		"hostname":    "hostname",
  4421  		"host-name":   "host-name",
  4422  		"hostname123": "hostname123",
  4423  		"123hostname": "123hostname",
  4424  		"hostname-of-63-bytes-long-should-be-valid-and-without-any-error": "hostname-of-63-bytes-long-should-be-valid-and-without-any-error",
  4425  	}
  4426  	for hostname := range validHostnames {
  4427  		dockerCmd(c, "run", "--hostname", hostname, "busybox", "echo", "test")
  4428  	}
  4429  
  4430  	invalidHostnames := map[string]string{
  4431  		"^hostname": "invalid hostname format: ^hostname",
  4432  		"hostname%": "invalid hostname format: hostname%",
  4433  		"host&name": "invalid hostname format: host&name",
  4434  		"-hostname": "invalid hostname format: -hostname",
  4435  		"host_name": "invalid hostname format: host_name",
  4436  		"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",
  4437  	}
  4438  
  4439  	for hostname, expectedError := range invalidHostnames {
  4440  		out, _, err = dockerCmdWithError("run", "--hostname", hostname, "busybox", "echo", "test")
  4441  		c.Assert(err, checker.NotNil, check.Commentf("Expected docker run to fail!"))
  4442  		c.Assert(out, checker.Contains, expectedError, check.Commentf("Expected to have '%s' in the output, get: %s!", expectedError, out))
  4443  
  4444  	}
  4445  }
  4446  
  4447  // Test case for #21976
  4448  func (s *DockerSuite) TestRunDNSInHostMode(c *check.C) {
  4449  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4450  
  4451  	expectedOutput := "nameserver 127.0.0.1"
  4452  	expectedWarning := "Localhost DNS setting"
  4453  	out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  4454  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  4455  	c.Assert(stderr, checker.Contains, expectedWarning, check.Commentf("Expected warning on stderr about localhost resolver, but got %q", stderr))
  4456  
  4457  	expectedOutput = "nameserver 1.2.3.4"
  4458  	out, _ = dockerCmd(c, "run", "--dns=1.2.3.4", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  4459  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  4460  
  4461  	expectedOutput = "search example.com"
  4462  	out, _ = dockerCmd(c, "run", "--dns-search=example.com", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  4463  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  4464  
  4465  	expectedOutput = "options timeout:3"
  4466  	out, _ = dockerCmd(c, "run", "--dns-opt=timeout:3", "--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  	expectedOutput1 := "nameserver 1.2.3.4"
  4470  	expectedOutput2 := "search example.com"
  4471  	expectedOutput3 := "options timeout:3"
  4472  	out, _ = dockerCmd(c, "run", "--dns=1.2.3.4", "--dns-search=example.com", "--dns-opt=timeout:3", "--net=host", "busybox", "cat", "/etc/resolv.conf")
  4473  	c.Assert(out, checker.Contains, expectedOutput1, check.Commentf("Expected '%s', but got %q", expectedOutput1, out))
  4474  	c.Assert(out, checker.Contains, expectedOutput2, check.Commentf("Expected '%s', but got %q", expectedOutput2, out))
  4475  	c.Assert(out, checker.Contains, expectedOutput3, check.Commentf("Expected '%s', but got %q", expectedOutput3, out))
  4476  }
  4477  
  4478  // Test case for #21976
  4479  func (s *DockerSuite) TestRunAddHostInHostMode(c *check.C) {
  4480  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  4481  
  4482  	expectedOutput := "1.2.3.4\textra"
  4483  	out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts")
  4484  	c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out))
  4485  }