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