github.com/fabiokung/docker@v0.11.2-0.20170222101415-4534dcd49497/integration-cli/docker_cli_run_test.go (about)

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