github.com/robertojrojas/docker@v1.9.1/integration-cli/docker_cli_run_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"net"
     9  	"os"
    10  	"os/exec"
    11  	"path"
    12  	"path/filepath"
    13  	"reflect"
    14  	"regexp"
    15  	"sort"
    16  	"strconv"
    17  	"strings"
    18  	"sync"
    19  	"time"
    20  
    21  	"github.com/docker/docker/pkg/integration/checker"
    22  	"github.com/docker/docker/pkg/nat"
    23  	"github.com/docker/docker/runconfig"
    24  	"github.com/docker/libnetwork/resolvconf"
    25  	"github.com/go-check/check"
    26  )
    27  
    28  // "test123" should be printed by docker run
    29  func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
    30  	out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
    31  	if out != "test123\n" {
    32  		c.Fatalf("container should've printed 'test123', got '%s'", out)
    33  	}
    34  }
    35  
    36  // "test" should be printed
    37  func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
    38  	out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
    39  	if out != "test\n" {
    40  		c.Errorf("container should've printed 'test'")
    41  	}
    42  }
    43  
    44  // docker run should not leak file descriptors. This test relies on Unix
    45  // specific functionality and cannot run on Windows.
    46  func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
    47  	testRequires(c, DaemonIsLinux)
    48  	out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
    49  
    50  	// normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
    51  	if out != "0  1  2  3\n" {
    52  		c.Errorf("container should've printed '0  1  2  3', not: %s", out)
    53  	}
    54  }
    55  
    56  // it should be possible to lookup Google DNS
    57  // this will fail when Internet access is unavailable
    58  func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
    59  	testRequires(c, Network)
    60  	image := DefaultImage
    61  	if daemonPlatform == "windows" {
    62  		// nslookup isn't present in Windows busybox. Is built-in.
    63  		image = WindowsBaseImage
    64  	}
    65  	dockerCmd(c, "run", image, "nslookup", "google.com")
    66  }
    67  
    68  // the exit code should be 0
    69  // some versions of lxc might make this test fail
    70  func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
    71  	dockerCmd(c, "run", "busybox", "true")
    72  }
    73  
    74  // the exit code should be 1
    75  // some versions of lxc might make this test fail
    76  func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
    77  	_, exitCode, err := dockerCmdWithError("run", "busybox", "false")
    78  	if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
    79  		c.Fatal(err)
    80  	}
    81  	if exitCode != 1 {
    82  		c.Errorf("container should've exited with exit code 1. Got %d", exitCode)
    83  	}
    84  }
    85  
    86  // it should be possible to pipe in data via stdin to a process running in a container
    87  // some versions of lxc might make this test fail
    88  func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
    89  	// TODO Windows: This needs some work to make compatible.
    90  	testRequires(c, DaemonIsLinux)
    91  	runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat")
    92  	runCmd.Stdin = strings.NewReader("blahblah")
    93  	out, _, _, err := runCommandWithStdoutStderr(runCmd)
    94  	if err != nil {
    95  		c.Fatalf("failed to run container: %v, output: %q", err, out)
    96  	}
    97  
    98  	out = strings.TrimSpace(out)
    99  	dockerCmd(c, "wait", out)
   100  
   101  	logsOut, _ := dockerCmd(c, "logs", out)
   102  
   103  	containerLogs := strings.TrimSpace(logsOut)
   104  	if containerLogs != "blahblah" {
   105  		c.Errorf("logs didn't print the container's logs %s", containerLogs)
   106  	}
   107  
   108  	dockerCmd(c, "rm", out)
   109  }
   110  
   111  // the container's ID should be printed when starting a container in detached mode
   112  func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
   113  	out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
   114  
   115  	out = strings.TrimSpace(out)
   116  	dockerCmd(c, "wait", out)
   117  
   118  	rmOut, _ := dockerCmd(c, "rm", out)
   119  
   120  	rmOut = strings.TrimSpace(rmOut)
   121  	if rmOut != out {
   122  		c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
   123  	}
   124  }
   125  
   126  // the working directory should be set correctly
   127  func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
   128  	// TODO Windows: There's a Windows bug stopping this from working.
   129  	testRequires(c, DaemonIsLinux)
   130  	dir := "/root"
   131  	image := "busybox"
   132  	if daemonPlatform == "windows" {
   133  		dir = `/windows`
   134  		image = WindowsBaseImage
   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  	// And then with the short form -n
   171  	out, exitCode, err = dockerCmdWithError("run", "-n=false", image, "ping", count, "1", "8.8.8.8")
   172  	if err != nil && exitCode != 1 {
   173  		c.Fatal(out, err)
   174  	}
   175  	if exitCode != 1 {
   176  		c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
   177  	}
   178  }
   179  
   180  //test --link use container name to link target
   181  func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
   182  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   183  	// settings are not populated back yet on inspect.
   184  	testRequires(c, DaemonIsLinux)
   185  	dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
   186  
   187  	ip, err := inspectField("parent", "NetworkSettings.Networks.bridge.IPAddress")
   188  	c.Assert(err, check.IsNil)
   189  
   190  	out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
   191  	if !strings.Contains(out, ip+"	test") {
   192  		c.Fatalf("use a container name to link target failed")
   193  	}
   194  }
   195  
   196  //test --link use container id to link target
   197  func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
   198  	// TODO Windows: This test cannot run on a Windows daemon as the networking
   199  	// settings are not populated back yet on inspect.
   200  	testRequires(c, DaemonIsLinux)
   201  	cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
   202  
   203  	cID = strings.TrimSpace(cID)
   204  	ip, err := inspectField(cID, "NetworkSettings.Networks.bridge.IPAddress")
   205  	c.Assert(err, check.IsNil)
   206  
   207  	out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
   208  	if !strings.Contains(out, ip+"	test") {
   209  		c.Fatalf("use a container id to link target failed")
   210  	}
   211  }
   212  
   213  // Issue 9677.
   214  func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) {
   215  	out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "-t", "busybox", "true")
   216  	if err != nil {
   217  		if !strings.Contains(out, "must follow the 'docker daemon' command") && // daemon
   218  			!strings.Contains(out, "flag provided but not defined: --exec-opt") { // no daemon (client-only)
   219  			c.Fatal(err, out)
   220  		}
   221  	}
   222  }
   223  
   224  // Regression test for #4979
   225  func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
   226  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   227  	// not support volumes
   228  	testRequires(c, DaemonIsLinux)
   229  	out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
   230  	if exitCode != 0 {
   231  		c.Fatal("1", out, exitCode)
   232  	}
   233  
   234  	out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
   235  	if exitCode != 0 {
   236  		c.Fatal("2", out, exitCode)
   237  	}
   238  }
   239  
   240  // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
   241  // But the volume call is just a normal volume, not a bind mount
   242  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
   243  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   244  	// not support volumes
   245  	testRequires(c, DaemonIsLinux, SameHostDaemon, NativeExecDriver)
   246  	name := "test-volume-symlink"
   247  
   248  	dir, err := ioutil.TempDir("", name)
   249  	if err != nil {
   250  		c.Fatal(err)
   251  	}
   252  	defer os.RemoveAll(dir)
   253  
   254  	f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
   255  	if err != nil {
   256  		c.Fatal(err)
   257  	}
   258  	f.Close()
   259  
   260  	dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
   261  	if _, err := buildImage(name, dockerFile, false); err != nil {
   262  		c.Fatal(err)
   263  	}
   264  
   265  	dockerCmd(c, "run", "-v", "/test/test", name)
   266  }
   267  
   268  func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
   269  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   270  	// not support volumes
   271  	testRequires(c, DaemonIsLinux)
   272  	if _, code, err := dockerCmdWithError("run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 {
   273  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   274  	}
   275  }
   276  
   277  func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) {
   278  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   279  	// not support volumes
   280  	testRequires(c, DaemonIsLinux)
   281  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
   282  
   283  	if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 {
   284  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   285  	}
   286  }
   287  
   288  // Regression test for #1201
   289  func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
   290  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   291  	// not support volumes
   292  	testRequires(c, DaemonIsLinux)
   293  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
   294  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
   295  
   296  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
   297  		c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
   298  	}
   299  
   300  	dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
   301  }
   302  
   303  func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
   304  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   305  	// not support volumes
   306  	testRequires(c, DaemonIsLinux)
   307  	dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
   308  
   309  	// Expect this "rw" mode to be be ignored since the inherited volume is "ro"
   310  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
   311  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
   312  	}
   313  
   314  	dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
   315  
   316  	// Expect this to be read-only since both are "ro"
   317  	if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
   318  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
   319  	}
   320  }
   321  
   322  // Test for GH#10618
   323  func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
   324  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   325  	// not support volumes
   326  	testRequires(c, DaemonIsLinux)
   327  	mountstr1 := randomTmpDirPath("test1", daemonPlatform) + ":/someplace"
   328  	mountstr2 := randomTmpDirPath("test2", daemonPlatform) + ":/someplace"
   329  
   330  	if out, _, err := dockerCmdWithError("run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
   331  		c.Fatal("Expected error about duplicate volume definitions")
   332  	} else {
   333  		if !strings.Contains(out, "Duplicate bind mount") {
   334  			c.Fatalf("Expected 'duplicate volume' error, got %v", err)
   335  		}
   336  	}
   337  }
   338  
   339  // Test for #1351
   340  func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
   341  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   342  	// not support volumes
   343  	testRequires(c, DaemonIsLinux)
   344  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
   345  	dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
   346  }
   347  
   348  func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
   349  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   350  	// not support volumes
   351  	testRequires(c, DaemonIsLinux)
   352  	dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
   353  	dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
   354  	dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
   355  }
   356  
   357  // this tests verifies the ID format for the container
   358  func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
   359  	out, exit, err := dockerCmdWithError("run", "-d", "busybox", "true")
   360  	if err != nil {
   361  		c.Fatal(err)
   362  	}
   363  	if exit != 0 {
   364  		c.Fatalf("expected exit code 0 received %d", exit)
   365  	}
   366  
   367  	match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
   368  	if err != nil {
   369  		c.Fatal(err)
   370  	}
   371  	if !match {
   372  		c.Fatalf("Invalid container ID: %s", out)
   373  	}
   374  }
   375  
   376  // Test that creating a container with a volume doesn't crash. Regression test for #995.
   377  func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
   378  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   379  	// not support volumes
   380  	testRequires(c, DaemonIsLinux)
   381  	dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true")
   382  }
   383  
   384  // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
   385  // Note that this bug happens only with symlinks with a target that starts with '/'.
   386  func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
   387  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   388  	// not support volumes
   389  	testRequires(c, DaemonIsLinux)
   390  	image := "docker-test-createvolumewithsymlink"
   391  
   392  	buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
   393  	buildCmd.Stdin = strings.NewReader(`FROM busybox
   394  		RUN ln -s home /bar`)
   395  	buildCmd.Dir = workingDirectory
   396  	err := buildCmd.Run()
   397  	if err != nil {
   398  		c.Fatalf("could not build '%s': %v", image, err)
   399  	}
   400  
   401  	_, exitCode, err := dockerCmdWithError("run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
   402  	if err != nil || exitCode != 0 {
   403  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   404  	}
   405  
   406  	volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
   407  	if err != nil {
   408  		c.Fatalf("[inspect] err: %v", err)
   409  	}
   410  
   411  	_, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink")
   412  	if err != nil || exitCode != 0 {
   413  		c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
   414  	}
   415  
   416  	_, err = os.Stat(volPath)
   417  	if !os.IsNotExist(err) {
   418  		c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
   419  	}
   420  }
   421  
   422  // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
   423  func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
   424  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   425  	// not support volumes
   426  	testRequires(c, DaemonIsLinux)
   427  	name := "docker-test-volumesfromsymlinkpath"
   428  
   429  	buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
   430  	buildCmd.Stdin = strings.NewReader(`FROM busybox
   431  		RUN ln -s home /foo
   432  		VOLUME ["/foo/bar"]`)
   433  	buildCmd.Dir = workingDirectory
   434  	err := buildCmd.Run()
   435  	if err != nil {
   436  		c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
   437  	}
   438  
   439  	_, exitCode, err := dockerCmdWithError("run", "--name", "test-volumesfromsymlinkpath", name)
   440  	if err != nil || exitCode != 0 {
   441  		c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
   442  	}
   443  
   444  	_, exitCode, err = dockerCmdWithError("run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
   445  	if err != nil || exitCode != 0 {
   446  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   447  	}
   448  }
   449  
   450  func (s *DockerSuite) TestRunExitCode(c *check.C) {
   451  	var (
   452  		exit int
   453  		err  error
   454  	)
   455  
   456  	_, exit, err = dockerCmdWithError("run", "busybox", "/bin/sh", "-c", "exit 72")
   457  
   458  	if err == nil {
   459  		c.Fatal("should not have a non nil error")
   460  	}
   461  	if exit != 72 {
   462  		c.Fatalf("expected exit code 72 received %d", exit)
   463  	}
   464  }
   465  
   466  func (s *DockerSuite) TestRunUserDefaults(c *check.C) {
   467  	expected := "uid=0(root) gid=0(root)"
   468  	if daemonPlatform == "windows" {
   469  		expected = "uid=1000(SYSTEM) gid=1000(SYSTEM)"
   470  	}
   471  	out, _ := dockerCmd(c, "run", "busybox", "id")
   472  	if !strings.Contains(out, expected) {
   473  		c.Fatalf("expected '%s' got %s", expected, out)
   474  	}
   475  }
   476  
   477  func (s *DockerSuite) TestRunUserByName(c *check.C) {
   478  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   479  	// not support the use of -u
   480  	testRequires(c, DaemonIsLinux)
   481  	out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
   482  	if !strings.Contains(out, "uid=0(root) gid=0(root)") {
   483  		c.Fatalf("expected root user got %s", out)
   484  	}
   485  }
   486  
   487  func (s *DockerSuite) TestRunUserByID(c *check.C) {
   488  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   489  	// not support the use of -u
   490  	testRequires(c, DaemonIsLinux)
   491  	out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
   492  	if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
   493  		c.Fatalf("expected daemon user got %s", out)
   494  	}
   495  }
   496  
   497  func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
   498  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   499  	// not support the use of -u
   500  	testRequires(c, DaemonIsLinux)
   501  	out, _, err := dockerCmdWithError("run", "-u", "2147483648", "busybox", "id")
   502  	if err == nil {
   503  		c.Fatal("No error, but must be.", out)
   504  	}
   505  	if !strings.Contains(out, "Uids and gids must be in range") {
   506  		c.Fatalf("expected error about uids range, got %s", out)
   507  	}
   508  }
   509  
   510  func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
   511  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   512  	// not support the use of -u
   513  	testRequires(c, DaemonIsLinux)
   514  	out, _, err := dockerCmdWithError("run", "-u", "-1", "busybox", "id")
   515  	if err == nil {
   516  		c.Fatal("No error, but must be.", out)
   517  	}
   518  	if !strings.Contains(out, "Uids and gids must be in range") {
   519  		c.Fatalf("expected error about uids range, got %s", out)
   520  	}
   521  }
   522  
   523  func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
   524  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   525  	// not support the use of -u
   526  	testRequires(c, DaemonIsLinux)
   527  	out, _, err := dockerCmdWithError("run", "-u", "0", "busybox", "id")
   528  	if err != nil {
   529  		c.Fatal(err, out)
   530  	}
   531  	if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
   532  		c.Fatalf("expected daemon user got %s", out)
   533  	}
   534  }
   535  
   536  func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
   537  	// TODO Windows: This test cannot run on a Windows daemon as Windows does
   538  	// not support the use of -u
   539  	testRequires(c, DaemonIsLinux)
   540  	_, _, err := dockerCmdWithError("run", "-u", "notme", "busybox", "id")
   541  	if err == nil {
   542  		c.Fatal("unknown user should cause container to fail")
   543  	}
   544  }
   545  
   546  func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
   547  	sleepTime := "2"
   548  	if daemonPlatform == "windows" {
   549  		sleepTime = "5" // Make more reliable on Windows
   550  	}
   551  	group := sync.WaitGroup{}
   552  	group.Add(2)
   553  
   554  	errChan := make(chan error, 2)
   555  	for i := 0; i < 2; i++ {
   556  		go func() {
   557  			defer group.Done()
   558  			_, _, err := dockerCmdWithError("run", "busybox", "sleep", sleepTime)
   559  			errChan <- err
   560  		}()
   561  	}
   562  
   563  	group.Wait()
   564  	close(errChan)
   565  
   566  	for err := range errChan {
   567  		c.Assert(err, check.IsNil)
   568  	}
   569  }
   570  
   571  func (s *DockerSuite) TestRunEnvironment(c *check.C) {
   572  	// TODO Windows: Environment handling is different between Linux and
   573  	// Windows and this test relies currently on lxc and unix functionality.
   574  	testRequires(c, DaemonIsLinux)
   575  	cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
   576  	cmd.Env = append(os.Environ(),
   577  		"TRUE=false",
   578  		"TRICKY=tri\ncky\n",
   579  	)
   580  
   581  	out, _, err := runCommandWithOutput(cmd)
   582  	if err != nil {
   583  		c.Fatal(err, out)
   584  	}
   585  
   586  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   587  	actualEnv := []string{}
   588  	for i := range actualEnvLxc {
   589  		if actualEnvLxc[i] != "container=lxc" {
   590  			actualEnv = append(actualEnv, actualEnvLxc[i])
   591  		}
   592  	}
   593  	sort.Strings(actualEnv)
   594  
   595  	goodEnv := []string{
   596  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   597  		"HOSTNAME=testing",
   598  		"FALSE=true",
   599  		"TRUE=false",
   600  		"TRICKY=tri",
   601  		"cky",
   602  		"",
   603  		"HOME=/root",
   604  	}
   605  	sort.Strings(goodEnv)
   606  	if len(goodEnv) != len(actualEnv) {
   607  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   608  	}
   609  	for i := range goodEnv {
   610  		if actualEnv[i] != goodEnv[i] {
   611  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   612  		}
   613  	}
   614  }
   615  
   616  func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
   617  	// TODO Windows: Environment handling is different between Linux and
   618  	// Windows and this test relies currently on lxc and unix functionality.
   619  	testRequires(c, DaemonIsLinux)
   620  
   621  	// Test to make sure that when we use -e on env vars that are
   622  	// not set in our local env that they're removed (if present) in
   623  	// the container
   624  
   625  	cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
   626  	cmd.Env = appendBaseEnv([]string{})
   627  
   628  	out, _, err := runCommandWithOutput(cmd)
   629  	if err != nil {
   630  		c.Fatal(err, out)
   631  	}
   632  
   633  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   634  	actualEnv := []string{}
   635  	for i := range actualEnvLxc {
   636  		if actualEnvLxc[i] != "container=lxc" {
   637  			actualEnv = append(actualEnv, actualEnvLxc[i])
   638  		}
   639  	}
   640  	sort.Strings(actualEnv)
   641  
   642  	goodEnv := []string{
   643  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   644  		"HOME=/root",
   645  	}
   646  	sort.Strings(goodEnv)
   647  	if len(goodEnv) != len(actualEnv) {
   648  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   649  	}
   650  	for i := range goodEnv {
   651  		if actualEnv[i] != goodEnv[i] {
   652  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   653  		}
   654  	}
   655  }
   656  
   657  func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
   658  	// TODO Windows: Environment handling is different between Linux and
   659  	// Windows and this test relies currently on lxc and unix functionality.
   660  	testRequires(c, DaemonIsLinux)
   661  
   662  	// Test to make sure that when we use -e on env vars that are
   663  	// already in the env that we're overriding them
   664  
   665  	cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
   666  	cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"})
   667  
   668  	out, _, err := runCommandWithOutput(cmd)
   669  	if err != nil {
   670  		c.Fatal(err, out)
   671  	}
   672  
   673  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   674  	actualEnv := []string{}
   675  	for i := range actualEnvLxc {
   676  		if actualEnvLxc[i] != "container=lxc" {
   677  			actualEnv = append(actualEnv, actualEnvLxc[i])
   678  		}
   679  	}
   680  	sort.Strings(actualEnv)
   681  
   682  	goodEnv := []string{
   683  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   684  		"HOME=/root2",
   685  		"HOSTNAME=bar",
   686  	}
   687  	sort.Strings(goodEnv)
   688  	if len(goodEnv) != len(actualEnv) {
   689  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   690  	}
   691  	for i := range goodEnv {
   692  		if actualEnv[i] != goodEnv[i] {
   693  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   694  		}
   695  	}
   696  }
   697  
   698  func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
   699  	if daemonPlatform == "windows" {
   700  		// Windows busybox does not have ping. Use built in ping instead.
   701  		dockerCmd(c, "run", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1")
   702  	} else {
   703  		dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
   704  	}
   705  }
   706  
   707  func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
   708  	// TODO Windows: This is Linux specific as --link is not supported and
   709  	// this will be deprecated in favour of container networking model.
   710  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   711  	dockerCmd(c, "run", "--name", "linked", "busybox", "true")
   712  
   713  	_, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true")
   714  	if err == nil {
   715  		c.Fatal("Expected error")
   716  	}
   717  }
   718  
   719  // #7851 hostname outside container shows FQDN, inside only shortname
   720  // For testing purposes it is not required to set host's hostname directly
   721  // and use "--net=host" (as the original issue submitter did), as the same
   722  // codepath is executed with "docker run -h <hostname>".  Both were manually
   723  // tested, but this testcase takes the simpler path of using "run -h .."
   724  func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
   725  	// TODO Windows: -h is not yet functional.
   726  	testRequires(c, DaemonIsLinux)
   727  	out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
   728  	if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
   729  		c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
   730  	}
   731  }
   732  
   733  func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
   734  	// Not applicable for Windows as Windows daemon does not support
   735  	// the concept of --privileged, and mknod is a Unix concept.
   736  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   737  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   738  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   739  		c.Fatalf("expected output ok received %s", actual)
   740  	}
   741  }
   742  
   743  func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
   744  	// Not applicable for Windows as Windows daemon does not support
   745  	// the concept of --privileged, and mknod is a Unix concept.
   746  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   747  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   748  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   749  		c.Fatalf("expected output ok received %s", actual)
   750  	}
   751  }
   752  
   753  func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
   754  	// Not applicable for Windows as there is no concept of --cap-drop
   755  	testRequires(c, DaemonIsLinux)
   756  	out, _, err := dockerCmdWithError("run", "--cap-drop=CHPASS", "busybox", "ls")
   757  	if err == nil {
   758  		c.Fatal(err, out)
   759  	}
   760  }
   761  
   762  func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
   763  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   764  	testRequires(c, DaemonIsLinux)
   765  	out, _, err := dockerCmdWithError("run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   766  
   767  	if err == nil {
   768  		c.Fatal(err, out)
   769  	}
   770  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   771  		c.Fatalf("expected output not ok received %s", actual)
   772  	}
   773  }
   774  
   775  func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
   776  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   777  	testRequires(c, DaemonIsLinux)
   778  	out, _, err := dockerCmdWithError("run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   779  
   780  	if err == nil {
   781  		c.Fatal(err, out)
   782  	}
   783  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   784  		c.Fatalf("expected output not ok received %s", actual)
   785  	}
   786  }
   787  
   788  func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
   789  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   790  	testRequires(c, DaemonIsLinux)
   791  	out, _, err := dockerCmdWithError("run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   792  	if err == nil {
   793  		c.Fatal(err, out)
   794  	}
   795  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   796  		c.Fatalf("expected output not ok received %s", actual)
   797  	}
   798  }
   799  
   800  func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
   801  	// Not applicable for Windows as there is no concept of --cap-drop or mknod
   802  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   803  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   804  
   805  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   806  		c.Fatalf("expected output ok received %s", actual)
   807  	}
   808  }
   809  
   810  func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
   811  	// Not applicable for Windows as there is no concept of --cap-add
   812  	testRequires(c, DaemonIsLinux)
   813  	out, _, err := dockerCmdWithError("run", "--cap-add=CHPASS", "busybox", "ls")
   814  	if err == nil {
   815  		c.Fatal(err, out)
   816  	}
   817  }
   818  
   819  func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
   820  	// Not applicable for Windows as there is no concept of --cap-add
   821  	testRequires(c, DaemonIsLinux)
   822  	out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   823  
   824  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   825  		c.Fatalf("expected output ok received %s", actual)
   826  	}
   827  }
   828  
   829  func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
   830  	// Not applicable for Windows as there is no concept of --cap-add
   831  	testRequires(c, DaemonIsLinux)
   832  	out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   833  
   834  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   835  		c.Fatalf("expected output ok received %s", actual)
   836  	}
   837  }
   838  
   839  func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
   840  	// Not applicable for Windows as there is no concept of --cap-add
   841  	testRequires(c, DaemonIsLinux)
   842  	out, _, err := dockerCmdWithError("run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   843  	if err == nil {
   844  		c.Fatal(err, out)
   845  	}
   846  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   847  		c.Fatalf("expected output not ok received %s", actual)
   848  	}
   849  }
   850  
   851  func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
   852  	// Not applicable for Windows as there is no concept of --group-add
   853  	testRequires(c, DaemonIsLinux, NativeExecDriver)
   854  	out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
   855  
   856  	groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777"
   857  	if actual := strings.Trim(out, "\r\n"); actual != groupsList {
   858  		c.Fatalf("expected output %s received %s", groupsList, actual)
   859  	}
   860  }
   861  
   862  func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
   863  	// Not applicable for Windows as there is no concept of --privileged
   864  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   865  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
   866  
   867  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   868  		c.Fatalf("expected output ok received %s", actual)
   869  	}
   870  }
   871  
   872  func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
   873  	// Not applicable for Windows as there is no concept of unprivileged
   874  	testRequires(c, DaemonIsLinux)
   875  	out, _, err := dockerCmdWithError("run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
   876  
   877  	if err == nil {
   878  		c.Fatal(err, out)
   879  	}
   880  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   881  		c.Fatalf("expected output not ok received %s", actual)
   882  	}
   883  }
   884  
   885  func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
   886  	// Not applicable for Windows as there is no concept of unprivileged
   887  	testRequires(c, DaemonIsLinux)
   888  	if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
   889  		c.Fatal("sys should not be writable in a non privileged container")
   890  	}
   891  }
   892  
   893  func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
   894  	// Not applicable for Windows as there is no concept of unprivileged
   895  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   896  	if _, code, err := dockerCmdWithError("run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
   897  		c.Fatalf("sys should be writable in privileged container")
   898  	}
   899  }
   900  
   901  func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
   902  	// Not applicable for Windows as there is no concept of unprivileged
   903  	testRequires(c, DaemonIsLinux)
   904  	if _, code, err := dockerCmdWithError("run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
   905  		c.Fatal("proc should not be writable in a non privileged container")
   906  	}
   907  }
   908  
   909  func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
   910  	// Not applicable for Windows as there is no concept of --privileged
   911  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   912  	if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 {
   913  		c.Fatalf("proc should be writable in privileged container")
   914  	}
   915  }
   916  
   917  func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
   918  	// Not applicable on Windows as /dev/ is a Unix specific concept
   919  	// TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user
   920  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   921  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
   922  	deviceLineFields := strings.Fields(out)
   923  	deviceLineFields[6] = ""
   924  	deviceLineFields[7] = ""
   925  	deviceLineFields[8] = ""
   926  	expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
   927  
   928  	if !(reflect.DeepEqual(deviceLineFields, expected)) {
   929  		c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
   930  	}
   931  }
   932  
   933  func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
   934  	// Not applicable on Windows as /dev/ is a Unix specific concept
   935  	testRequires(c, DaemonIsLinux)
   936  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
   937  	if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
   938  		c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
   939  	}
   940  }
   941  
   942  func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
   943  	// Not applicable on Windows as it does not support chroot
   944  	testRequires(c, DaemonIsLinux)
   945  	dockerCmd(c, "run", "busybox", "chroot", "/", "true")
   946  }
   947  
   948  func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
   949  	// Not applicable on Windows as Windows does not support --device
   950  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   951  	out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
   952  	if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
   953  		c.Fatalf("expected output /dev/nulo, received %s", actual)
   954  	}
   955  }
   956  
   957  func (s *DockerSuite) TestRunAddingOptionalDevicesNoSrc(c *check.C) {
   958  	// Not applicable on Windows as Windows does not support --device
   959  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   960  	out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero")
   961  	if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" {
   962  		c.Fatalf("expected output /dev/zero, received %s", actual)
   963  	}
   964  }
   965  
   966  func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *check.C) {
   967  	// Not applicable on Windows as Windows does not support --device
   968  	testRequires(c, DaemonIsLinux, NotUserNamespace)
   969  	_, _, err := dockerCmdWithError("run", "--device", "/dev/zero:ro", "busybox", "sh", "-c", "ls /dev/zero")
   970  	if err == nil {
   971  		c.Fatalf("run container with device mode ro should fail")
   972  	}
   973  }
   974  
   975  func (s *DockerSuite) TestRunModeHostname(c *check.C) {
   976  	// Not applicable on Windows as Windows does not support -h
   977  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
   978  
   979  	out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
   980  
   981  	if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
   982  		c.Fatalf("expected 'testhostname', but says: %q", actual)
   983  	}
   984  
   985  	out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
   986  
   987  	hostname, err := os.Hostname()
   988  	if err != nil {
   989  		c.Fatal(err)
   990  	}
   991  	if actual := strings.Trim(out, "\r\n"); actual != hostname {
   992  		c.Fatalf("expected %q, but says: %q", hostname, actual)
   993  	}
   994  }
   995  
   996  func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
   997  	out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
   998  	expected := "/\n"
   999  	if daemonPlatform == "windows" {
  1000  		expected = "C:" + expected
  1001  	}
  1002  	if out != expected {
  1003  		c.Fatalf("pwd returned %q (expected %s)", s, expected)
  1004  	}
  1005  }
  1006  
  1007  func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
  1008  	testRequires(c, DaemonIsLinux)
  1009  	dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
  1010  }
  1011  
  1012  func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
  1013  	// Not applicable on Windows as Windows does not support volumes
  1014  	testRequires(c, DaemonIsLinux)
  1015  	out, _, err := dockerCmdWithError("run", "-v", "/:/", "busybox", "ls", "/host")
  1016  	if err == nil {
  1017  		c.Fatal(out, err)
  1018  	}
  1019  }
  1020  
  1021  // Verify that a container gets default DNS when only localhost resolvers exist
  1022  func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
  1023  	// Not applicable on Windows as this is testing Unix specific functionality
  1024  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1025  
  1026  	// preserve original resolv.conf for restoring after test
  1027  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1028  	if os.IsNotExist(err) {
  1029  		c.Fatalf("/etc/resolv.conf does not exist")
  1030  	}
  1031  	// defer restored original conf
  1032  	defer func() {
  1033  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1034  			c.Fatal(err)
  1035  		}
  1036  	}()
  1037  
  1038  	// test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
  1039  	// 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
  1040  	// GetNameservers(), leading to a replacement of nameservers with the default set
  1041  	tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
  1042  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1043  		c.Fatal(err)
  1044  	}
  1045  
  1046  	actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  1047  	// check that the actual defaults are appended to the commented out
  1048  	// localhost resolver (which should be preserved)
  1049  	// NOTE: if we ever change the defaults from google dns, this will break
  1050  	expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1051  	if actual != expected {
  1052  		c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  1053  	}
  1054  }
  1055  
  1056  func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
  1057  	// Not applicable on Windows as Windows does not support --dns*, or
  1058  	// the Unix-specific functionality of resolv.conf.
  1059  	testRequires(c, DaemonIsLinux)
  1060  	out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "--dns-opt=ndots:9", "busybox", "cat", "/etc/resolv.conf")
  1061  
  1062  	// The client will get a warning on stderr when setting DNS to a localhost address; verify this:
  1063  	if !strings.Contains(stderr, "Localhost DNS setting") {
  1064  		c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
  1065  	}
  1066  
  1067  	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1068  	if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
  1069  		c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
  1070  	}
  1071  
  1072  	out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf")
  1073  
  1074  	actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
  1075  	if actual != "nameserver 127.0.0.1 options ndots:3" {
  1076  		c.Fatalf("expected 'nameserver 127.0.0.1 options ndots:3', but says: %q", actual)
  1077  	}
  1078  }
  1079  
  1080  func (s *DockerSuite) TestRunDnsRepeatOptions(c *check.C) {
  1081  	testRequires(c, DaemonIsLinux)
  1082  	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")
  1083  
  1084  	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
  1085  	if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
  1086  		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)
  1087  	}
  1088  }
  1089  
  1090  func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
  1091  	// Not applicable on Windows as testing Unix specific functionality
  1092  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1093  
  1094  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1095  	if os.IsNotExist(err) {
  1096  		c.Fatalf("/etc/resolv.conf does not exist")
  1097  	}
  1098  
  1099  	hostNamservers := resolvconf.GetNameservers(origResolvConf)
  1100  	hostSearch := resolvconf.GetSearchDomains(origResolvConf)
  1101  
  1102  	var out string
  1103  	out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
  1104  
  1105  	if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
  1106  		c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
  1107  	}
  1108  
  1109  	actualSearch := resolvconf.GetSearchDomains([]byte(out))
  1110  	if len(actualSearch) != len(hostSearch) {
  1111  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1112  	}
  1113  	for i := range actualSearch {
  1114  		if actualSearch[i] != hostSearch[i] {
  1115  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1116  		}
  1117  	}
  1118  
  1119  	out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
  1120  
  1121  	actualNameservers := resolvconf.GetNameservers([]byte(out))
  1122  	if len(actualNameservers) != len(hostNamservers) {
  1123  		c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
  1124  	}
  1125  	for i := range actualNameservers {
  1126  		if actualNameservers[i] != hostNamservers[i] {
  1127  			c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
  1128  		}
  1129  	}
  1130  
  1131  	if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
  1132  		c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
  1133  	}
  1134  
  1135  	// test with file
  1136  	tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  1137  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1138  		c.Fatal(err)
  1139  	}
  1140  	// put the old resolvconf back
  1141  	defer func() {
  1142  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1143  			c.Fatal(err)
  1144  		}
  1145  	}()
  1146  
  1147  	resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1148  	if os.IsNotExist(err) {
  1149  		c.Fatalf("/etc/resolv.conf does not exist")
  1150  	}
  1151  
  1152  	hostNamservers = resolvconf.GetNameservers(resolvConf)
  1153  	hostSearch = resolvconf.GetSearchDomains(resolvConf)
  1154  
  1155  	out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  1156  	if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  1157  		c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  1158  	}
  1159  
  1160  	actualSearch = resolvconf.GetSearchDomains([]byte(out))
  1161  	if len(actualSearch) != len(hostSearch) {
  1162  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1163  	}
  1164  	for i := range actualSearch {
  1165  		if actualSearch[i] != hostSearch[i] {
  1166  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1167  		}
  1168  	}
  1169  }
  1170  
  1171  // Test to see if a non-root user can resolve a DNS name and reach out to it. Also
  1172  // check if the container resolv.conf file has at least 0644 perm.
  1173  func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  1174  	// Not applicable on Windows as Windows does not support --user
  1175  	testRequires(c, SameHostDaemon, Network, DaemonIsLinux)
  1176  
  1177  	dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org")
  1178  
  1179  	cID, err := getIDByName("testperm")
  1180  	if err != nil {
  1181  		c.Fatal(err)
  1182  	}
  1183  
  1184  	fmode := (os.FileMode)(0644)
  1185  	finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  1186  	if err != nil {
  1187  		c.Fatal(err)
  1188  	}
  1189  
  1190  	if (finfo.Mode() & fmode) != fmode {
  1191  		c.Fatalf("Expected container resolv.conf mode to be at least %s, instead got %s", fmode.String(), finfo.Mode().String())
  1192  	}
  1193  }
  1194  
  1195  // Test if container resolv.conf gets updated the next time it restarts
  1196  // if host /etc/resolv.conf has changed. This only applies if the container
  1197  // uses the host's /etc/resolv.conf and does not have any dns options provided.
  1198  func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  1199  	// Not applicable on Windows as testing unix specific functionality
  1200  	testRequires(c, SameHostDaemon, DaemonIsLinux, NativeExecDriver)
  1201  
  1202  	tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n")
  1203  	tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  1204  
  1205  	//take a copy of resolv.conf for restoring after test completes
  1206  	resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  1207  	if err != nil {
  1208  		c.Fatal(err)
  1209  	}
  1210  
  1211  	// This test case is meant to test monitoring resolv.conf when it is
  1212  	// a regular file not a bind mounc. So we unmount resolv.conf and replace
  1213  	// it with a file containing the original settings.
  1214  	cmd := exec.Command("umount", "/etc/resolv.conf")
  1215  	if _, err = runCommand(cmd); err != nil {
  1216  		c.Fatal(err)
  1217  	}
  1218  
  1219  	//cleanup
  1220  	defer func() {
  1221  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1222  			c.Fatal(err)
  1223  		}
  1224  	}()
  1225  
  1226  	//1. test that a restarting container gets an updated resolv.conf
  1227  	dockerCmd(c, "run", "--name='first'", "busybox", "true")
  1228  	containerID1, err := getIDByName("first")
  1229  	if err != nil {
  1230  		c.Fatal(err)
  1231  	}
  1232  
  1233  	// replace resolv.conf with our temporary copy
  1234  	bytesResolvConf := []byte(tmpResolvConf)
  1235  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1236  		c.Fatal(err)
  1237  	}
  1238  
  1239  	// start the container again to pickup changes
  1240  	dockerCmd(c, "start", "first")
  1241  
  1242  	// check for update in container
  1243  	containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  1244  	if err != nil {
  1245  		c.Fatal(err)
  1246  	}
  1247  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1248  		c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1249  	}
  1250  
  1251  	/*	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1252  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1253  						c.Fatal(err)
  1254  								} */
  1255  	//2. test that a restarting container does not receive resolv.conf updates
  1256  	//   if it modified the container copy of the starting point resolv.conf
  1257  	dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  1258  	containerID2, err := getIDByName("second")
  1259  	if err != nil {
  1260  		c.Fatal(err)
  1261  	}
  1262  
  1263  	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1264  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1265  		c.Fatal(err)
  1266  	}
  1267  
  1268  	// start the container again
  1269  	dockerCmd(c, "start", "second")
  1270  
  1271  	// check for update in container
  1272  	containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  1273  	if err != nil {
  1274  		c.Fatal(err)
  1275  	}
  1276  
  1277  	if bytes.Equal(containerResolv, resolvConfSystem) {
  1278  		c.Fatalf("Restarting  a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem))
  1279  	}
  1280  
  1281  	//3. test that a running container's resolv.conf is not modified while running
  1282  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1283  	runningContainerID := strings.TrimSpace(out)
  1284  
  1285  	// replace resolv.conf
  1286  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1287  		c.Fatal(err)
  1288  	}
  1289  
  1290  	// check for update in container
  1291  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1292  	if err != nil {
  1293  		c.Fatal(err)
  1294  	}
  1295  
  1296  	if bytes.Equal(containerResolv, bytesResolvConf) {
  1297  		c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  1298  	}
  1299  
  1300  	//4. test that a running container's resolv.conf is updated upon restart
  1301  	//   (the above container is still running..)
  1302  	dockerCmd(c, "restart", runningContainerID)
  1303  
  1304  	// check for update in container
  1305  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1306  	if err != nil {
  1307  		c.Fatal(err)
  1308  	}
  1309  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1310  		c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  1311  	}
  1312  
  1313  	//5. test that additions of a localhost resolver are cleaned from
  1314  	//   host resolv.conf before updating container's resolv.conf copies
  1315  
  1316  	// replace resolv.conf with a localhost-only nameserver copy
  1317  	bytesResolvConf = []byte(tmpLocalhostResolvConf)
  1318  	if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1319  		c.Fatal(err)
  1320  	}
  1321  
  1322  	// start the container again to pickup changes
  1323  	dockerCmd(c, "start", "first")
  1324  
  1325  	// our first exited container ID should have been updated, but with default DNS
  1326  	// after the cleanup of resolv.conf found only a localhost nameserver:
  1327  	containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1328  	if err != nil {
  1329  		c.Fatal(err)
  1330  	}
  1331  
  1332  	expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4\n"
  1333  	if !bytes.Equal(containerResolv, []byte(expected)) {
  1334  		c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1335  	}
  1336  
  1337  	//6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1338  	//   of containers' resolv.conf.
  1339  
  1340  	// Restore the original resolv.conf
  1341  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1342  		c.Fatal(err)
  1343  	}
  1344  
  1345  	// Run the container so it picks up the old settings
  1346  	dockerCmd(c, "run", "--name='third'", "busybox", "true")
  1347  	containerID3, err := getIDByName("third")
  1348  	if err != nil {
  1349  		c.Fatal(err)
  1350  	}
  1351  
  1352  	// Create a modified resolv.conf.aside and override resolv.conf with it
  1353  	bytesResolvConf = []byte(tmpResolvConf)
  1354  	if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1355  		c.Fatal(err)
  1356  	}
  1357  
  1358  	err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1359  	if err != nil {
  1360  		c.Fatal(err)
  1361  	}
  1362  
  1363  	// start the container again to pickup changes
  1364  	dockerCmd(c, "start", "third")
  1365  
  1366  	// check for update in container
  1367  	containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1368  	if err != nil {
  1369  		c.Fatal(err)
  1370  	}
  1371  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1372  		c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1373  	}
  1374  
  1375  	//cleanup, restore original resolv.conf happens in defer func()
  1376  }
  1377  
  1378  func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1379  	// Not applicable on Windows as it does not support --add-host
  1380  	testRequires(c, DaemonIsLinux)
  1381  	out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1382  
  1383  	actual := strings.Trim(out, "\r\n")
  1384  	if actual != "86.75.30.9\textra" {
  1385  		c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1386  	}
  1387  }
  1388  
  1389  // Regression test for #6983
  1390  func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1391  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  1392  	if exitCode != 0 {
  1393  		c.Fatalf("Container should have exited with error code 0")
  1394  	}
  1395  }
  1396  
  1397  // Regression test for #6983
  1398  func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1399  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1400  	if exitCode != 0 {
  1401  		c.Fatalf("Container should have exited with error code 0")
  1402  	}
  1403  }
  1404  
  1405  // Regression test for #6983
  1406  func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1407  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1408  	if exitCode != 0 {
  1409  		c.Fatalf("Container should have exited with error code 0")
  1410  	}
  1411  }
  1412  
  1413  // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1414  // but using --attach instead of -a to make sure we read the flag correctly
  1415  func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1416  	cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1417  	_, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1418  	if err == nil {
  1419  		c.Fatal("Container should have exited with error code different than 0")
  1420  	} else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1421  		c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1422  	}
  1423  }
  1424  
  1425  func (s *DockerSuite) TestRunState(c *check.C) {
  1426  	// TODO Windows: This needs some rework as Windows busybox does not support top
  1427  	testRequires(c, DaemonIsLinux)
  1428  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1429  
  1430  	id := strings.TrimSpace(out)
  1431  	state, err := inspectField(id, "State.Running")
  1432  	c.Assert(err, check.IsNil)
  1433  	if state != "true" {
  1434  		c.Fatal("Container state is 'not running'")
  1435  	}
  1436  	pid1, err := inspectField(id, "State.Pid")
  1437  	c.Assert(err, check.IsNil)
  1438  	if pid1 == "0" {
  1439  		c.Fatal("Container state Pid 0")
  1440  	}
  1441  
  1442  	dockerCmd(c, "stop", id)
  1443  	state, err = inspectField(id, "State.Running")
  1444  	c.Assert(err, check.IsNil)
  1445  	if state != "false" {
  1446  		c.Fatal("Container state is 'running'")
  1447  	}
  1448  	pid2, err := inspectField(id, "State.Pid")
  1449  	c.Assert(err, check.IsNil)
  1450  	if pid2 == pid1 {
  1451  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1452  	}
  1453  
  1454  	dockerCmd(c, "start", id)
  1455  	state, err = inspectField(id, "State.Running")
  1456  	c.Assert(err, check.IsNil)
  1457  	if state != "true" {
  1458  		c.Fatal("Container state is 'not running'")
  1459  	}
  1460  	pid3, err := inspectField(id, "State.Pid")
  1461  	c.Assert(err, check.IsNil)
  1462  	if pid3 == pid1 {
  1463  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1464  	}
  1465  }
  1466  
  1467  // Test for #1737
  1468  func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1469  	// Not applicable on Windows as it does not support volumes, uid or gid
  1470  	testRequires(c, DaemonIsLinux)
  1471  	name := "testrunvolumesuidgid"
  1472  	_, err := buildImage(name,
  1473  		`FROM busybox
  1474  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1475  		RUN echo 'dockerio:x:1001:' >> /etc/group
  1476  		RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1477  		true)
  1478  	if err != nil {
  1479  		c.Fatal(err)
  1480  	}
  1481  
  1482  	// Test that the uid and gid is copied from the image to the volume
  1483  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1484  	out = strings.TrimSpace(out)
  1485  	if out != "dockerio:dockerio" {
  1486  		c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1487  	}
  1488  }
  1489  
  1490  // Test for #1582
  1491  func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1492  	// Not applicable on Windows as it does not support volumes
  1493  	testRequires(c, DaemonIsLinux)
  1494  	name := "testruncopyvolumecontent"
  1495  	_, err := buildImage(name,
  1496  		`FROM busybox
  1497  		RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1498  		true)
  1499  	if err != nil {
  1500  		c.Fatal(err)
  1501  	}
  1502  
  1503  	// Test that the content is copied from the image to the volume
  1504  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1505  	if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1506  		c.Fatal("Container failed to transfer content to volume")
  1507  	}
  1508  }
  1509  
  1510  func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1511  	name := "testrunmdcleanuponentrypoint"
  1512  	if _, err := buildImage(name,
  1513  		`FROM busybox
  1514  		ENTRYPOINT ["echo"]
  1515  		CMD ["testingpoint"]`,
  1516  		true); err != nil {
  1517  		c.Fatal(err)
  1518  	}
  1519  
  1520  	out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1521  	if exit != 0 {
  1522  		c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1523  	}
  1524  	out = strings.TrimSpace(out)
  1525  	expected := "root"
  1526  	if daemonPlatform == "windows" {
  1527  		expected = `nt authority\system`
  1528  	}
  1529  	if out != expected {
  1530  		c.Fatalf("Expected output %s, got %q", expected, out)
  1531  	}
  1532  }
  1533  
  1534  // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1535  func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1536  	existingFile := "/bin/cat"
  1537  	expected := "Cannot mkdir: /bin/cat is not a directory"
  1538  	if daemonPlatform == "windows" {
  1539  		existingFile = `\windows\system32\ntdll.dll`
  1540  		expected = "The directory name is invalid"
  1541  	}
  1542  
  1543  	out, exit, err := dockerCmdWithError("run", "-w", existingFile, "busybox")
  1544  	if !(err != nil && exit == 1 && strings.Contains(out, expected)) {
  1545  		c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1546  	}
  1547  }
  1548  
  1549  func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1550  	name := "testrunexitonstdinclose"
  1551  
  1552  	meow := "/bin/cat"
  1553  	delay := 1
  1554  	if daemonPlatform == "windows" {
  1555  		meow = "cat"
  1556  		delay = 5
  1557  	}
  1558  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow)
  1559  
  1560  	stdin, err := runCmd.StdinPipe()
  1561  	if err != nil {
  1562  		c.Fatal(err)
  1563  	}
  1564  	stdout, err := runCmd.StdoutPipe()
  1565  	if err != nil {
  1566  		c.Fatal(err)
  1567  	}
  1568  
  1569  	if err := runCmd.Start(); err != nil {
  1570  		c.Fatal(err)
  1571  	}
  1572  	if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1573  		c.Fatal(err)
  1574  	}
  1575  
  1576  	r := bufio.NewReader(stdout)
  1577  	line, err := r.ReadString('\n')
  1578  	if err != nil {
  1579  		c.Fatal(err)
  1580  	}
  1581  	line = strings.TrimSpace(line)
  1582  	if line != "hello" {
  1583  		c.Fatalf("Output should be 'hello', got '%q'", line)
  1584  	}
  1585  	if err := stdin.Close(); err != nil {
  1586  		c.Fatal(err)
  1587  	}
  1588  	finish := make(chan error)
  1589  	go func() {
  1590  		finish <- runCmd.Wait()
  1591  		close(finish)
  1592  	}()
  1593  	select {
  1594  	case err := <-finish:
  1595  		c.Assert(err, check.IsNil)
  1596  	case <-time.After(time.Duration(delay) * time.Second):
  1597  		c.Fatal("docker run failed to exit on stdin close")
  1598  	}
  1599  	state, err := inspectField(name, "State.Running")
  1600  	c.Assert(err, check.IsNil)
  1601  
  1602  	if state != "false" {
  1603  		c.Fatal("Container must be stopped after stdin closing")
  1604  	}
  1605  }
  1606  
  1607  // Test for #2267
  1608  func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1609  	// Cannot run on Windows as Windows does not support diff.
  1610  	testRequires(c, DaemonIsLinux)
  1611  	name := "writehosts"
  1612  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1613  	if !strings.Contains(out, "test2267") {
  1614  		c.Fatal("/etc/hosts should contain 'test2267'")
  1615  	}
  1616  
  1617  	out, _ = dockerCmd(c, "diff", name)
  1618  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1619  		c.Fatal("diff should be empty")
  1620  	}
  1621  }
  1622  
  1623  func eqToBaseDiff(out string, c *check.C) bool {
  1624  	out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
  1625  	cID := strings.TrimSpace(out1)
  1626  
  1627  	baseDiff, _ := dockerCmd(c, "diff", cID)
  1628  	baseArr := strings.Split(baseDiff, "\n")
  1629  	sort.Strings(baseArr)
  1630  	outArr := strings.Split(out, "\n")
  1631  	sort.Strings(outArr)
  1632  	return sliceEq(baseArr, outArr)
  1633  }
  1634  
  1635  func sliceEq(a, b []string) bool {
  1636  	if len(a) != len(b) {
  1637  		return false
  1638  	}
  1639  
  1640  	for i := range a {
  1641  		if a[i] != b[i] {
  1642  			return false
  1643  		}
  1644  	}
  1645  
  1646  	return true
  1647  }
  1648  
  1649  // Test for #2267
  1650  func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1651  	// Cannot run on Windows as Windows does not support diff.
  1652  	testRequires(c, DaemonIsLinux)
  1653  	name := "writehostname"
  1654  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1655  	if !strings.Contains(out, "test2267") {
  1656  		c.Fatal("/etc/hostname should contain 'test2267'")
  1657  	}
  1658  
  1659  	out, _ = dockerCmd(c, "diff", name)
  1660  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1661  		c.Fatal("diff should be empty")
  1662  	}
  1663  }
  1664  
  1665  // Test for #2267
  1666  func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1667  	// Cannot run on Windows as Windows does not support diff.
  1668  	testRequires(c, DaemonIsLinux)
  1669  	name := "writeresolv"
  1670  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1671  	if !strings.Contains(out, "test2267") {
  1672  		c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1673  	}
  1674  
  1675  	out, _ = dockerCmd(c, "diff", name)
  1676  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1677  		c.Fatal("diff should be empty")
  1678  	}
  1679  }
  1680  
  1681  func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1682  	// Cannot run on Windows as Windows does not support --device
  1683  	testRequires(c, DaemonIsLinux)
  1684  	name := "baddevice"
  1685  	out, _, err := dockerCmdWithError("run", "--name", name, "--device", "/etc", "busybox", "true")
  1686  
  1687  	if err == nil {
  1688  		c.Fatal("Run should fail with bad device")
  1689  	}
  1690  	expected := `"/etc": not a device node`
  1691  	if !strings.Contains(out, expected) {
  1692  		c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1693  	}
  1694  }
  1695  
  1696  func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1697  	name := "entrypoint"
  1698  
  1699  	// Note Windows does not have an echo.exe built in.
  1700  	var out, expected string
  1701  	if daemonPlatform == "windows" {
  1702  		out, _ = dockerCmd(c, "run", "--name", name, "--entrypoint", "cmd /s /c echo", "busybox", "foobar")
  1703  		expected = "foobar\r\n"
  1704  	} else {
  1705  		out, _ = dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1706  		expected = "foobar"
  1707  	}
  1708  
  1709  	if out != expected {
  1710  		c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1711  	}
  1712  }
  1713  
  1714  func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1715  	// /tmp gets permission denied
  1716  	testRequires(c, NotUserNamespace)
  1717  	// Cannot run on Windows as Windows does not support volumes
  1718  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  1719  
  1720  	tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1721  	if err != nil {
  1722  		c.Fatal(err)
  1723  	}
  1724  
  1725  	defer os.RemoveAll(tmpDir)
  1726  	writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1727  
  1728  	// Test reading from a read-only bind mount
  1729  	out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1730  	if !strings.Contains(out, "touch-me") {
  1731  		c.Fatal("Container failed to read from bind mount")
  1732  	}
  1733  
  1734  	// test writing to bind mount
  1735  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1736  
  1737  	readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1738  
  1739  	// test mounting to an illegal destination directory
  1740  	_, _, err = dockerCmdWithError("run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1741  	if err == nil {
  1742  		c.Fatal("Container bind mounted illegal directory")
  1743  	}
  1744  
  1745  	// test mount a file
  1746  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1747  	content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1748  	expected := "yotta"
  1749  	if content != expected {
  1750  		c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1751  	}
  1752  }
  1753  
  1754  // Ensure that CIDFile gets deleted if it's empty
  1755  // Perform this test by making `docker run` fail
  1756  func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1757  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1758  	if err != nil {
  1759  		c.Fatal(err)
  1760  	}
  1761  	defer os.RemoveAll(tmpDir)
  1762  	tmpCidFile := path.Join(tmpDir, "cid")
  1763  
  1764  	image := "emptyfs"
  1765  	if daemonPlatform == "windows" {
  1766  		// Windows can't support an emptyfs image. Just use the regular Windows image
  1767  		image = WindowsBaseImage
  1768  	}
  1769  	out, _, err := dockerCmdWithError("run", "--cidfile", tmpCidFile, image)
  1770  	if err == nil {
  1771  		c.Fatalf("Run without command must fail. out=%s", out)
  1772  	} else if !strings.Contains(out, "No command specified") {
  1773  		c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1774  	}
  1775  
  1776  	if _, err := os.Stat(tmpCidFile); err == nil {
  1777  		c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1778  	}
  1779  }
  1780  
  1781  // #2098 - Docker cidFiles only contain short version of the containerId
  1782  //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1783  // TestRunCidFile tests that run --cidfile returns the longid
  1784  func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1785  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1786  	if err != nil {
  1787  		c.Fatal(err)
  1788  	}
  1789  	tmpCidFile := path.Join(tmpDir, "cid")
  1790  	defer os.RemoveAll(tmpDir)
  1791  
  1792  	out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1793  
  1794  	id := strings.TrimSpace(out)
  1795  	buffer, err := ioutil.ReadFile(tmpCidFile)
  1796  	if err != nil {
  1797  		c.Fatal(err)
  1798  	}
  1799  	cid := string(buffer)
  1800  	if len(cid) != 64 {
  1801  		c.Fatalf("--cidfile should be a long id, not %q", id)
  1802  	}
  1803  	if cid != id {
  1804  		c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1805  	}
  1806  }
  1807  
  1808  func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1809  	// TODO Windows. Test modified to be theoretically Windows compatible,
  1810  	// but the version of busybox being used on Windows doesn't handle
  1811  	// sh -c ipconfig -all (or /all). It ignores the *all bit. This could
  1812  	// be a bug in busybox.
  1813  	testRequires(c, DaemonIsLinux)
  1814  	mac := "12:34:56:78:9a:bc"
  1815  
  1816  	var out string
  1817  	if daemonPlatform == "windows" {
  1818  		out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
  1819  	} else {
  1820  		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}'")
  1821  	}
  1822  
  1823  	actualMac := strings.TrimSpace(out)
  1824  	if actualMac != mac {
  1825  		c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1826  	}
  1827  }
  1828  
  1829  func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1830  	// TODO Windows. Network settings are not propagated back to inspect.
  1831  	testRequires(c, DaemonIsLinux)
  1832  	mac := "12:34:56:78:9a:bc"
  1833  	out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1834  
  1835  	id := strings.TrimSpace(out)
  1836  	inspectedMac, err := inspectField(id, "NetworkSettings.Networks.bridge.MacAddress")
  1837  	c.Assert(err, check.IsNil)
  1838  	if inspectedMac != mac {
  1839  		c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1840  	}
  1841  }
  1842  
  1843  // test docker run use a invalid mac address
  1844  func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1845  	out, _, err := dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1846  	//use a invalid mac address should with a error out
  1847  	if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1848  		c.Fatalf("run with an invalid --mac-address should with error out")
  1849  	}
  1850  }
  1851  
  1852  func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1853  	// TODO Windows. Network settings are not propagated back to inspect.
  1854  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1855  
  1856  	out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1857  
  1858  	id := strings.TrimSpace(out)
  1859  	ip, err := inspectField(id, "NetworkSettings.Networks.bridge.IPAddress")
  1860  	c.Assert(err, check.IsNil)
  1861  	iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1862  		"!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1863  	out, _, err = runCommandWithOutput(iptCmd)
  1864  	if err != nil {
  1865  		c.Fatal(err, out)
  1866  	}
  1867  	if err := deleteContainer(id); err != nil {
  1868  		c.Fatal(err)
  1869  	}
  1870  
  1871  	dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1872  }
  1873  
  1874  func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1875  	// TODO Windows. The duplicate NAT message returned by Windows will be
  1876  	// changing as is currently completely undecipherable. Does need modifying
  1877  	// to run sh rather than top though as top isn't in Windows busybox.
  1878  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1879  
  1880  	port := "1234"
  1881  	dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1882  
  1883  	out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top")
  1884  	if err == nil {
  1885  		c.Fatalf("Binding on used port must fail")
  1886  	}
  1887  	if !strings.Contains(out, "port is already allocated") {
  1888  		c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1889  	}
  1890  }
  1891  
  1892  // https://github.com/docker/docker/issues/12148
  1893  func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  1894  	// TODO Windows. -P is not yet supported
  1895  	testRequires(c, DaemonIsLinux)
  1896  	// allocate a dynamic port to get the most recent
  1897  	out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  1898  
  1899  	id := strings.TrimSpace(out)
  1900  	out, _ = dockerCmd(c, "port", id, "80")
  1901  
  1902  	strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  1903  	port, err := strconv.ParseInt(strPort, 10, 64)
  1904  	if err != nil {
  1905  		c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  1906  	}
  1907  
  1908  	// allocate a static port and a dynamic port together, with static port
  1909  	// takes the next recent port in dynamic port range.
  1910  	dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  1911  }
  1912  
  1913  // Regression test for #7792
  1914  func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1915  	// tmp gets permission denied
  1916  	testRequires(c, NotUserNamespace)
  1917  	// Not applicable on Windows as Windows does not support volumes
  1918  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1919  
  1920  	tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1921  	if err != nil {
  1922  		c.Fatal(err)
  1923  	}
  1924  	defer os.RemoveAll(tmpDir)
  1925  
  1926  	tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1927  	if err != nil {
  1928  		c.Fatal(err)
  1929  	}
  1930  	defer os.RemoveAll(tmpDir2)
  1931  
  1932  	// Create a temporary tmpfs mounc.
  1933  	fooDir := filepath.Join(tmpDir, "foo")
  1934  	if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1935  		c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1936  	}
  1937  
  1938  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1939  		c.Fatal(err)
  1940  	}
  1941  
  1942  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1943  		c.Fatal(err)
  1944  	}
  1945  
  1946  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1947  		c.Fatal(err)
  1948  	}
  1949  
  1950  	dockerCmd(c, "run",
  1951  		"-v", fmt.Sprintf("%s:/tmp", tmpDir),
  1952  		"-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
  1953  		"-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
  1954  		"-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
  1955  		"busybox:latest", "sh", "-c",
  1956  		"ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1957  }
  1958  
  1959  // Regression test for https://github.com/docker/docker/issues/8259
  1960  func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1961  	// /tmp gets permission denied
  1962  	testRequires(c, NotUserNamespace)
  1963  	// Not applicable on Windows as Windows does not support volumes
  1964  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  1965  
  1966  	tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1967  	if err != nil {
  1968  		c.Fatal(err)
  1969  	}
  1970  	defer os.RemoveAll(tmpDir)
  1971  
  1972  	linkPath := os.TempDir() + "/testlink2"
  1973  	if err := os.Symlink(tmpDir, linkPath); err != nil {
  1974  		c.Fatal(err)
  1975  	}
  1976  	defer os.RemoveAll(linkPath)
  1977  
  1978  	// Create first container
  1979  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1980  
  1981  	// Create second container with same symlinked path
  1982  	// This will fail if the referenced issue is hit with a "Volume exists" error
  1983  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1984  }
  1985  
  1986  //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1987  func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1988  	// Not applicable on Windows as Windows does not support volumes
  1989  	testRequires(c, DaemonIsLinux)
  1990  	out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1991  	if !strings.Contains(out, "nameserver 127.0.0.1") {
  1992  		c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1993  	}
  1994  
  1995  	out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1996  	if !strings.Contains(out, "test123") {
  1997  		c.Fatal("/etc volume mount hides /etc/hostname")
  1998  	}
  1999  
  2000  	out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  2001  	out = strings.Replace(out, "\n", " ", -1)
  2002  	if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  2003  		c.Fatal("/etc volume mount hides /etc/hosts")
  2004  	}
  2005  }
  2006  
  2007  func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  2008  	// Not applicable on Windows as Windows does not support volumes
  2009  	testRequires(c, DaemonIsLinux)
  2010  	if _, err := buildImage("dataimage",
  2011  		`FROM busybox
  2012  		RUN mkdir -p /foo
  2013  		RUN touch /foo/bar`,
  2014  		true); err != nil {
  2015  		c.Fatal(err)
  2016  	}
  2017  
  2018  	dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  2019  
  2020  	if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2021  		c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  2022  	}
  2023  
  2024  	tmpDir := randomTmpDirPath("docker_test_bind_mount_copy_data", daemonPlatform)
  2025  	if out, _, err := dockerCmdWithError("run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  2026  		c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  2027  	}
  2028  }
  2029  
  2030  func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  2031  	// just run with unknown image
  2032  	cmd := exec.Command(dockerBinary, "run", "asdfsg")
  2033  	stdout := bytes.NewBuffer(nil)
  2034  	cmd.Stdout = stdout
  2035  	if err := cmd.Run(); err == nil {
  2036  		c.Fatal("Run with unknown image should fail")
  2037  	}
  2038  	if stdout.Len() != 0 {
  2039  		c.Fatalf("Stdout contains output from pull: %s", stdout)
  2040  	}
  2041  }
  2042  
  2043  func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  2044  	// Not applicable on Windows as Windows does not support volumes
  2045  	testRequires(c, DaemonIsLinux)
  2046  	if _, err := buildImage("run_volumes_clean_paths",
  2047  		`FROM busybox
  2048  		VOLUME /foo/`,
  2049  		true); err != nil {
  2050  		c.Fatal(err)
  2051  	}
  2052  
  2053  	dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  2054  
  2055  	out, err := inspectMountSourceField("dark_helmet", "/foo/")
  2056  	if err != errMountNotFound {
  2057  		c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  2058  	}
  2059  
  2060  	out, err = inspectMountSourceField("dark_helmet", "/foo")
  2061  	c.Assert(err, check.IsNil)
  2062  	if !strings.Contains(out, volumesConfigPath) {
  2063  		c.Fatalf("Volume was not defined for /foo\n%q", out)
  2064  	}
  2065  
  2066  	out, err = inspectMountSourceField("dark_helmet", "/bar/")
  2067  	if err != errMountNotFound {
  2068  		c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  2069  	}
  2070  
  2071  	out, err = inspectMountSourceField("dark_helmet", "/bar")
  2072  	c.Assert(err, check.IsNil)
  2073  	if !strings.Contains(out, volumesConfigPath) {
  2074  		c.Fatalf("Volume was not defined for /bar\n%q", out)
  2075  	}
  2076  }
  2077  
  2078  // Regression test for #3631
  2079  func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  2080  	// TODO Windows: This should be able to run on Windows if can find an
  2081  	// alternate to /dev/zero and /dev/stdout.
  2082  	testRequires(c, DaemonIsLinux)
  2083  	cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  2084  
  2085  	stdout, err := cont.StdoutPipe()
  2086  	if err != nil {
  2087  		c.Fatal(err)
  2088  	}
  2089  
  2090  	if err := cont.Start(); err != nil {
  2091  		c.Fatal(err)
  2092  	}
  2093  	n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  2094  	if err != nil {
  2095  		c.Fatal(err)
  2096  	}
  2097  
  2098  	expected := 2 * 1024 * 2000
  2099  	if n != expected {
  2100  		c.Fatalf("Expected %d, got %d", expected, n)
  2101  	}
  2102  }
  2103  
  2104  func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  2105  	// TODO Windows: -P is not currently supported. Also network
  2106  	// settings are not propagated back.
  2107  	testRequires(c, DaemonIsLinux)
  2108  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  2109  
  2110  	id := strings.TrimSpace(out)
  2111  	portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2112  	c.Assert(err, check.IsNil)
  2113  	var ports nat.PortMap
  2114  	if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  2115  		c.Fatal(err)
  2116  	}
  2117  	for port, binding := range ports {
  2118  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2119  		if portnum < 3000 || portnum > 3003 {
  2120  			c.Fatalf("Port %d is out of range ", portnum)
  2121  		}
  2122  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2123  			c.Fatalf("Port is not mapped for the port %s", port)
  2124  		}
  2125  	}
  2126  }
  2127  
  2128  // test docker run expose a invalid port
  2129  func (s *DockerSuite) TestRunExposePort(c *check.C) {
  2130  	out, _, err := dockerCmdWithError("run", "--expose", "80000", "busybox")
  2131  	//expose a invalid port should with a error out
  2132  	if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  2133  		c.Fatalf("run --expose a invalid port should with error out")
  2134  	}
  2135  }
  2136  
  2137  func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  2138  	if daemonPlatform != "windows" {
  2139  		testRequires(c, NativeExecDriver)
  2140  	}
  2141  	out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  2142  
  2143  	cID := strings.TrimSpace(out)
  2144  	_, _, err := dockerCmdWithError("start", cID)
  2145  
  2146  	// Windows and Linux are different here by architectural design. Linux will
  2147  	// fail to start the container, so an error is expected. Windows will
  2148  	// successfully start the container, and once started attempt to execute
  2149  	// the command which will fail.
  2150  	if daemonPlatform == "windows" {
  2151  		// Wait for it to exit.
  2152  		waitExited(cID, 30*time.Second)
  2153  		c.Assert(err, check.IsNil)
  2154  	} else {
  2155  		c.Assert(err, check.NotNil)
  2156  	}
  2157  
  2158  	rc, err := inspectField(cID, "State.ExitCode")
  2159  	c.Assert(err, check.IsNil)
  2160  	if rc == "0" {
  2161  		c.Fatalf("ExitCode(%v) cannot be 0", rc)
  2162  	}
  2163  }
  2164  
  2165  func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  2166  	// Not applicable on Windows as uses Unix-specific capabilities
  2167  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2168  
  2169  	hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  2170  	if err != nil {
  2171  		c.Fatal(err)
  2172  	}
  2173  
  2174  	out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  2175  	out = strings.Trim(out, "\n")
  2176  	if hostIpc != out {
  2177  		c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  2178  	}
  2179  
  2180  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  2181  	out = strings.Trim(out, "\n")
  2182  	if hostIpc == out {
  2183  		c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  2184  	}
  2185  }
  2186  
  2187  func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  2188  	// Not applicable on Windows as uses Unix-specific capabilities
  2189  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2190  
  2191  	out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && top")
  2192  
  2193  	id := strings.TrimSpace(out)
  2194  	state, err := inspectField(id, "State.Running")
  2195  	c.Assert(err, check.IsNil)
  2196  	if state != "true" {
  2197  		c.Fatal("Container state is 'not running'")
  2198  	}
  2199  	pid1, err := inspectField(id, "State.Pid")
  2200  	c.Assert(err, check.IsNil)
  2201  
  2202  	parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  2203  	if err != nil {
  2204  		c.Fatal(err)
  2205  	}
  2206  
  2207  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  2208  	out = strings.Trim(out, "\n")
  2209  	if parentContainerIpc != out {
  2210  		c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  2211  	}
  2212  
  2213  	catOutput, _ := dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "cat", "/dev/shm/test")
  2214  	if catOutput != "test" {
  2215  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", catOutput)
  2216  	}
  2217  }
  2218  
  2219  func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  2220  	// Not applicable on Windows as uses Unix-specific capabilities
  2221  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2222  	out, _, err := dockerCmdWithError("run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  2223  	if !strings.Contains(out, "abcd1234") || err == nil {
  2224  		c.Fatalf("run IPC from a non exists container should with correct error out")
  2225  	}
  2226  }
  2227  
  2228  func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  2229  	// Not applicable on Windows as uses Unix-specific capabilities
  2230  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2231  
  2232  	out, _ := dockerCmd(c, "create", "busybox")
  2233  
  2234  	id := strings.TrimSpace(out)
  2235  	out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  2236  	if err == nil {
  2237  		c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  2238  	}
  2239  }
  2240  
  2241  func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) {
  2242  	// Not applicable on Windows as uses Unix-specific capabilities
  2243  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2244  
  2245  	dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && top")
  2246  	volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm")
  2247  	c.Assert(err, check.IsNil)
  2248  	if volPath != "/dev/shm" {
  2249  		c.Fatalf("volumePath should have been /dev/shm, was %s", volPath)
  2250  	}
  2251  
  2252  	out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test")
  2253  	if out != "test" {
  2254  		c.Fatalf("Output of /dev/shm/test expected test but found: %s", out)
  2255  	}
  2256  }
  2257  
  2258  func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  2259  	// Not applicable on Windows as uses Unix-specific capabilities
  2260  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2261  
  2262  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2263  	id := strings.TrimSpace(out)
  2264  	c.Assert(waitRun(id), check.IsNil)
  2265  	pid1, err := inspectField(id, "State.Pid")
  2266  	c.Assert(err, check.IsNil)
  2267  
  2268  	parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2269  	if err != nil {
  2270  		c.Fatal(err)
  2271  	}
  2272  
  2273  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2274  	out = strings.Trim(out, "\n")
  2275  	if parentContainerNet != out {
  2276  		c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  2277  	}
  2278  }
  2279  
  2280  func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  2281  	// Not applicable on Windows as uses Unix-specific capabilities
  2282  	testRequires(c, NativeExecDriver, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2283  
  2284  	hostPid, err := os.Readlink("/proc/1/ns/pid")
  2285  	if err != nil {
  2286  		c.Fatal(err)
  2287  	}
  2288  
  2289  	out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2290  	out = strings.Trim(out, "\n")
  2291  	if hostPid != out {
  2292  		c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  2293  	}
  2294  
  2295  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2296  	out = strings.Trim(out, "\n")
  2297  	if hostPid == out {
  2298  		c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  2299  	}
  2300  }
  2301  
  2302  func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  2303  	// Not applicable on Windows as uses Unix-specific capabilities
  2304  	testRequires(c, NativeExecDriver, SameHostDaemon, DaemonIsLinux)
  2305  
  2306  	hostUTS, err := os.Readlink("/proc/1/ns/uts")
  2307  	if err != nil {
  2308  		c.Fatal(err)
  2309  	}
  2310  
  2311  	out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  2312  	out = strings.Trim(out, "\n")
  2313  	if hostUTS != out {
  2314  		c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  2315  	}
  2316  
  2317  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  2318  	out = strings.Trim(out, "\n")
  2319  	if hostUTS == out {
  2320  		c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  2321  	}
  2322  }
  2323  
  2324  func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  2325  	if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 {
  2326  		c.Fatalf("Should have worked: %v:\n%v", err, out)
  2327  	}
  2328  
  2329  	// Regardless of whether we specify true or false we need to
  2330  	// test to make sure tls is turned on if --tlsverify is specified at all
  2331  	out, code, err := dockerCmdWithError("--tlsverify=false", "ps")
  2332  	if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  2333  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2334  	}
  2335  
  2336  	out, code, err = dockerCmdWithError("--tlsverify=true", "ps")
  2337  	if err == nil || code == 0 || !strings.Contains(out, "cert") {
  2338  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2339  	}
  2340  }
  2341  
  2342  func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  2343  	// TODO Windows. Once moved to libnetwork/CNM, this may be able to be
  2344  	// re-instated.
  2345  	testRequires(c, DaemonIsLinux)
  2346  	// first find allocator current position
  2347  	out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2348  
  2349  	id := strings.TrimSpace(out)
  2350  	out, _ = dockerCmd(c, "port", id)
  2351  
  2352  	out = strings.TrimSpace(out)
  2353  	if out == "" {
  2354  		c.Fatal("docker port command output is empty")
  2355  	}
  2356  	out = strings.Split(out, ":")[1]
  2357  	lastPort, err := strconv.Atoi(out)
  2358  	if err != nil {
  2359  		c.Fatal(err)
  2360  	}
  2361  	port := lastPort + 1
  2362  	l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2363  	if err != nil {
  2364  		c.Fatal(err)
  2365  	}
  2366  	defer l.Close()
  2367  
  2368  	out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2369  
  2370  	id = strings.TrimSpace(out)
  2371  	dockerCmd(c, "port", id)
  2372  }
  2373  
  2374  func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  2375  	errChan := make(chan error)
  2376  	go func() {
  2377  		defer close(errChan)
  2378  
  2379  		cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2380  		if _, err := cmd.StdinPipe(); err != nil {
  2381  			errChan <- err
  2382  			return
  2383  		}
  2384  
  2385  		expected := "cannot enable tty mode"
  2386  		if out, _, err := runCommandWithOutput(cmd); err == nil {
  2387  			errChan <- fmt.Errorf("run should have failed")
  2388  			return
  2389  		} else if !strings.Contains(out, expected) {
  2390  			errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2391  			return
  2392  		}
  2393  	}()
  2394  
  2395  	select {
  2396  	case err := <-errChan:
  2397  		c.Assert(err, check.IsNil)
  2398  	case <-time.After(6 * time.Second):
  2399  		c.Fatal("container is running but should have failed")
  2400  	}
  2401  }
  2402  
  2403  func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  2404  	addr := "00:16:3E:08:00:50"
  2405  	cmd := "ifconfig"
  2406  	image := "busybox"
  2407  	expected := addr
  2408  
  2409  	if daemonPlatform == "windows" {
  2410  		cmd = "ipconfig /all"
  2411  		image = WindowsBaseImage
  2412  		expected = strings.Replace(addr, ":", "-", -1)
  2413  
  2414  	}
  2415  
  2416  	if out, _ := dockerCmd(c, "run", "--mac-address", addr, image, cmd); !strings.Contains(out, expected) {
  2417  		c.Fatalf("Output should have contained %q: %s", expected, out)
  2418  	}
  2419  }
  2420  
  2421  func (s *DockerSuite) TestRunNetHost(c *check.C) {
  2422  	// Not applicable on Windows as uses Unix-specific capabilities
  2423  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2424  
  2425  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2426  	if err != nil {
  2427  		c.Fatal(err)
  2428  	}
  2429  
  2430  	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2431  	out = strings.Trim(out, "\n")
  2432  	if hostNet != out {
  2433  		c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  2434  	}
  2435  
  2436  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  2437  	out = strings.Trim(out, "\n")
  2438  	if hostNet == out {
  2439  		c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  2440  	}
  2441  }
  2442  
  2443  func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  2444  	// TODO Windows. As Windows networking evolves and converges towards
  2445  	// CNM, this test may be possible to enable on Windows.
  2446  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2447  
  2448  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2449  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2450  }
  2451  
  2452  func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  2453  	// Not applicable on Windows as uses Unix-specific capabilities
  2454  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2455  
  2456  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2457  	if err != nil {
  2458  		c.Fatal(err)
  2459  	}
  2460  
  2461  	dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2462  
  2463  	out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2464  	out = strings.Trim(out, "\n")
  2465  	if hostNet != out {
  2466  		c.Fatalf("Container should have host network namespace")
  2467  	}
  2468  }
  2469  
  2470  func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  2471  	// TODO Windows. This may be possible to enable in the future. However,
  2472  	// Windows does not currently support --expose, or populate the network
  2473  	// settings seen through inspect.
  2474  	testRequires(c, DaemonIsLinux)
  2475  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2476  
  2477  	id := strings.TrimSpace(out)
  2478  	portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2479  	c.Assert(err, check.IsNil)
  2480  
  2481  	var ports nat.PortMap
  2482  	err = unmarshalJSON([]byte(portstr), &ports)
  2483  	for port, binding := range ports {
  2484  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2485  		if portnum < 3000 || portnum > 3003 {
  2486  			c.Fatalf("Port %d is out of range ", portnum)
  2487  		}
  2488  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2489  			c.Fatal("Port is not mapped for the port "+port, out)
  2490  		}
  2491  	}
  2492  }
  2493  
  2494  func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  2495  	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "sleep", "30")
  2496  	out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
  2497  	c.Assert(err, check.IsNil)
  2498  	if out != "no" {
  2499  		c.Fatalf("Set default restart policy failed")
  2500  	}
  2501  }
  2502  
  2503  func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  2504  	out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  2505  	timeout := 10 * time.Second
  2506  	if daemonPlatform == "windows" {
  2507  		timeout = 45 * time.Second
  2508  	}
  2509  
  2510  	id := strings.TrimSpace(string(out))
  2511  	if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil {
  2512  		c.Fatal(err)
  2513  	}
  2514  
  2515  	count, err := inspectField(id, "RestartCount")
  2516  	c.Assert(err, check.IsNil)
  2517  	if count != "3" {
  2518  		c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2519  	}
  2520  
  2521  	MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2522  	c.Assert(err, check.IsNil)
  2523  	if MaximumRetryCount != "3" {
  2524  		c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2525  	}
  2526  }
  2527  
  2528  func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  2529  	dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  2530  }
  2531  
  2532  func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  2533  	// Not applicable on Windows which does not support --read-only
  2534  	testRequires(c, NativeExecDriver, DaemonIsLinux)
  2535  
  2536  	for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me"} {
  2537  		testReadOnlyFile(f, c)
  2538  	}
  2539  }
  2540  
  2541  func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  2542  	// Not applicable on Windows due to use of Unix specific functionality, plus
  2543  	// the use of --read-only which is not supported.
  2544  	// --read-only + userns has remount issues
  2545  	testRequires(c, DaemonIsLinux, NativeExecDriver, NotUserNamespace)
  2546  
  2547  	// Ensure we have not broken writing /dev/pts
  2548  	out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  2549  	if status != 0 {
  2550  		c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  2551  	}
  2552  	expected := "type devpts (rw,"
  2553  	if !strings.Contains(string(out), expected) {
  2554  		c.Fatalf("expected output to contain %s but contains %s", expected, out)
  2555  	}
  2556  }
  2557  
  2558  func testReadOnlyFile(filename string, c *check.C) {
  2559  	// Not applicable on Windows which does not support --read-only
  2560  	testRequires(c, NativeExecDriver, DaemonIsLinux, NotUserNamespace)
  2561  
  2562  	out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "touch", filename)
  2563  	if err == nil {
  2564  		c.Fatal("expected container to error on run with read only error")
  2565  	}
  2566  	expected := "Read-only file system"
  2567  	if !strings.Contains(string(out), expected) {
  2568  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2569  	}
  2570  
  2571  	out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
  2572  	if err == nil {
  2573  		c.Fatal("expected container to error on run with read only error")
  2574  	}
  2575  	expected = "Read-only file system"
  2576  	if !strings.Contains(string(out), expected) {
  2577  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2578  	}
  2579  }
  2580  
  2581  func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  2582  	// Not applicable on Windows which does not support --link
  2583  	// --read-only + userns has remount issues
  2584  	testRequires(c, NativeExecDriver, DaemonIsLinux, NotUserNamespace)
  2585  
  2586  	dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  2587  
  2588  	out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  2589  	if !strings.Contains(string(out), "testlinked") {
  2590  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  2591  	}
  2592  }
  2593  
  2594  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  2595  	// Not applicable on Windows which does not support either --read-only or --dns.
  2596  	// --read-only + userns has remount issues
  2597  	testRequires(c, NativeExecDriver, DaemonIsLinux, NotUserNamespace)
  2598  
  2599  	out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  2600  	if !strings.Contains(string(out), "1.1.1.1") {
  2601  		c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  2602  	}
  2603  }
  2604  
  2605  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  2606  	// Not applicable on Windows which does not support --read-only
  2607  	// --read-only + userns has remount issues
  2608  	testRequires(c, NativeExecDriver, DaemonIsLinux, NotUserNamespace)
  2609  
  2610  	out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  2611  	if !strings.Contains(string(out), "testreadonly") {
  2612  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  2613  	}
  2614  }
  2615  
  2616  func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  2617  	// TODO Windows. Not applicable on Windows which does not support volumes.
  2618  	// This may be possible to add in the future.
  2619  	testRequires(c, DaemonIsLinux)
  2620  	dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
  2621  	dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
  2622  
  2623  	// Remove the main volume container and restart the consuming container
  2624  	dockerCmd(c, "rm", "-f", "voltest")
  2625  
  2626  	// This should not fail since the volumes-from were already applied
  2627  	dockerCmd(c, "restart", "restarter")
  2628  }
  2629  
  2630  // run container with --rm should remove container if exit code != 0
  2631  func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2632  	name := "flowers"
  2633  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2634  	if err == nil {
  2635  		c.Fatal("Expected docker run to fail", out, err)
  2636  	}
  2637  
  2638  	out, err = getAllContainers()
  2639  	if err != nil {
  2640  		c.Fatal(out, err)
  2641  	}
  2642  
  2643  	if out != "" {
  2644  		c.Fatal("Expected not to have containers", out)
  2645  	}
  2646  }
  2647  
  2648  func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2649  	name := "sparkles"
  2650  	out, _, err := dockerCmdWithError("run", "--name", name, "--rm", "busybox", "commandNotFound")
  2651  	if err == nil {
  2652  		c.Fatal("Expected docker run to fail", out, err)
  2653  	}
  2654  
  2655  	out, err = getAllContainers()
  2656  	if err != nil {
  2657  		c.Fatal(out, err)
  2658  	}
  2659  
  2660  	if out != "" {
  2661  		c.Fatal("Expected not to have containers", out)
  2662  	}
  2663  }
  2664  
  2665  func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2666  	// Not applicable on Windows as uses Unix specific functionality
  2667  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  2668  	name := "ibuildthecloud"
  2669  	dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2670  
  2671  	c.Assert(waitRun(name), check.IsNil)
  2672  
  2673  	errchan := make(chan error)
  2674  	go func() {
  2675  		if out, _, err := dockerCmdWithError("kill", name); err != nil {
  2676  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  2677  		}
  2678  		close(errchan)
  2679  	}()
  2680  	select {
  2681  	case err := <-errchan:
  2682  		c.Assert(err, check.IsNil)
  2683  	case <-time.After(5 * time.Second):
  2684  		c.Fatal("Kill container timed out")
  2685  	}
  2686  }
  2687  
  2688  func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  2689  	// TODO Windows. This may be possible to enable once Windows supports
  2690  	// memory limits on containers
  2691  	testRequires(c, DaemonIsLinux)
  2692  	// this memory limit is 1 byte less than the min, which is 4MB
  2693  	// https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  2694  	out, _, err := dockerCmdWithError("run", "-m", "4194303", "busybox")
  2695  	if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2696  		c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2697  	}
  2698  }
  2699  
  2700  func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  2701  	// Not applicable on Windows as uses Unix specific functionality
  2702  	testRequires(c, DaemonIsLinux)
  2703  	_, code, err := dockerCmdWithError("run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2704  	if err == nil || code == 0 {
  2705  		c.Fatal("standard container should not be able to write to /proc/asound")
  2706  	}
  2707  }
  2708  
  2709  func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  2710  	// Not applicable on Windows as uses Unix specific functionality
  2711  	testRequires(c, NativeExecDriver, DaemonIsLinux)
  2712  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/timer_stats")
  2713  	if code != 0 {
  2714  		return
  2715  	}
  2716  	if err != nil {
  2717  		c.Fatal(err)
  2718  	}
  2719  	if strings.Trim(out, "\n ") != "" {
  2720  		c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2721  	}
  2722  }
  2723  
  2724  func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  2725  	// Not applicable on Windows as uses Unix specific functionality
  2726  	testRequires(c, NativeExecDriver, DaemonIsLinux)
  2727  	// some kernels don't have this configured so skip the test if this file is not found
  2728  	// on the host running the tests.
  2729  	if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2730  		c.Skip("kernel doesnt have latency_stats configured")
  2731  		return
  2732  	}
  2733  	out, code, err := dockerCmdWithError("run", "busybox", "cat", "/proc/latency_stats")
  2734  	if code != 0 {
  2735  		return
  2736  	}
  2737  	if err != nil {
  2738  		c.Fatal(err)
  2739  	}
  2740  	if strings.Trim(out, "\n ") != "" {
  2741  		c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2742  	}
  2743  }
  2744  
  2745  func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  2746  	// Not applicable on Windows as uses Unix specific functionality
  2747  	testRequires(c, Apparmor, DaemonIsLinux, NotUserNamespace)
  2748  
  2749  	testReadPaths := []string{
  2750  		"/proc/latency_stats",
  2751  		"/proc/timer_stats",
  2752  		"/proc/kcore",
  2753  	}
  2754  	for i, filePath := range testReadPaths {
  2755  		name := fmt.Sprintf("procsieve-%d", i)
  2756  		shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2757  
  2758  		out, exitCode, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2759  		if exitCode != 0 {
  2760  			return
  2761  		}
  2762  		if err != nil {
  2763  			c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2764  		}
  2765  	}
  2766  }
  2767  
  2768  func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  2769  	// Not applicable on Windows as uses Unix specific functionality
  2770  	testRequires(c, DaemonIsLinux)
  2771  	testRequires(c, NativeExecDriver)
  2772  	_, code, err := dockerCmdWithError("run", "-v", "/proc//sys", "busybox", "true")
  2773  	if err == nil || code == 0 {
  2774  		c.Fatal("container should not be able to mount into /proc")
  2775  	}
  2776  }
  2777  
  2778  func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  2779  	// Not applicable on Windows as uses Unix specific functionality
  2780  	testRequires(c, DaemonIsLinux)
  2781  	testRequires(c, NativeExecDriver, NotUserNamespace)
  2782  	dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2783  }
  2784  
  2785  func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  2786  	c.Skip("unstable test: is apparmor in a container reliable?")
  2787  
  2788  	// Not applicable on Windows as uses Unix specific functionality
  2789  	testRequires(c, Apparmor, NativeExecDriver, DaemonIsLinux)
  2790  
  2791  	name := "acidburn"
  2792  	if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
  2793  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2794  	}
  2795  
  2796  	name = "cereal"
  2797  	if out, _, err := dockerCmdWithError("run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2798  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2799  	}
  2800  
  2801  	/* Ensure still fails if running privileged with the default policy */
  2802  	name = "crashoverride"
  2803  	if out, _, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2804  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2805  	}
  2806  }
  2807  
  2808  func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  2809  	// TODO Windows: This may be possible once Windows moves to libnetwork and CNM
  2810  	testRequires(c, DaemonIsLinux)
  2811  	dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2812  	out, _ := dockerCmd(c, "port", "test")
  2813  	out = strings.Trim(out, "\r\n")
  2814  	if out != "" {
  2815  		c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2816  	}
  2817  }
  2818  
  2819  // Issue #10184.
  2820  func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  2821  	// Not applicable on Windows as uses Unix specific functionality
  2822  	testRequires(c, DaemonIsLinux)
  2823  	testRequires(c, NativeExecDriver)
  2824  	const permissions = "crw-rw-rw-"
  2825  	out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2826  	if status != 0 {
  2827  		c.Fatalf("expected status 0, got %d", status)
  2828  	}
  2829  	if !strings.HasPrefix(out, permissions) {
  2830  		c.Fatalf("output should begin with %q, got %q", permissions, out)
  2831  	}
  2832  }
  2833  
  2834  func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  2835  	// Not applicable on Windows as uses Unix specific functionality
  2836  	testRequires(c, DaemonIsLinux)
  2837  	testRequires(c, NativeExecDriver)
  2838  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  2839  
  2840  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  2841  		c.Fatalf("expected output ok received %s", actual)
  2842  	}
  2843  }
  2844  
  2845  // https://github.com/docker/docker/pull/14498
  2846  func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  2847  	// Not applicable on Windows as volumes are not supported on Winodws
  2848  	testRequires(c, DaemonIsLinux)
  2849  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  2850  	dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  2851  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  2852  
  2853  	mRO, err := inspectMountPoint("test-volumes-1", "/test")
  2854  	c.Assert(err, check.IsNil)
  2855  	if mRO.RW {
  2856  		c.Fatalf("Expected RO volume was RW")
  2857  	}
  2858  
  2859  	mRW, err := inspectMountPoint("test-volumes-2", "/test")
  2860  	c.Assert(err, check.IsNil)
  2861  	if !mRW.RW {
  2862  		c.Fatalf("Expected RW volume was RO")
  2863  	}
  2864  }
  2865  
  2866  func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  2867  	// Not applicable on Windows as uses Unix specific functionality
  2868  	testRequires(c, Apparmor, NativeExecDriver, DaemonIsLinux, NotUserNamespace)
  2869  
  2870  	testWritePaths := []string{
  2871  		/* modprobe and core_pattern should both be denied by generic
  2872  		 * policy of denials for /proc/sys/kernel. These files have been
  2873  		 * picked to be checked as they are particularly sensitive to writes */
  2874  		"/proc/sys/kernel/modprobe",
  2875  		"/proc/sys/kernel/core_pattern",
  2876  		"/proc/sysrq-trigger",
  2877  		"/proc/kcore",
  2878  	}
  2879  	for i, filePath := range testWritePaths {
  2880  		name := fmt.Sprintf("writeprocsieve-%d", i)
  2881  
  2882  		shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  2883  		out, code, err := dockerCmdWithError("run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2884  		if code != 0 {
  2885  			return
  2886  		}
  2887  		if err != nil {
  2888  			c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  2889  		}
  2890  	}
  2891  }
  2892  
  2893  func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  2894  	// Not applicable on Windows as uses Unix specific functionality
  2895  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2896  
  2897  	expected := "test123"
  2898  
  2899  	filename := createTmpFile(c, expected)
  2900  	defer os.Remove(filename)
  2901  
  2902  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2903  
  2904  	for i := range nwfiles {
  2905  		actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i])
  2906  		if actual != expected {
  2907  			c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual)
  2908  		}
  2909  	}
  2910  }
  2911  
  2912  func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) {
  2913  	// Not applicable on Windows as uses Unix specific functionality
  2914  	testRequires(c, SameHostDaemon, DaemonIsLinux)
  2915  
  2916  	filename := createTmpFile(c, "test123")
  2917  	defer os.Remove(filename)
  2918  
  2919  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2920  
  2921  	for i := range nwfiles {
  2922  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "busybox", "touch", nwfiles[i])
  2923  		if err == nil || exitCode == 0 {
  2924  			c.Fatalf("run should fail because bind mount of %s is ro: exit code %d", nwfiles[i], exitCode)
  2925  		}
  2926  	}
  2927  }
  2928  
  2929  func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) {
  2930  	// Not applicable on Windows as uses Unix specific functionality
  2931  	// --read-only + userns has remount issues
  2932  	testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace)
  2933  
  2934  	filename := createTmpFile(c, "test123")
  2935  	defer os.Remove(filename)
  2936  
  2937  	nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"}
  2938  
  2939  	for i := range nwfiles {
  2940  		_, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i])
  2941  		if exitCode != 0 {
  2942  			c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2943  		}
  2944  	}
  2945  
  2946  	for i := range nwfiles {
  2947  		_, exitCode, err := dockerCmdWithError("run", "-v", filename+":"+nwfiles[i]+":ro", "--read-only", "busybox", "touch", nwfiles[i])
  2948  		if err == nil || exitCode == 0 {
  2949  			c.Fatalf("run should fail because %s is mounted read-only on read-only root filesystem: exit code %d", nwfiles[i], exitCode)
  2950  		}
  2951  	}
  2952  }
  2953  
  2954  func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  2955  	// Windows does not support this functionality
  2956  	testRequires(c, DaemonIsLinux)
  2957  	repoName := s.setupTrustedImage(c, "trusted-run")
  2958  
  2959  	// Try run
  2960  	runCmd := exec.Command(dockerBinary, "run", repoName)
  2961  	s.trustedCmd(runCmd)
  2962  	out, _, err := runCommandWithOutput(runCmd)
  2963  	if err != nil {
  2964  		c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  2965  	}
  2966  
  2967  	if !strings.Contains(string(out), "Tagging") {
  2968  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2969  	}
  2970  
  2971  	dockerCmd(c, "rmi", repoName)
  2972  
  2973  	// Try untrusted run to ensure we pushed the tag to the registry
  2974  	runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  2975  	s.trustedCmd(runCmd)
  2976  	out, _, err = runCommandWithOutput(runCmd)
  2977  	if err != nil {
  2978  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2979  	}
  2980  
  2981  	if !strings.Contains(string(out), "Status: Downloaded") {
  2982  		c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  2983  	}
  2984  }
  2985  
  2986  func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  2987  	// Windows does not support this functionality
  2988  	testRequires(c, DaemonIsLinux)
  2989  	repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL)
  2990  	// tag the image and upload it to the private registry
  2991  	dockerCmd(c, "tag", "busybox", repoName)
  2992  	dockerCmd(c, "push", repoName)
  2993  	dockerCmd(c, "rmi", repoName)
  2994  
  2995  	// Try trusted run on untrusted tag
  2996  	runCmd := exec.Command(dockerBinary, "run", repoName)
  2997  	s.trustedCmd(runCmd)
  2998  	out, _, err := runCommandWithOutput(runCmd)
  2999  	if err == nil {
  3000  		c.Fatalf("Error expected when running trusted run with:\n%s", out)
  3001  	}
  3002  
  3003  	if !strings.Contains(string(out), "no trust data available") {
  3004  		c.Fatalf("Missing expected output on trusted run:\n%s", out)
  3005  	}
  3006  }
  3007  
  3008  func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  3009  	// Windows does not support this functionality
  3010  	testRequires(c, DaemonIsLinux)
  3011  	c.Skip("Currently changes system time, causing instability")
  3012  	repoName := s.setupTrustedImage(c, "trusted-run-expired")
  3013  
  3014  	// Certificates have 10 years of expiration
  3015  	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  3016  
  3017  	runAtDifferentDate(elevenYearsFromNow, func() {
  3018  		// Try run
  3019  		runCmd := exec.Command(dockerBinary, "run", repoName)
  3020  		s.trustedCmd(runCmd)
  3021  		out, _, err := runCommandWithOutput(runCmd)
  3022  		if err == nil {
  3023  			c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  3024  		}
  3025  
  3026  		if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  3027  			c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  3028  		}
  3029  	})
  3030  
  3031  	runAtDifferentDate(elevenYearsFromNow, func() {
  3032  		// Try run
  3033  		runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  3034  		s.trustedCmd(runCmd)
  3035  		out, _, err := runCommandWithOutput(runCmd)
  3036  		if err != nil {
  3037  			c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  3038  		}
  3039  
  3040  		if !strings.Contains(string(out), "Status: Downloaded") {
  3041  			c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  3042  		}
  3043  	})
  3044  }
  3045  
  3046  func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  3047  	// Windows does not support this functionality
  3048  	testRequires(c, DaemonIsLinux)
  3049  	repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  3050  	evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir")
  3051  	if err != nil {
  3052  		c.Fatalf("Failed to create local temp dir")
  3053  	}
  3054  
  3055  	// tag the image and upload it to the private registry
  3056  	dockerCmd(c, "tag", "busybox", repoName)
  3057  
  3058  	pushCmd := exec.Command(dockerBinary, "push", repoName)
  3059  	s.trustedCmd(pushCmd)
  3060  	out, _, err := runCommandWithOutput(pushCmd)
  3061  	if err != nil {
  3062  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3063  	}
  3064  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3065  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3066  	}
  3067  
  3068  	dockerCmd(c, "rmi", repoName)
  3069  
  3070  	// Try run
  3071  	runCmd := exec.Command(dockerBinary, "run", repoName)
  3072  	s.trustedCmd(runCmd)
  3073  	out, _, err = runCommandWithOutput(runCmd)
  3074  	if err != nil {
  3075  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  3076  	}
  3077  
  3078  	if !strings.Contains(string(out), "Tagging") {
  3079  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3080  	}
  3081  
  3082  	dockerCmd(c, "rmi", repoName)
  3083  
  3084  	// Kill the notary server, start a new "evil" one.
  3085  	s.not.Close()
  3086  	s.not, err = newTestNotary(c)
  3087  	if err != nil {
  3088  		c.Fatalf("Restarting notary server failed.")
  3089  	}
  3090  
  3091  	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  3092  	// tag an image and upload it to the private registry
  3093  	dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  3094  
  3095  	// Push up to the new server
  3096  	pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  3097  	s.trustedCmd(pushCmd)
  3098  	out, _, err = runCommandWithOutput(pushCmd)
  3099  	if err != nil {
  3100  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  3101  	}
  3102  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  3103  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3104  	}
  3105  
  3106  	// Now, try running with the original client from this new trust server. This should fail.
  3107  	runCmd = exec.Command(dockerBinary, "run", repoName)
  3108  	s.trustedCmd(runCmd)
  3109  	out, _, err = runCommandWithOutput(runCmd)
  3110  	if err == nil {
  3111  		c.Fatalf("Expected to fail on this run due to different remote data: %s\n%s", err, out)
  3112  	}
  3113  
  3114  	if !strings.Contains(string(out), "failed to validate data with current trusted certificates") {
  3115  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  3116  	}
  3117  }
  3118  
  3119  func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  3120  	// Not applicable on Windows as uses Unix specific functionality
  3121  	testRequires(c, DaemonIsLinux, SameHostDaemon)
  3122  
  3123  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  3124  	id := strings.TrimSpace(out)
  3125  	c.Assert(waitRun(id), check.IsNil)
  3126  	pid1, err := inspectField(id, "State.Pid")
  3127  	c.Assert(err, check.IsNil)
  3128  
  3129  	_, err = os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  3130  	if err != nil {
  3131  		c.Fatal(err)
  3132  	}
  3133  }
  3134  
  3135  func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  3136  	// Not applicable on Windows as uses Unix specific functionality
  3137  	testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor, DaemonIsLinux, NotGCCGO)
  3138  
  3139  	// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  3140  	// itself, but pid>1 should not be able to trace pid1.
  3141  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "sh", "-c", "readlink /proc/1/ns/net")
  3142  	if exitCode == 0 {
  3143  		c.Fatal("ptrace was not successfully restricted by AppArmor")
  3144  	}
  3145  }
  3146  
  3147  func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  3148  	// Not applicable on Windows as uses Unix specific functionality
  3149  	testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor)
  3150  
  3151  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net")
  3152  	if exitCode != 0 {
  3153  		c.Fatal("ptrace of self failed.")
  3154  	}
  3155  }
  3156  
  3157  func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) {
  3158  	c.Skip("Test is failing, and what it tests is unclear")
  3159  
  3160  	// Not applicable on Windows as uses Unix specific functionality
  3161  	testRequires(c, SameHostDaemon, NativeExecDriver, Apparmor, DaemonIsLinux)
  3162  	_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo")
  3163  	if exitCode == 0 {
  3164  		// If our test failed, attempt to repair the host system...
  3165  		_, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "444", "/proc/cpuinfo")
  3166  		if exitCode == 0 {
  3167  			c.Fatal("AppArmor was unsuccessful in prohibiting chmod of /proc/* files.")
  3168  		}
  3169  	}
  3170  }
  3171  
  3172  func (s *DockerSuite) TestRunCapAddSYSTIME(c *check.C) {
  3173  	// Not applicable on Windows as uses Unix specific functionality
  3174  	testRequires(c, DaemonIsLinux, NativeExecDriver)
  3175  
  3176  	dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$")
  3177  }
  3178  
  3179  // run create container failed should clean up the container
  3180  func (s *DockerSuite) TestRunCreateContainerFailedCleanUp(c *check.C) {
  3181  	// TODO Windows. This may be possible to enable once link is supported
  3182  	testRequires(c, DaemonIsLinux)
  3183  	name := "unique_name"
  3184  	_, _, err := dockerCmdWithError("run", "--name", name, "--link", "nothing:nothing", "busybox")
  3185  	c.Assert(err, check.NotNil, check.Commentf("Expected docker run to fail!"))
  3186  
  3187  	containerID, err := inspectField(name, "Id")
  3188  	c.Assert(containerID, check.Equals, "", check.Commentf("Expected not to have this container: %s!", containerID))
  3189  }
  3190  
  3191  func (s *DockerSuite) TestRunNamedVolume(c *check.C) {
  3192  	// TODO Windows: This may be possible to modify once Windows supports volumes
  3193  	testRequires(c, DaemonIsLinux)
  3194  	dockerCmd(c, "run", "--name=test", "-v", "testing:/foo", "busybox", "sh", "-c", "echo hello > /foo/bar")
  3195  
  3196  	out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat /foo/bar")
  3197  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3198  
  3199  	out, _ = dockerCmd(c, "run", "-v", "testing:/foo", "busybox", "sh", "-c", "cat /foo/bar")
  3200  	c.Assert(strings.TrimSpace(out), check.Equals, "hello")
  3201  }
  3202  
  3203  func (s *DockerSuite) TestRunWithUlimits(c *check.C) {
  3204  	// Not applicable on Windows as uses Unix specific functionality
  3205  	testRequires(c, DaemonIsLinux, NativeExecDriver)
  3206  
  3207  	out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n")
  3208  	ul := strings.TrimSpace(out)
  3209  	if ul != "42" {
  3210  		c.Fatalf("expected `ulimit -n` to be 42, got %s", ul)
  3211  	}
  3212  }
  3213  
  3214  func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) {
  3215  	// Not applicable on Windows as uses Unix specific functionality
  3216  	testRequires(c, DaemonIsLinux, NativeExecDriver)
  3217  
  3218  	cgroupParent := "test"
  3219  	name := "cgroup-test"
  3220  
  3221  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3222  	if err != nil {
  3223  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3224  	}
  3225  	cgroupPaths := parseCgroupPaths(string(out))
  3226  	if len(cgroupPaths) == 0 {
  3227  		c.Fatalf("unexpected output - %q", string(out))
  3228  	}
  3229  	id, err := getIDByName(name)
  3230  	c.Assert(err, check.IsNil)
  3231  	expectedCgroup := path.Join(cgroupParent, id)
  3232  	found := false
  3233  	for _, path := range cgroupPaths {
  3234  		if strings.HasSuffix(path, expectedCgroup) {
  3235  			found = true
  3236  			break
  3237  		}
  3238  	}
  3239  	if !found {
  3240  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3241  	}
  3242  }
  3243  
  3244  func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) {
  3245  	// Not applicable on Windows as uses Unix specific functionality
  3246  	testRequires(c, DaemonIsLinux, NativeExecDriver)
  3247  
  3248  	cgroupParent := "/cgroup-parent/test"
  3249  	name := "cgroup-test"
  3250  	out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup")
  3251  	if err != nil {
  3252  		c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err)
  3253  	}
  3254  	cgroupPaths := parseCgroupPaths(string(out))
  3255  	if len(cgroupPaths) == 0 {
  3256  		c.Fatalf("unexpected output - %q", string(out))
  3257  	}
  3258  	id, err := getIDByName(name)
  3259  	c.Assert(err, check.IsNil)
  3260  	expectedCgroup := path.Join(cgroupParent, id)
  3261  	found := false
  3262  	for _, path := range cgroupPaths {
  3263  		if strings.HasSuffix(path, expectedCgroup) {
  3264  			found = true
  3265  			break
  3266  		}
  3267  	}
  3268  	if !found {
  3269  		c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths)
  3270  	}
  3271  }
  3272  
  3273  func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) {
  3274  	// Not applicable on Windows as uses Unix specific functionality
  3275  	// --read-only + userns has remount issues
  3276  	testRequires(c, DaemonIsLinux, NativeExecDriver, NotUserNamespace)
  3277  
  3278  	filename := "/sys/fs/cgroup/devices/test123"
  3279  	out, _, err := dockerCmdWithError("run", "busybox", "touch", filename)
  3280  	if err == nil {
  3281  		c.Fatal("expected cgroup mount point to be read-only, touch file should fail")
  3282  	}
  3283  	expected := "Read-only file system"
  3284  	if !strings.Contains(out, expected) {
  3285  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  3286  	}
  3287  }
  3288  
  3289  func (s *DockerSuite) TestRunContainerNetworkModeToSelf(c *check.C) {
  3290  	// Not applicable on Windows which does not support --net=container
  3291  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3292  	out, _, err := dockerCmdWithError("run", "--name=me", "--net=container:me", "busybox", "true")
  3293  	if err == nil || !strings.Contains(out, "cannot join own network") {
  3294  		c.Fatalf("using container net mode to self should result in an error\nerr: %q\nout: %s", err, out)
  3295  	}
  3296  }
  3297  
  3298  func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) {
  3299  	// Not applicable on Windows which does not support --net=container
  3300  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3301  	out, _, err := dockerCmdWithError("run", "-d", "--name", "parent", "busybox", "top")
  3302  	if err != nil {
  3303  		c.Fatalf("failed to run container: %v, output: %q", err, out)
  3304  	}
  3305  
  3306  	out, _, err = dockerCmdWithError("run", "--dns", "1.2.3.4", "--net=container:parent", "busybox")
  3307  	if err == nil || !strings.Contains(out, "Conflicting options: --dns and the network mode") {
  3308  		c.Fatalf("run --net=container with --dns should error out")
  3309  	}
  3310  
  3311  	out, _, err = dockerCmdWithError("run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox")
  3312  	if err == nil || !strings.Contains(out, "--mac-address and the network mode") {
  3313  		c.Fatalf("run --net=container with --mac-address should error out")
  3314  	}
  3315  
  3316  	out, _, err = dockerCmdWithError("run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox")
  3317  	if err == nil || !strings.Contains(out, "--add-host and the network mode") {
  3318  		c.Fatalf("run --net=container with --add-host should error out")
  3319  	}
  3320  }
  3321  
  3322  func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) {
  3323  	// Not applicable on Windows which does not support --net=container
  3324  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3325  	dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top")
  3326  
  3327  	out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox")
  3328  	if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
  3329  		c.Fatalf("run --net=container with -p should error out")
  3330  	}
  3331  
  3332  	out, _, err = dockerCmdWithError("run", "-P", "--net=container:parent", "busybox")
  3333  	if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") {
  3334  		c.Fatalf("run --net=container with -P should error out")
  3335  	}
  3336  
  3337  	out, _, err = dockerCmdWithError("run", "--expose", "5000", "--net=container:parent", "busybox")
  3338  	if err == nil || !strings.Contains(out, "Conflicting options: --expose and the network mode (--expose)") {
  3339  		c.Fatalf("run --net=container with --expose should error out")
  3340  	}
  3341  }
  3342  
  3343  func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) {
  3344  	// Not applicable on Windows which does not support --net=container or --link
  3345  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3346  	dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top")
  3347  	dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top")
  3348  	dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top")
  3349  	dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top")
  3350  	dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top")
  3351  }
  3352  
  3353  func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) {
  3354  	// TODO Windows: This may be possible to convert.
  3355  	testRequires(c, DaemonIsLinux)
  3356  	out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up")
  3357  
  3358  	var (
  3359  		count = 0
  3360  		parts = strings.Split(out, "\n")
  3361  	)
  3362  
  3363  	for _, l := range parts {
  3364  		if l != "" {
  3365  			count++
  3366  		}
  3367  	}
  3368  
  3369  	if count != 1 {
  3370  		c.Fatalf("Wrong interface count in container %d", count)
  3371  	}
  3372  
  3373  	if !strings.HasPrefix(out, "1: lo") {
  3374  		c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out)
  3375  	}
  3376  }
  3377  
  3378  // Issue #4681
  3379  func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) {
  3380  	if daemonPlatform == "windows" {
  3381  		dockerCmd(c, "run", "--net=none", WindowsBaseImage, "ping", "-n", "1", "127.0.0.1")
  3382  	} else {
  3383  		dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1")
  3384  	}
  3385  }
  3386  
  3387  func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) {
  3388  	// Windows does not support --net=container
  3389  	testRequires(c, DaemonIsLinux, ExecSupport, NotUserNamespace)
  3390  
  3391  	dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top")
  3392  	out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname")
  3393  	out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname")
  3394  
  3395  	if out1 != out {
  3396  		c.Fatal("containers with shared net namespace should have same hostname")
  3397  	}
  3398  }
  3399  
  3400  func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) {
  3401  	// TODO Windows: Network settings are not currently propagated. This may
  3402  	// be resolved in the future with the move to libnetwork and CNM.
  3403  	testRequires(c, DaemonIsLinux)
  3404  	out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top")
  3405  	id := strings.TrimSpace(out)
  3406  	res, err := inspectField(id, "NetworkSettings.Networks.none.IPAddress")
  3407  	c.Assert(err, check.IsNil)
  3408  	if res != "" {
  3409  		c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res)
  3410  	}
  3411  }
  3412  
  3413  func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) {
  3414  	// Not applicable as Windows does not support --net=host
  3415  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace)
  3416  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3417  	dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top")
  3418  	dockerCmd(c, "stop", "first")
  3419  	dockerCmd(c, "stop", "second")
  3420  }
  3421  
  3422  func (s *DockerSuite) TestContainersInUserDefinedNetwork(c *check.C) {
  3423  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3424  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork")
  3425  	dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top")
  3426  	c.Assert(waitRun("first"), check.IsNil)
  3427  	dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first")
  3428  }
  3429  
  3430  func (s *DockerSuite) TestContainersInMultipleNetworks(c *check.C) {
  3431  	testRequires(c, DaemonIsLinux, NotUserNamespace, NativeExecDriver)
  3432  	// Create 2 networks using bridge driver
  3433  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3434  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3435  	// Run and connect containers to testnetwork1
  3436  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3437  	c.Assert(waitRun("first"), check.IsNil)
  3438  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3439  	c.Assert(waitRun("second"), check.IsNil)
  3440  	// Check connectivity between containers in testnetwork2
  3441  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3442  	// Connect containers to testnetwork2
  3443  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3444  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3445  	// Check connectivity between containers
  3446  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3447  }
  3448  
  3449  func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) {
  3450  	testRequires(c, DaemonIsLinux, NotUserNamespace, NativeExecDriver)
  3451  	// Create 2 networks using bridge driver
  3452  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3453  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3454  	// Run 1 container in testnetwork1 and another in testnetwork2
  3455  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3456  	c.Assert(waitRun("first"), check.IsNil)
  3457  	dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top")
  3458  	c.Assert(waitRun("second"), check.IsNil)
  3459  
  3460  	// Check Isolation between containers : ping must fail
  3461  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3462  	c.Assert(err, check.NotNil)
  3463  	// Connect first container to testnetwork2
  3464  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3465  	// ping must succeed now
  3466  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3467  	c.Assert(err, check.IsNil)
  3468  
  3469  	// Disconnect first container from testnetwork2
  3470  	dockerCmd(c, "network", "disconnect", "testnetwork2", "first")
  3471  	// ping must fail again
  3472  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second")
  3473  	c.Assert(err, check.NotNil)
  3474  }
  3475  
  3476  func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) {
  3477  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3478  	// Create 2 networks using bridge driver
  3479  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3480  	// Run and connect containers to testnetwork1
  3481  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3482  	c.Assert(waitRun("first"), check.IsNil)
  3483  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3484  	c.Assert(waitRun("second"), check.IsNil)
  3485  	// Network delete with active containers must fail
  3486  	_, _, err := dockerCmdWithError("network", "rm", "testnetwork1")
  3487  	c.Assert(err, check.NotNil)
  3488  
  3489  	dockerCmd(c, "stop", "first")
  3490  	_, _, err = dockerCmdWithError("network", "rm", "testnetwork1")
  3491  	c.Assert(err, check.NotNil)
  3492  }
  3493  
  3494  func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) {
  3495  	testRequires(c, DaemonIsLinux, NotUserNamespace, NativeExecDriver)
  3496  	// Create 2 networks using bridge driver
  3497  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3498  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2")
  3499  
  3500  	// Run and connect containers to testnetwork1
  3501  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top")
  3502  	c.Assert(waitRun("first"), check.IsNil)
  3503  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3504  	c.Assert(waitRun("second"), check.IsNil)
  3505  	// Check connectivity between containers in testnetwork2
  3506  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3507  	// Connect containers to testnetwork2
  3508  	dockerCmd(c, "network", "connect", "testnetwork2", "first")
  3509  	dockerCmd(c, "network", "connect", "testnetwork2", "second")
  3510  	// Check connectivity between containers
  3511  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3512  
  3513  	// Stop second container and test ping failures on both networks
  3514  	dockerCmd(c, "stop", "second")
  3515  	_, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3516  	c.Assert(err, check.NotNil)
  3517  	_, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2")
  3518  	c.Assert(err, check.NotNil)
  3519  
  3520  	// Start second container and connectivity must be restored on both networks
  3521  	dockerCmd(c, "start", "second")
  3522  	dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1")
  3523  	dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2")
  3524  }
  3525  
  3526  func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) {
  3527  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3528  	// Run a container with --net=host
  3529  	dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top")
  3530  	c.Assert(waitRun("first"), check.IsNil)
  3531  
  3532  	// Create a network using bridge driver
  3533  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3534  
  3535  	// Connecting to the user defined network must fail
  3536  	_, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3537  	c.Assert(err, check.NotNil)
  3538  }
  3539  
  3540  func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) {
  3541  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3542  	dockerCmd(c, "run", "-d", "--name=first", "busybox", "top")
  3543  	c.Assert(waitRun("first"), check.IsNil)
  3544  	// Run second container in first container's network namespace
  3545  	dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top")
  3546  	c.Assert(waitRun("second"), check.IsNil)
  3547  
  3548  	// Create a network using bridge driver
  3549  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3550  
  3551  	// Connecting to the user defined network must fail
  3552  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second")
  3553  	c.Assert(err, check.NotNil)
  3554  	c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error())
  3555  }
  3556  
  3557  func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) {
  3558  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  3559  	dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top")
  3560  	c.Assert(waitRun("first"), check.IsNil)
  3561  
  3562  	// Create a network using bridge driver
  3563  	dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1")
  3564  
  3565  	// Connecting to the user defined network must fail
  3566  	out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first")
  3567  	c.Assert(err, check.NotNil)
  3568  	c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error())
  3569  
  3570  	// create a container connected to testnetwork1
  3571  	dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top")
  3572  	c.Assert(waitRun("second"), check.IsNil)
  3573  
  3574  	// Connect second container to none network. it must fail as well
  3575  	_, _, err = dockerCmdWithError("network", "connect", "none", "second")
  3576  	c.Assert(err, check.NotNil)
  3577  }
  3578  
  3579  // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited
  3580  func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) {
  3581  	cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true")
  3582  	in, err := cmd.StdinPipe()
  3583  	c.Assert(err, check.IsNil)
  3584  	defer in.Close()
  3585  	c.Assert(cmd.Start(), check.IsNil)
  3586  
  3587  	waitChan := make(chan error)
  3588  	go func() {
  3589  		waitChan <- cmd.Wait()
  3590  	}()
  3591  
  3592  	select {
  3593  	case err := <-waitChan:
  3594  		c.Assert(err, check.IsNil)
  3595  	case <-time.After(30 * time.Second):
  3596  		c.Fatal("timeout waiting for command to exit")
  3597  	}
  3598  }
  3599  
  3600  func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) {
  3601  	out, _, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true")
  3602  	c.Assert(err, check.NotNil)
  3603  	expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n"
  3604  	c.Assert(out, check.Equals, expected, check.Commentf("Expected output to contain %q, got %q", expected, out))
  3605  }
  3606  
  3607  func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) {
  3608  	out, _, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true")
  3609  	c.Assert(err, check.NotNil)
  3610  	expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n"
  3611  	c.Assert(out, check.Equals, expected, check.Commentf("Expected output to contain %q, got %q", expected, out))
  3612  }