github.com/yp-engineering/docker@v1.8.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/nat"
    22  	"github.com/docker/libnetwork/resolvconf"
    23  	"github.com/go-check/check"
    24  )
    25  
    26  // "test123" should be printed by docker run
    27  func (s *DockerSuite) TestRunEchoStdout(c *check.C) {
    28  	out, _ := dockerCmd(c, "run", "busybox", "echo", "test123")
    29  	if out != "test123\n" {
    30  		c.Fatalf("container should've printed 'test123'")
    31  	}
    32  }
    33  
    34  // "test" should be printed
    35  func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) {
    36  	out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "16m", "busybox", "echo", "test")
    37  	out = strings.Trim(out, "\r\n")
    38  
    39  	if expected := "test"; out != expected {
    40  		c.Fatalf("container should've printed %q but printed %q", expected, out)
    41  	}
    42  }
    43  
    44  // should run without memory swap
    45  func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
    46  	testRequires(c, NativeExecDriver)
    47  	dockerCmd(c, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true")
    48  }
    49  
    50  func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
    51  	dockerCmd(c, "run", "--memory-swappiness", "0", "busybox", "true")
    52  }
    53  
    54  func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
    55  	out, _, err := dockerCmdWithError(c, "run", "--memory-swappiness", "101", "busybox", "true")
    56  	if err == nil {
    57  		c.Fatalf("failed. test was able to set invalid value, output: %q", out)
    58  	}
    59  }
    60  
    61  // "test" should be printed
    62  func (s *DockerSuite) TestRunEchoStdoutWitCPULimit(c *check.C) {
    63  	out, _ := dockerCmd(c, "run", "-c", "1000", "busybox", "echo", "test")
    64  	if out != "test\n" {
    65  		c.Errorf("container should've printed 'test'")
    66  	}
    67  }
    68  
    69  // "test" should be printed
    70  func (s *DockerSuite) TestRunEchoStdoutWithCPUAndMemoryLimit(c *check.C) {
    71  	out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-c", "1000", "-m", "16m", "busybox", "echo", "test")
    72  	if out != "test\n" {
    73  		c.Errorf("container should've printed 'test', got %q instead", out)
    74  	}
    75  }
    76  
    77  // "test" should be printed
    78  func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) {
    79  	out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test")
    80  	if out != "test\n" {
    81  		c.Errorf("container should've printed 'test'")
    82  	}
    83  }
    84  
    85  // docker run should not leak file descriptors
    86  func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) {
    87  	out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd")
    88  
    89  	// normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory
    90  	if out != "0  1  2  3\n" {
    91  		c.Errorf("container should've printed '0  1  2  3', not: %s", out)
    92  	}
    93  }
    94  
    95  // it should be possible to lookup Google DNS
    96  // this will fail when Internet access is unavailable
    97  func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) {
    98  	testRequires(c, Network)
    99  	dockerCmd(c, "run", "busybox", "nslookup", "google.com")
   100  }
   101  
   102  // the exit code should be 0
   103  // some versions of lxc might make this test fail
   104  func (s *DockerSuite) TestRunExitCodeZero(c *check.C) {
   105  	dockerCmd(c, "run", "busybox", "true")
   106  }
   107  
   108  // the exit code should be 1
   109  // some versions of lxc might make this test fail
   110  func (s *DockerSuite) TestRunExitCodeOne(c *check.C) {
   111  	_, exitCode, err := dockerCmdWithError(c, "run", "busybox", "false")
   112  	if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) {
   113  		c.Fatal(err)
   114  	}
   115  	if exitCode != 1 {
   116  		c.Errorf("container should've exited with exit code 1")
   117  	}
   118  }
   119  
   120  // it should be possible to pipe in data via stdin to a process running in a container
   121  // some versions of lxc might make this test fail
   122  func (s *DockerSuite) TestRunStdinPipe(c *check.C) {
   123  	runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat")
   124  	runCmd.Stdin = strings.NewReader("blahblah")
   125  	out, _, _, err := runCommandWithStdoutStderr(runCmd)
   126  	if err != nil {
   127  		c.Fatalf("failed to run container: %v, output: %q", err, out)
   128  	}
   129  
   130  	out = strings.TrimSpace(out)
   131  	dockerCmd(c, "wait", out)
   132  
   133  	logsOut, _ := dockerCmd(c, "logs", out)
   134  
   135  	containerLogs := strings.TrimSpace(logsOut)
   136  	if containerLogs != "blahblah" {
   137  		c.Errorf("logs didn't print the container's logs %s", containerLogs)
   138  	}
   139  
   140  	dockerCmd(c, "rm", out)
   141  }
   142  
   143  // the container's ID should be printed when starting a container in detached mode
   144  func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) {
   145  	out, _ := dockerCmd(c, "run", "-d", "busybox", "true")
   146  
   147  	out = strings.TrimSpace(out)
   148  	dockerCmd(c, "wait", out)
   149  
   150  	rmOut, _ := dockerCmd(c, "rm", out)
   151  
   152  	rmOut = strings.TrimSpace(rmOut)
   153  	if rmOut != out {
   154  		c.Errorf("rm didn't print the container ID %s %s", out, rmOut)
   155  	}
   156  }
   157  
   158  // the working directory should be set correctly
   159  func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) {
   160  	out, _ := dockerCmd(c, "run", "-w", "/root", "busybox", "pwd")
   161  
   162  	out = strings.TrimSpace(out)
   163  	if out != "/root" {
   164  		c.Errorf("-w failed to set working directory")
   165  	}
   166  
   167  	out, _ = dockerCmd(c, "run", "--workdir", "/root", "busybox", "pwd")
   168  	out = strings.TrimSpace(out)
   169  	if out != "/root" {
   170  		c.Errorf("--workdir failed to set working directory")
   171  	}
   172  }
   173  
   174  // pinging Google's DNS resolver should fail when we disable the networking
   175  func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) {
   176  	out, exitCode, err := dockerCmdWithError(c, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8")
   177  	if err != nil && exitCode != 1 {
   178  		c.Fatal(out, err)
   179  	}
   180  	if exitCode != 1 {
   181  		c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
   182  	}
   183  
   184  	out, exitCode, err = dockerCmdWithError(c, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8")
   185  	if err != nil && exitCode != 1 {
   186  		c.Fatal(out, err)
   187  	}
   188  	if exitCode != 1 {
   189  		c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8")
   190  	}
   191  }
   192  
   193  //test --link use container name to link target
   194  func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) {
   195  	dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox")
   196  
   197  	ip, err := inspectField("parent", "NetworkSettings.IPAddress")
   198  	c.Assert(err, check.IsNil)
   199  
   200  	out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts")
   201  	if !strings.Contains(out, ip+"	test") {
   202  		c.Fatalf("use a container name to link target failed")
   203  	}
   204  }
   205  
   206  //test --link use container id to link target
   207  func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) {
   208  	cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox")
   209  
   210  	cID = strings.TrimSpace(cID)
   211  	ip, err := inspectField(cID, "NetworkSettings.IPAddress")
   212  	c.Assert(err, check.IsNil)
   213  
   214  	out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts")
   215  	if !strings.Contains(out, ip+"	test") {
   216  		c.Fatalf("use a container id to link target failed")
   217  	}
   218  }
   219  
   220  // Issue 9677.
   221  func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) {
   222  	out, _, err := dockerCmdWithError(c, "--selinux-enabled", "run", "-i", "-t", "busybox", "true")
   223  	if err != nil {
   224  		if !strings.Contains(out, "must follow the 'docker daemon' command") && // daemon
   225  			!strings.Contains(out, "flag provided but not defined: --selinux-enabled") { // no daemon (client-only)
   226  			c.Fatal(err, out)
   227  		}
   228  	}
   229  }
   230  
   231  // Regression test for #4979
   232  func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) {
   233  	out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file")
   234  	if exitCode != 0 {
   235  		c.Fatal("1", out, exitCode)
   236  	}
   237  
   238  	out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file")
   239  	if exitCode != 0 {
   240  		c.Fatal("2", out, exitCode)
   241  	}
   242  }
   243  
   244  // Volume path is a symlink which also exists on the host, and the host side is a file not a dir
   245  // But the volume call is just a normal volume, not a bind mount
   246  func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) {
   247  	testRequires(c, SameHostDaemon)
   248  	testRequires(c, NativeExecDriver)
   249  	name := "test-volume-symlink"
   250  
   251  	dir, err := ioutil.TempDir("", name)
   252  	if err != nil {
   253  		c.Fatal(err)
   254  	}
   255  	defer os.RemoveAll(dir)
   256  
   257  	f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700)
   258  	if err != nil {
   259  		c.Fatal(err)
   260  	}
   261  	f.Close()
   262  
   263  	dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir)
   264  	if _, err := buildImage(name, dockerFile, false); err != nil {
   265  		c.Fatal(err)
   266  	}
   267  
   268  	dockerCmd(c, "run", "-v", "/test/test", name)
   269  }
   270  
   271  func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) {
   272  	if _, code, err := dockerCmdWithError(c, "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  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
   279  
   280  	if _, code, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 {
   281  		c.Fatalf("run should fail because volume is ro: exit code %d", code)
   282  	}
   283  }
   284  
   285  // Regression test for #1201
   286  func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) {
   287  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
   288  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file")
   289  
   290  	if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") {
   291  		c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out)
   292  	}
   293  
   294  	dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file")
   295  }
   296  
   297  func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) {
   298  	dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true")
   299  
   300  	// Expect this "rw" mode to be be ignored since the inherited volume is "ro"
   301  	if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil {
   302  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`")
   303  	}
   304  
   305  	dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true")
   306  
   307  	// Expect this to be read-only since both are "ro"
   308  	if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil {
   309  		c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`")
   310  	}
   311  }
   312  
   313  // Test for GH#10618
   314  func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) {
   315  	mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace"
   316  	mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace"
   317  
   318  	if out, _, err := dockerCmdWithError(c, "run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil {
   319  		c.Fatal("Expected error about duplicate volume definitions")
   320  	} else {
   321  		if !strings.Contains(out, "Duplicate bind mount") {
   322  			c.Fatalf("Expected 'duplicate volume' error, got %v", err)
   323  		}
   324  	}
   325  }
   326  
   327  // Test for #1351
   328  func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) {
   329  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo")
   330  	dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo")
   331  }
   332  
   333  func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) {
   334  	dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo")
   335  	dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar")
   336  	dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar")
   337  }
   338  
   339  // this tests verifies the ID format for the container
   340  func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) {
   341  	out, exit, err := dockerCmdWithError(c, "run", "-d", "busybox", "true")
   342  	if err != nil {
   343  		c.Fatal(err)
   344  	}
   345  	if exit != 0 {
   346  		c.Fatalf("expected exit code 0 received %d", exit)
   347  	}
   348  
   349  	match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n"))
   350  	if err != nil {
   351  		c.Fatal(err)
   352  	}
   353  	if !match {
   354  		c.Fatalf("Invalid container ID: %s", out)
   355  	}
   356  }
   357  
   358  // Test that creating a container with a volume doesn't crash. Regression test for #995.
   359  func (s *DockerSuite) TestRunCreateVolume(c *check.C) {
   360  	dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true")
   361  }
   362  
   363  // Test that creating a volume with a symlink in its path works correctly. Test for #5152.
   364  // Note that this bug happens only with symlinks with a target that starts with '/'.
   365  func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) {
   366  	image := "docker-test-createvolumewithsymlink"
   367  
   368  	buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-")
   369  	buildCmd.Stdin = strings.NewReader(`FROM busybox
   370  		RUN ln -s home /bar`)
   371  	buildCmd.Dir = workingDirectory
   372  	err := buildCmd.Run()
   373  	if err != nil {
   374  		c.Fatalf("could not build '%s': %v", image, err)
   375  	}
   376  
   377  	_, exitCode, err := dockerCmdWithError(c, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo")
   378  	if err != nil || exitCode != 0 {
   379  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   380  	}
   381  
   382  	volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo")
   383  	if err != nil {
   384  		c.Fatalf("[inspect] err: %v", err)
   385  	}
   386  
   387  	_, exitCode, err = dockerCmdWithError(c, "rm", "-v", "test-createvolumewithsymlink")
   388  	if err != nil || exitCode != 0 {
   389  		c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode)
   390  	}
   391  
   392  	_, err = os.Stat(volPath)
   393  	if !os.IsNotExist(err) {
   394  		c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath)
   395  	}
   396  }
   397  
   398  // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`.
   399  func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) {
   400  	name := "docker-test-volumesfromsymlinkpath"
   401  
   402  	buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-")
   403  	buildCmd.Stdin = strings.NewReader(`FROM busybox
   404  		RUN ln -s home /foo
   405  		VOLUME ["/foo/bar"]`)
   406  	buildCmd.Dir = workingDirectory
   407  	err := buildCmd.Run()
   408  	if err != nil {
   409  		c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err)
   410  	}
   411  
   412  	_, exitCode, err := dockerCmdWithError(c, "run", "--name", "test-volumesfromsymlinkpath", name)
   413  	if err != nil || exitCode != 0 {
   414  		c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode)
   415  	}
   416  
   417  	_, exitCode, err = dockerCmdWithError(c, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar")
   418  	if err != nil || exitCode != 0 {
   419  		c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode)
   420  	}
   421  }
   422  
   423  func (s *DockerSuite) TestRunExitCode(c *check.C) {
   424  	_, exit, err := dockerCmdWithError(c, "run", "busybox", "/bin/sh", "-c", "exit 72")
   425  	if err == nil {
   426  		c.Fatal("should not have a non nil error")
   427  	}
   428  	if exit != 72 {
   429  		c.Fatalf("expected exit code 72 received %d", exit)
   430  	}
   431  }
   432  
   433  func (s *DockerSuite) TestRunUserDefaultsToRoot(c *check.C) {
   434  	out, _ := dockerCmd(c, "run", "busybox", "id")
   435  	if !strings.Contains(out, "uid=0(root) gid=0(root)") {
   436  		c.Fatalf("expected root user got %s", out)
   437  	}
   438  }
   439  
   440  func (s *DockerSuite) TestRunUserByName(c *check.C) {
   441  	out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id")
   442  	if !strings.Contains(out, "uid=0(root) gid=0(root)") {
   443  		c.Fatalf("expected root user got %s", out)
   444  	}
   445  }
   446  
   447  func (s *DockerSuite) TestRunUserByID(c *check.C) {
   448  	out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id")
   449  	if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") {
   450  		c.Fatalf("expected daemon user got %s", out)
   451  	}
   452  }
   453  
   454  func (s *DockerSuite) TestRunUserByIDBig(c *check.C) {
   455  	out, _, err := dockerCmdWithError(c, "run", "-u", "2147483648", "busybox", "id")
   456  	if err == nil {
   457  		c.Fatal("No error, but must be.", out)
   458  	}
   459  	if !strings.Contains(out, "Uids and gids must be in range") {
   460  		c.Fatalf("expected error about uids range, got %s", out)
   461  	}
   462  }
   463  
   464  func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) {
   465  	out, _, err := dockerCmdWithError(c, "run", "-u", "-1", "busybox", "id")
   466  	if err == nil {
   467  		c.Fatal("No error, but must be.", out)
   468  	}
   469  	if !strings.Contains(out, "Uids and gids must be in range") {
   470  		c.Fatalf("expected error about uids range, got %s", out)
   471  	}
   472  }
   473  
   474  func (s *DockerSuite) TestRunUserByIDZero(c *check.C) {
   475  	out, _, err := dockerCmdWithError(c, "run", "-u", "0", "busybox", "id")
   476  	if err != nil {
   477  		c.Fatal(err, out)
   478  	}
   479  	if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") {
   480  		c.Fatalf("expected daemon user got %s", out)
   481  	}
   482  }
   483  
   484  func (s *DockerSuite) TestRunUserNotFound(c *check.C) {
   485  	_, _, err := dockerCmdWithError(c, "run", "-u", "notme", "busybox", "id")
   486  	if err == nil {
   487  		c.Fatal("unknown user should cause container to fail")
   488  	}
   489  }
   490  
   491  func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) {
   492  	group := sync.WaitGroup{}
   493  	group.Add(2)
   494  
   495  	errChan := make(chan error, 2)
   496  	for i := 0; i < 2; i++ {
   497  		go func() {
   498  			defer group.Done()
   499  			_, _, err := dockerCmdWithError(c, "run", "busybox", "sleep", "2")
   500  			errChan <- err
   501  		}()
   502  	}
   503  
   504  	group.Wait()
   505  	close(errChan)
   506  
   507  	for err := range errChan {
   508  		c.Assert(err, check.IsNil)
   509  	}
   510  }
   511  
   512  func (s *DockerSuite) TestRunEnvironment(c *check.C) {
   513  	cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env")
   514  	cmd.Env = append(os.Environ(),
   515  		"TRUE=false",
   516  		"TRICKY=tri\ncky\n",
   517  	)
   518  
   519  	out, _, err := runCommandWithOutput(cmd)
   520  	if err != nil {
   521  		c.Fatal(err, out)
   522  	}
   523  
   524  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   525  	actualEnv := []string{}
   526  	for i := range actualEnvLxc {
   527  		if actualEnvLxc[i] != "container=lxc" {
   528  			actualEnv = append(actualEnv, actualEnvLxc[i])
   529  		}
   530  	}
   531  	sort.Strings(actualEnv)
   532  
   533  	goodEnv := []string{
   534  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   535  		"HOSTNAME=testing",
   536  		"FALSE=true",
   537  		"TRUE=false",
   538  		"TRICKY=tri",
   539  		"cky",
   540  		"",
   541  		"HOME=/root",
   542  	}
   543  	sort.Strings(goodEnv)
   544  	if len(goodEnv) != len(actualEnv) {
   545  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   546  	}
   547  	for i := range goodEnv {
   548  		if actualEnv[i] != goodEnv[i] {
   549  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   550  		}
   551  	}
   552  }
   553  
   554  func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) {
   555  	// Test to make sure that when we use -e on env vars that are
   556  	// not set in our local env that they're removed (if present) in
   557  	// the container
   558  
   559  	cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env")
   560  	cmd.Env = appendBaseEnv([]string{})
   561  
   562  	out, _, err := runCommandWithOutput(cmd)
   563  	if err != nil {
   564  		c.Fatal(err, out)
   565  	}
   566  
   567  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   568  	actualEnv := []string{}
   569  	for i := range actualEnvLxc {
   570  		if actualEnvLxc[i] != "container=lxc" {
   571  			actualEnv = append(actualEnv, actualEnvLxc[i])
   572  		}
   573  	}
   574  	sort.Strings(actualEnv)
   575  
   576  	goodEnv := []string{
   577  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   578  		"HOME=/root",
   579  	}
   580  	sort.Strings(goodEnv)
   581  	if len(goodEnv) != len(actualEnv) {
   582  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   583  	}
   584  	for i := range goodEnv {
   585  		if actualEnv[i] != goodEnv[i] {
   586  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   587  		}
   588  	}
   589  }
   590  
   591  func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) {
   592  	// Test to make sure that when we use -e on env vars that are
   593  	// already in the env that we're overriding them
   594  
   595  	cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env")
   596  	cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"})
   597  
   598  	out, _, err := runCommandWithOutput(cmd)
   599  	if err != nil {
   600  		c.Fatal(err, out)
   601  	}
   602  
   603  	actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n")
   604  	actualEnv := []string{}
   605  	for i := range actualEnvLxc {
   606  		if actualEnvLxc[i] != "container=lxc" {
   607  			actualEnv = append(actualEnv, actualEnvLxc[i])
   608  		}
   609  	}
   610  	sort.Strings(actualEnv)
   611  
   612  	goodEnv := []string{
   613  		"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
   614  		"HOME=/root2",
   615  		"HOSTNAME=bar",
   616  	}
   617  	sort.Strings(goodEnv)
   618  	if len(goodEnv) != len(actualEnv) {
   619  		c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", "))
   620  	}
   621  	for i := range goodEnv {
   622  		if actualEnv[i] != goodEnv[i] {
   623  			c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i])
   624  		}
   625  	}
   626  }
   627  
   628  func (s *DockerSuite) TestRunContainerNetwork(c *check.C) {
   629  	dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1")
   630  }
   631  
   632  func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) {
   633  	dockerCmd(c, "run", "--name", "linked", "busybox", "true")
   634  
   635  	_, _, err := dockerCmdWithError(c, "run", "--net=host", "--link", "linked:linked", "busybox", "true")
   636  	if err == nil {
   637  		c.Fatal("Expected error")
   638  	}
   639  }
   640  
   641  // #7851 hostname outside container shows FQDN, inside only shortname
   642  // For testing purposes it is not required to set host's hostname directly
   643  // and use "--net=host" (as the original issue submitter did), as the same
   644  // codepath is executed with "docker run -h <hostname>".  Both were manually
   645  // tested, but this testcase takes the simpler path of using "run -h .."
   646  func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) {
   647  	out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname")
   648  	if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" {
   649  		c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual)
   650  	}
   651  }
   652  
   653  func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
   654  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   655  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   656  		c.Fatalf("expected output ok received %s", actual)
   657  	}
   658  }
   659  
   660  func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
   661  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   662  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   663  		c.Fatalf("expected output ok received %s", actual)
   664  	}
   665  }
   666  
   667  func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) {
   668  	out, _, err := dockerCmdWithError(c, "run", "--cap-drop=CHPASS", "busybox", "ls")
   669  	if err == nil {
   670  		c.Fatal(err, out)
   671  	}
   672  }
   673  
   674  func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) {
   675  	out, _, err := dockerCmdWithError(c, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   676  
   677  	if err == nil {
   678  		c.Fatal(err, out)
   679  	}
   680  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   681  		c.Fatalf("expected output not ok received %s", actual)
   682  	}
   683  }
   684  
   685  func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) {
   686  	out, _, err := dockerCmdWithError(c, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   687  
   688  	if err == nil {
   689  		c.Fatal(err, out)
   690  	}
   691  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   692  		c.Fatalf("expected output not ok received %s", actual)
   693  	}
   694  }
   695  
   696  func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) {
   697  	out, _, err := dockerCmdWithError(c, "run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   698  	if err == nil {
   699  		c.Fatal(err, out)
   700  	}
   701  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   702  		c.Fatalf("expected output not ok received %s", actual)
   703  	}
   704  }
   705  
   706  func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) {
   707  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
   708  
   709  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   710  		c.Fatalf("expected output ok received %s", actual)
   711  	}
   712  }
   713  
   714  func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) {
   715  	out, _, err := dockerCmdWithError(c, "run", "--cap-add=CHPASS", "busybox", "ls")
   716  	if err == nil {
   717  		c.Fatal(err, out)
   718  	}
   719  }
   720  
   721  func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) {
   722  	out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   723  
   724  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   725  		c.Fatalf("expected output ok received %s", actual)
   726  	}
   727  }
   728  
   729  func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) {
   730  	out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   731  
   732  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   733  		c.Fatalf("expected output ok received %s", actual)
   734  	}
   735  }
   736  
   737  func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) {
   738  	out, _, err := dockerCmdWithError(c, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok")
   739  	if err == nil {
   740  		c.Fatal(err, out)
   741  	}
   742  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   743  		c.Fatalf("expected output not ok received %s", actual)
   744  	}
   745  }
   746  
   747  func (s *DockerSuite) TestRunGroupAdd(c *check.C) {
   748  	testRequires(c, NativeExecDriver)
   749  	out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id")
   750  
   751  	groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777"
   752  	if actual := strings.Trim(out, "\r\n"); actual != groupsList {
   753  		c.Fatalf("expected output %s received %s", groupsList, actual)
   754  	}
   755  }
   756  
   757  func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
   758  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
   759  
   760  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
   761  		c.Fatalf("expected output ok received %s", actual)
   762  	}
   763  }
   764  
   765  func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
   766  	out, _, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
   767  
   768  	if err == nil {
   769  		c.Fatal(err, out)
   770  	}
   771  	if actual := strings.Trim(out, "\r\n"); actual == "ok" {
   772  		c.Fatalf("expected output not ok received %s", actual)
   773  	}
   774  }
   775  
   776  func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) {
   777  	if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 {
   778  		c.Fatal("sys should not be writable in a non privileged container")
   779  	}
   780  }
   781  
   782  func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) {
   783  	if _, code, err := dockerCmdWithError(c, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 {
   784  		c.Fatalf("sys should be writable in privileged container")
   785  	}
   786  }
   787  
   788  func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) {
   789  	if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 {
   790  		c.Fatal("proc should not be writable in a non privileged container")
   791  	}
   792  }
   793  
   794  func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) {
   795  	if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 {
   796  		c.Fatalf("proc should be writable in privileged container")
   797  	}
   798  }
   799  
   800  func (s *DockerSuite) TestRunWithCpuset(c *check.C) {
   801  	if _, code := dockerCmd(c, "run", "--cpuset", "0", "busybox", "true"); code != 0 {
   802  		c.Fatalf("container should run successfully with cpuset of 0")
   803  	}
   804  }
   805  
   806  func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
   807  	if _, code := dockerCmd(c, "run", "--cpuset-cpus", "0", "busybox", "true"); code != 0 {
   808  		c.Fatalf("container should run successfully with cpuset-cpus of 0")
   809  	}
   810  }
   811  
   812  func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
   813  	if _, code := dockerCmd(c, "run", "--cpuset-mems", "0", "busybox", "true"); code != 0 {
   814  		c.Fatalf("container should run successfully with cpuset-mems of 0")
   815  	}
   816  }
   817  
   818  func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
   819  	if _, code := dockerCmd(c, "run", "--blkio-weight", "300", "busybox", "true"); code != 0 {
   820  		c.Fatalf("container should run successfully with blkio-weight of 300")
   821  	}
   822  }
   823  
   824  func (s *DockerSuite) TestRunWithBlkioInvalidWeight(c *check.C) {
   825  	if _, _, err := dockerCmdWithError(c, "run", "--blkio-weight", "5", "busybox", "true"); err == nil {
   826  		c.Fatalf("run with invalid blkio-weight should failed")
   827  	}
   828  }
   829  
   830  func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) {
   831  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null")
   832  	deviceLineFields := strings.Fields(out)
   833  	deviceLineFields[6] = ""
   834  	deviceLineFields[7] = ""
   835  	deviceLineFields[8] = ""
   836  	expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"}
   837  
   838  	if !(reflect.DeepEqual(deviceLineFields, expected)) {
   839  		c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out)
   840  	}
   841  }
   842  
   843  func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) {
   844  	out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero")
   845  	if actual := strings.Trim(out, "\r\n"); actual[0] == '0' {
   846  		c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual)
   847  	}
   848  }
   849  
   850  func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) {
   851  	dockerCmd(c, "run", "busybox", "chroot", "/", "true")
   852  }
   853  
   854  func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) {
   855  	out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo")
   856  	if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" {
   857  		c.Fatalf("expected output /dev/nulo, received %s", actual)
   858  	}
   859  }
   860  
   861  func (s *DockerSuite) TestRunModeHostname(c *check.C) {
   862  	testRequires(c, SameHostDaemon)
   863  
   864  	out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname")
   865  
   866  	if actual := strings.Trim(out, "\r\n"); actual != "testhostname" {
   867  		c.Fatalf("expected 'testhostname', but says: %q", actual)
   868  	}
   869  
   870  	out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname")
   871  
   872  	hostname, err := os.Hostname()
   873  	if err != nil {
   874  		c.Fatal(err)
   875  	}
   876  	if actual := strings.Trim(out, "\r\n"); actual != hostname {
   877  		c.Fatalf("expected %q, but says: %q", hostname, actual)
   878  	}
   879  }
   880  
   881  func (s *DockerSuite) TestRunRootWorkdir(c *check.C) {
   882  	out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd")
   883  	if out != "/\n" {
   884  		c.Fatalf("pwd returned %q (expected /\\n)", s)
   885  	}
   886  }
   887  
   888  func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) {
   889  	dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host")
   890  }
   891  
   892  func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) {
   893  	out, _, err := dockerCmdWithError(c, "run", "-v", "/:/", "busybox", "ls", "/host")
   894  	if err == nil {
   895  		c.Fatal(out, err)
   896  	}
   897  }
   898  
   899  // Verify that a container gets default DNS when only localhost resolvers exist
   900  func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) {
   901  	testRequires(c, SameHostDaemon)
   902  
   903  	// preserve original resolv.conf for restoring after test
   904  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
   905  	if os.IsNotExist(err) {
   906  		c.Fatalf("/etc/resolv.conf does not exist")
   907  	}
   908  	// defer restored original conf
   909  	defer func() {
   910  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
   911  			c.Fatal(err)
   912  		}
   913  	}()
   914  
   915  	// test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost
   916  	// 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by
   917  	// GetNameservers(), leading to a replacement of nameservers with the default set
   918  	tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1")
   919  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
   920  		c.Fatal(err)
   921  	}
   922  
   923  	actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
   924  	// check that the actual defaults are appended to the commented out
   925  	// localhost resolver (which should be preserved)
   926  	// NOTE: if we ever change the defaults from google dns, this will break
   927  	expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
   928  	if actual != expected {
   929  		c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
   930  	}
   931  }
   932  
   933  func (s *DockerSuite) TestRunDnsOptions(c *check.C) {
   934  	out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
   935  
   936  	// The client will get a warning on stderr when setting DNS to a localhost address; verify this:
   937  	if !strings.Contains(stderr, "Localhost DNS setting") {
   938  		c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr)
   939  	}
   940  
   941  	actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
   942  	if actual != "nameserver 127.0.0.1 search mydomain" {
   943  		c.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual)
   944  	}
   945  
   946  	out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf")
   947  
   948  	actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
   949  	if actual != "nameserver 127.0.0.1" {
   950  		c.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual)
   951  	}
   952  }
   953  
   954  func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) {
   955  	testRequires(c, SameHostDaemon)
   956  
   957  	origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
   958  	if os.IsNotExist(err) {
   959  		c.Fatalf("/etc/resolv.conf does not exist")
   960  	}
   961  
   962  	hostNamservers := resolvconf.GetNameservers(origResolvConf)
   963  	hostSearch := resolvconf.GetSearchDomains(origResolvConf)
   964  
   965  	var out string
   966  	out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf")
   967  
   968  	if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" {
   969  		c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0]))
   970  	}
   971  
   972  	actualSearch := resolvconf.GetSearchDomains([]byte(out))
   973  	if len(actualSearch) != len(hostSearch) {
   974  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
   975  	}
   976  	for i := range actualSearch {
   977  		if actualSearch[i] != hostSearch[i] {
   978  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
   979  		}
   980  	}
   981  
   982  	out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf")
   983  
   984  	actualNameservers := resolvconf.GetNameservers([]byte(out))
   985  	if len(actualNameservers) != len(hostNamservers) {
   986  		c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers))
   987  	}
   988  	for i := range actualNameservers {
   989  		if actualNameservers[i] != hostNamservers[i] {
   990  			c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i])
   991  		}
   992  	}
   993  
   994  	if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" {
   995  		c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0]))
   996  	}
   997  
   998  	// test with file
   999  	tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1")
  1000  	if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil {
  1001  		c.Fatal(err)
  1002  	}
  1003  	// put the old resolvconf back
  1004  	defer func() {
  1005  		if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil {
  1006  			c.Fatal(err)
  1007  		}
  1008  	}()
  1009  
  1010  	resolvConf, err := ioutil.ReadFile("/etc/resolv.conf")
  1011  	if os.IsNotExist(err) {
  1012  		c.Fatalf("/etc/resolv.conf does not exist")
  1013  	}
  1014  
  1015  	hostNamservers = resolvconf.GetNameservers(resolvConf)
  1016  	hostSearch = resolvconf.GetSearchDomains(resolvConf)
  1017  
  1018  	out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf")
  1019  	if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 {
  1020  		c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers)
  1021  	}
  1022  
  1023  	actualSearch = resolvconf.GetSearchDomains([]byte(out))
  1024  	if len(actualSearch) != len(hostSearch) {
  1025  		c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch))
  1026  	}
  1027  	for i := range actualSearch {
  1028  		if actualSearch[i] != hostSearch[i] {
  1029  			c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i])
  1030  		}
  1031  	}
  1032  }
  1033  
  1034  // Test to see if a non-root user can resolve a DNS name and reach out to it. Also
  1035  // check if the container resolv.conf file has atleast 0644 perm.
  1036  func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) {
  1037  	testRequires(c, SameHostDaemon, Network)
  1038  
  1039  	dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "apt.dockerproject.org")
  1040  
  1041  	cID, err := getIDByName("testperm")
  1042  	if err != nil {
  1043  		c.Fatal(err)
  1044  	}
  1045  
  1046  	fmode := (os.FileMode)(0644)
  1047  	finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf"))
  1048  	if err != nil {
  1049  		c.Fatal(err)
  1050  	}
  1051  
  1052  	if (finfo.Mode() & fmode) != fmode {
  1053  		c.Fatalf("Expected container resolv.conf mode to be atleast %s, instead got %s", fmode.String(), finfo.Mode().String())
  1054  	}
  1055  }
  1056  
  1057  // Test if container resolv.conf gets updated the next time it restarts
  1058  // if host /etc/resolv.conf has changed. This only applies if the container
  1059  // uses the host's /etc/resolv.conf and does not have any dns options provided.
  1060  func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) {
  1061  	testRequires(c, SameHostDaemon)
  1062  
  1063  	tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78")
  1064  	tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1")
  1065  
  1066  	//take a copy of resolv.conf for restoring after test completes
  1067  	resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf")
  1068  	if err != nil {
  1069  		c.Fatal(err)
  1070  	}
  1071  
  1072  	// This test case is meant to test monitoring resolv.conf when it is
  1073  	// a regular file not a bind mounc. So we unmount resolv.conf and replace
  1074  	// it with a file containing the original settings.
  1075  	cmd := exec.Command("umount", "/etc/resolv.conf")
  1076  	if _, err = runCommand(cmd); err != nil {
  1077  		c.Fatal(err)
  1078  	}
  1079  
  1080  	//cleanup
  1081  	defer func() {
  1082  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1083  			c.Fatal(err)
  1084  		}
  1085  	}()
  1086  
  1087  	//1. test that a restarting container gets an updated resolv.conf
  1088  	dockerCmd(c, "run", "--name='first'", "busybox", "true")
  1089  	containerID1, err := getIDByName("first")
  1090  	if err != nil {
  1091  		c.Fatal(err)
  1092  	}
  1093  
  1094  	// replace resolv.conf with our temporary copy
  1095  	bytesResolvConf := []byte(tmpResolvConf)
  1096  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1097  		c.Fatal(err)
  1098  	}
  1099  
  1100  	// start the container again to pickup changes
  1101  	dockerCmd(c, "start", "first")
  1102  
  1103  	// check for update in container
  1104  	containerResolv, err := readContainerFile(containerID1, "resolv.conf")
  1105  	if err != nil {
  1106  		c.Fatal(err)
  1107  	}
  1108  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1109  		c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv))
  1110  	}
  1111  
  1112  	/*	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1113  		if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1114  						c.Fatal(err)
  1115  								} */
  1116  	//2. test that a restarting container does not receive resolv.conf updates
  1117  	//   if it modified the container copy of the starting point resolv.conf
  1118  	dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf")
  1119  	containerID2, err := getIDByName("second")
  1120  	if err != nil {
  1121  		c.Fatal(err)
  1122  	}
  1123  
  1124  	//make a change to resolv.conf (in this case replacing our tmp copy with orig copy)
  1125  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1126  		c.Fatal(err)
  1127  	}
  1128  
  1129  	// start the container again
  1130  	dockerCmd(c, "start", "second")
  1131  
  1132  	// check for update in container
  1133  	containerResolv, err = readContainerFile(containerID2, "resolv.conf")
  1134  	if err != nil {
  1135  		c.Fatal(err)
  1136  	}
  1137  
  1138  	if bytes.Equal(containerResolv, resolvConfSystem) {
  1139  		c.Fatalf("Restarting  a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem))
  1140  	}
  1141  
  1142  	//3. test that a running container's resolv.conf is not modified while running
  1143  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1144  	runningContainerID := strings.TrimSpace(out)
  1145  
  1146  	// replace resolv.conf
  1147  	if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1148  		c.Fatal(err)
  1149  	}
  1150  
  1151  	// check for update in container
  1152  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1153  	if err != nil {
  1154  		c.Fatal(err)
  1155  	}
  1156  
  1157  	if bytes.Equal(containerResolv, bytesResolvConf) {
  1158  		c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv))
  1159  	}
  1160  
  1161  	//4. test that a running container's resolv.conf is updated upon restart
  1162  	//   (the above container is still running..)
  1163  	dockerCmd(c, "restart", runningContainerID)
  1164  
  1165  	// check for update in container
  1166  	containerResolv, err = readContainerFile(runningContainerID, "resolv.conf")
  1167  	if err != nil {
  1168  		c.Fatal(err)
  1169  	}
  1170  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1171  		c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv))
  1172  	}
  1173  
  1174  	//5. test that additions of a localhost resolver are cleaned from
  1175  	//   host resolv.conf before updating container's resolv.conf copies
  1176  
  1177  	// replace resolv.conf with a localhost-only nameserver copy
  1178  	bytesResolvConf = []byte(tmpLocalhostResolvConf)
  1179  	if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil {
  1180  		c.Fatal(err)
  1181  	}
  1182  
  1183  	// start the container again to pickup changes
  1184  	dockerCmd(c, "start", "first")
  1185  
  1186  	// our first exited container ID should have been updated, but with default DNS
  1187  	// after the cleanup of resolv.conf found only a localhost nameserver:
  1188  	containerResolv, err = readContainerFile(containerID1, "resolv.conf")
  1189  	if err != nil {
  1190  		c.Fatal(err)
  1191  	}
  1192  
  1193  	expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4"
  1194  	if !bytes.Equal(containerResolv, []byte(expected)) {
  1195  		c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv))
  1196  	}
  1197  
  1198  	//6. Test that replacing (as opposed to modifying) resolv.conf triggers an update
  1199  	//   of containers' resolv.conf.
  1200  
  1201  	// Restore the original resolv.conf
  1202  	if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil {
  1203  		c.Fatal(err)
  1204  	}
  1205  
  1206  	// Run the container so it picks up the old settings
  1207  	dockerCmd(c, "run", "--name='third'", "busybox", "true")
  1208  	containerID3, err := getIDByName("third")
  1209  	if err != nil {
  1210  		c.Fatal(err)
  1211  	}
  1212  
  1213  	// Create a modified resolv.conf.aside and override resolv.conf with it
  1214  	bytesResolvConf = []byte(tmpResolvConf)
  1215  	if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil {
  1216  		c.Fatal(err)
  1217  	}
  1218  
  1219  	err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf")
  1220  	if err != nil {
  1221  		c.Fatal(err)
  1222  	}
  1223  
  1224  	// start the container again to pickup changes
  1225  	dockerCmd(c, "start", "third")
  1226  
  1227  	// check for update in container
  1228  	containerResolv, err = readContainerFile(containerID3, "resolv.conf")
  1229  	if err != nil {
  1230  		c.Fatal(err)
  1231  	}
  1232  	if !bytes.Equal(containerResolv, bytesResolvConf) {
  1233  		c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv))
  1234  	}
  1235  
  1236  	//cleanup, restore original resolv.conf happens in defer func()
  1237  }
  1238  
  1239  func (s *DockerSuite) TestRunAddHost(c *check.C) {
  1240  	out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts")
  1241  
  1242  	actual := strings.Trim(out, "\r\n")
  1243  	if actual != "86.75.30.9\textra" {
  1244  		c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual)
  1245  	}
  1246  }
  1247  
  1248  // Regression test for #6983
  1249  func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) {
  1250  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true")
  1251  	if exitCode != 0 {
  1252  		c.Fatalf("Container should have exited with error code 0")
  1253  	}
  1254  }
  1255  
  1256  // Regression test for #6983
  1257  func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) {
  1258  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true")
  1259  	if exitCode != 0 {
  1260  		c.Fatalf("Container should have exited with error code 0")
  1261  	}
  1262  }
  1263  
  1264  // Regression test for #6983
  1265  func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) {
  1266  	_, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true")
  1267  	if exitCode != 0 {
  1268  		c.Fatalf("Container should have exited with error code 0")
  1269  	}
  1270  }
  1271  
  1272  // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode
  1273  // but using --attach instead of -a to make sure we read the flag correctly
  1274  func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) {
  1275  	cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true")
  1276  	_, stderr, _, err := runCommandWithStdoutStderr(cmd)
  1277  	if err == nil {
  1278  		c.Fatal("Container should have exited with error code different than 0")
  1279  	} else if !strings.Contains(stderr, "Conflicting options: -a and -d") {
  1280  		c.Fatal("Should have been returned an error with conflicting options -a and -d")
  1281  	}
  1282  }
  1283  
  1284  func (s *DockerSuite) TestRunState(c *check.C) {
  1285  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1286  
  1287  	id := strings.TrimSpace(out)
  1288  	state, err := inspectField(id, "State.Running")
  1289  	c.Assert(err, check.IsNil)
  1290  	if state != "true" {
  1291  		c.Fatal("Container state is 'not running'")
  1292  	}
  1293  	pid1, err := inspectField(id, "State.Pid")
  1294  	c.Assert(err, check.IsNil)
  1295  	if pid1 == "0" {
  1296  		c.Fatal("Container state Pid 0")
  1297  	}
  1298  
  1299  	dockerCmd(c, "stop", id)
  1300  	state, err = inspectField(id, "State.Running")
  1301  	c.Assert(err, check.IsNil)
  1302  	if state != "false" {
  1303  		c.Fatal("Container state is 'running'")
  1304  	}
  1305  	pid2, err := inspectField(id, "State.Pid")
  1306  	c.Assert(err, check.IsNil)
  1307  	if pid2 == pid1 {
  1308  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1309  	}
  1310  
  1311  	dockerCmd(c, "start", id)
  1312  	state, err = inspectField(id, "State.Running")
  1313  	c.Assert(err, check.IsNil)
  1314  	if state != "true" {
  1315  		c.Fatal("Container state is 'not running'")
  1316  	}
  1317  	pid3, err := inspectField(id, "State.Pid")
  1318  	c.Assert(err, check.IsNil)
  1319  	if pid3 == pid1 {
  1320  		c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1)
  1321  	}
  1322  }
  1323  
  1324  // Test for #1737
  1325  func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) {
  1326  	name := "testrunvolumesuidgid"
  1327  	_, err := buildImage(name,
  1328  		`FROM busybox
  1329  		RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd
  1330  		RUN echo 'dockerio:x:1001:' >> /etc/group
  1331  		RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`,
  1332  		true)
  1333  	if err != nil {
  1334  		c.Fatal(err)
  1335  	}
  1336  
  1337  	// Test that the uid and gid is copied from the image to the volume
  1338  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'")
  1339  	out = strings.TrimSpace(out)
  1340  	if out != "dockerio:dockerio" {
  1341  		c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out)
  1342  	}
  1343  }
  1344  
  1345  // Test for #1582
  1346  func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) {
  1347  	name := "testruncopyvolumecontent"
  1348  	_, err := buildImage(name,
  1349  		`FROM busybox
  1350  		RUN mkdir -p /hello/local && echo hello > /hello/local/world`,
  1351  		true)
  1352  	if err != nil {
  1353  		c.Fatal(err)
  1354  	}
  1355  
  1356  	// Test that the content is copied from the image to the volume
  1357  	out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello")
  1358  	if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) {
  1359  		c.Fatal("Container failed to transfer content to volume")
  1360  	}
  1361  }
  1362  
  1363  func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) {
  1364  	name := "testrunmdcleanuponentrypoint"
  1365  	if _, err := buildImage(name,
  1366  		`FROM busybox
  1367  		ENTRYPOINT ["echo"]
  1368  		CMD ["testingpoint"]`,
  1369  		true); err != nil {
  1370  		c.Fatal(err)
  1371  	}
  1372  
  1373  	out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name)
  1374  	if exit != 0 {
  1375  		c.Fatalf("expected exit code 0 received %d, out: %q", exit, out)
  1376  	}
  1377  	out = strings.TrimSpace(out)
  1378  	if out != "root" {
  1379  		c.Fatalf("Expected output root, got %q", out)
  1380  	}
  1381  }
  1382  
  1383  // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected
  1384  func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) {
  1385  	out, exit, err := dockerCmdWithError(c, "run", "-w", "/bin/cat", "busybox")
  1386  	if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) {
  1387  		c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err)
  1388  	}
  1389  }
  1390  
  1391  func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) {
  1392  	name := "testrunexitonstdinclose"
  1393  	runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat")
  1394  
  1395  	stdin, err := runCmd.StdinPipe()
  1396  	if err != nil {
  1397  		c.Fatal(err)
  1398  	}
  1399  	stdout, err := runCmd.StdoutPipe()
  1400  	if err != nil {
  1401  		c.Fatal(err)
  1402  	}
  1403  
  1404  	if err := runCmd.Start(); err != nil {
  1405  		c.Fatal(err)
  1406  	}
  1407  	if _, err := stdin.Write([]byte("hello\n")); err != nil {
  1408  		c.Fatal(err)
  1409  	}
  1410  
  1411  	r := bufio.NewReader(stdout)
  1412  	line, err := r.ReadString('\n')
  1413  	if err != nil {
  1414  		c.Fatal(err)
  1415  	}
  1416  	line = strings.TrimSpace(line)
  1417  	if line != "hello" {
  1418  		c.Fatalf("Output should be 'hello', got '%q'", line)
  1419  	}
  1420  	if err := stdin.Close(); err != nil {
  1421  		c.Fatal(err)
  1422  	}
  1423  	finish := make(chan error)
  1424  	go func() {
  1425  		finish <- runCmd.Wait()
  1426  		close(finish)
  1427  	}()
  1428  	select {
  1429  	case err := <-finish:
  1430  		c.Assert(err, check.IsNil)
  1431  	case <-time.After(1 * time.Second):
  1432  		c.Fatal("docker run failed to exit on stdin close")
  1433  	}
  1434  	state, err := inspectField(name, "State.Running")
  1435  	c.Assert(err, check.IsNil)
  1436  
  1437  	if state != "false" {
  1438  		c.Fatal("Container must be stopped after stdin closing")
  1439  	}
  1440  }
  1441  
  1442  // Test for #2267
  1443  func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) {
  1444  	name := "writehosts"
  1445  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts")
  1446  	if !strings.Contains(out, "test2267") {
  1447  		c.Fatal("/etc/hosts should contain 'test2267'")
  1448  	}
  1449  
  1450  	out, _ = dockerCmd(c, "diff", name)
  1451  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1452  		c.Fatal("diff should be empty")
  1453  	}
  1454  }
  1455  
  1456  func eqToBaseDiff(out string, c *check.C) bool {
  1457  	out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello")
  1458  	cID := strings.TrimSpace(out1)
  1459  
  1460  	baseDiff, _ := dockerCmd(c, "diff", cID)
  1461  	baseArr := strings.Split(baseDiff, "\n")
  1462  	sort.Strings(baseArr)
  1463  	outArr := strings.Split(out, "\n")
  1464  	sort.Strings(outArr)
  1465  	return sliceEq(baseArr, outArr)
  1466  }
  1467  
  1468  func sliceEq(a, b []string) bool {
  1469  	if len(a) != len(b) {
  1470  		return false
  1471  	}
  1472  
  1473  	for i := range a {
  1474  		if a[i] != b[i] {
  1475  			return false
  1476  		}
  1477  	}
  1478  
  1479  	return true
  1480  }
  1481  
  1482  // Test for #2267
  1483  func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) {
  1484  	name := "writehostname"
  1485  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname")
  1486  	if !strings.Contains(out, "test2267") {
  1487  		c.Fatal("/etc/hostname should contain 'test2267'")
  1488  	}
  1489  
  1490  	out, _ = dockerCmd(c, "diff", name)
  1491  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1492  		c.Fatal("diff should be empty")
  1493  	}
  1494  }
  1495  
  1496  // Test for #2267
  1497  func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) {
  1498  	name := "writeresolv"
  1499  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf")
  1500  	if !strings.Contains(out, "test2267") {
  1501  		c.Fatal("/etc/resolv.conf should contain 'test2267'")
  1502  	}
  1503  
  1504  	out, _ = dockerCmd(c, "diff", name)
  1505  	if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) {
  1506  		c.Fatal("diff should be empty")
  1507  	}
  1508  }
  1509  
  1510  func (s *DockerSuite) TestRunWithBadDevice(c *check.C) {
  1511  	name := "baddevice"
  1512  	out, _, err := dockerCmdWithError(c, "run", "--name", name, "--device", "/etc", "busybox", "true")
  1513  
  1514  	if err == nil {
  1515  		c.Fatal("Run should fail with bad device")
  1516  	}
  1517  	expected := `"/etc": not a device node`
  1518  	if !strings.Contains(out, expected) {
  1519  		c.Fatalf("Output should contain %q, actual out: %q", expected, out)
  1520  	}
  1521  }
  1522  
  1523  func (s *DockerSuite) TestRunEntrypoint(c *check.C) {
  1524  	name := "entrypoint"
  1525  	out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar")
  1526  
  1527  	expected := "foobar"
  1528  	if out != expected {
  1529  		c.Fatalf("Output should be %q, actual out: %q", expected, out)
  1530  	}
  1531  }
  1532  
  1533  func (s *DockerSuite) TestRunBindMounts(c *check.C) {
  1534  	testRequires(c, SameHostDaemon)
  1535  
  1536  	tmpDir, err := ioutil.TempDir("", "docker-test-container")
  1537  	if err != nil {
  1538  		c.Fatal(err)
  1539  	}
  1540  
  1541  	defer os.RemoveAll(tmpDir)
  1542  	writeFile(path.Join(tmpDir, "touch-me"), "", c)
  1543  
  1544  	// Test reading from a read-only bind mount
  1545  	out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp")
  1546  	if !strings.Contains(out, "touch-me") {
  1547  		c.Fatal("Container failed to read from bind mount")
  1548  	}
  1549  
  1550  	// test writing to bind mount
  1551  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla")
  1552  
  1553  	readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1554  
  1555  	// test mounting to an illegal destination directory
  1556  	_, _, err = dockerCmdWithError(c, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".")
  1557  	if err == nil {
  1558  		c.Fatal("Container bind mounted illegal directory")
  1559  	}
  1560  
  1561  	// test mount a file
  1562  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla")
  1563  	content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist
  1564  	expected := "yotta"
  1565  	if content != expected {
  1566  		c.Fatalf("Output should be %q, actual out: %q", expected, content)
  1567  	}
  1568  }
  1569  
  1570  // Ensure that CIDFile gets deleted if it's empty
  1571  // Perform this test by making `docker run` fail
  1572  func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) {
  1573  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1574  	if err != nil {
  1575  		c.Fatal(err)
  1576  	}
  1577  	defer os.RemoveAll(tmpDir)
  1578  	tmpCidFile := path.Join(tmpDir, "cid")
  1579  
  1580  	out, _, err := dockerCmdWithError(c, "run", "--cidfile", tmpCidFile, "emptyfs")
  1581  	if err == nil {
  1582  		c.Fatalf("Run without command must fail. out=%s", out)
  1583  	} else if !strings.Contains(out, "No command specified") {
  1584  		c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err)
  1585  	}
  1586  
  1587  	if _, err := os.Stat(tmpCidFile); err == nil {
  1588  		c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile)
  1589  	}
  1590  }
  1591  
  1592  // #2098 - Docker cidFiles only contain short version of the containerId
  1593  //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test"
  1594  // TestRunCidFile tests that run --cidfile returns the longid
  1595  func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) {
  1596  	tmpDir, err := ioutil.TempDir("", "TestRunCidFile")
  1597  	if err != nil {
  1598  		c.Fatal(err)
  1599  	}
  1600  	tmpCidFile := path.Join(tmpDir, "cid")
  1601  	defer os.RemoveAll(tmpDir)
  1602  
  1603  	out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true")
  1604  
  1605  	id := strings.TrimSpace(out)
  1606  	buffer, err := ioutil.ReadFile(tmpCidFile)
  1607  	if err != nil {
  1608  		c.Fatal(err)
  1609  	}
  1610  	cid := string(buffer)
  1611  	if len(cid) != 64 {
  1612  		c.Fatalf("--cidfile should be a long id, not %q", id)
  1613  	}
  1614  	if cid != id {
  1615  		c.Fatalf("cid must be equal to %s, got %s", id, cid)
  1616  	}
  1617  }
  1618  
  1619  func (s *DockerSuite) TestRunSetMacAddress(c *check.C) {
  1620  	mac := "12:34:56:78:9a:bc"
  1621  
  1622  	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}'")
  1623  
  1624  	actualMac := strings.TrimSpace(out)
  1625  	if actualMac != mac {
  1626  		c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac)
  1627  	}
  1628  }
  1629  
  1630  func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) {
  1631  	mac := "12:34:56:78:9a:bc"
  1632  	out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top")
  1633  
  1634  	id := strings.TrimSpace(out)
  1635  	inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress")
  1636  	c.Assert(err, check.IsNil)
  1637  	if inspectedMac != mac {
  1638  		c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac)
  1639  	}
  1640  }
  1641  
  1642  // test docker run use a invalid mac address
  1643  func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) {
  1644  	out, _, err := dockerCmdWithError(c, "run", "--mac-address", "92:d0:c6:0a:29", "busybox")
  1645  	//use a invalid mac address should with a error out
  1646  	if err == nil || !strings.Contains(out, "is not a valid mac address") {
  1647  		c.Fatalf("run with an invalid --mac-address should with error out")
  1648  	}
  1649  }
  1650  
  1651  func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) {
  1652  	testRequires(c, SameHostDaemon)
  1653  
  1654  	out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1655  
  1656  	id := strings.TrimSpace(out)
  1657  	ip, err := inspectField(id, "NetworkSettings.IPAddress")
  1658  	c.Assert(err, check.IsNil)
  1659  	iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip),
  1660  		"!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT")
  1661  	out, _, err = runCommandWithOutput(iptCmd)
  1662  	if err != nil {
  1663  		c.Fatal(err, out)
  1664  	}
  1665  	if err := deleteContainer(id); err != nil {
  1666  		c.Fatal(err)
  1667  	}
  1668  
  1669  	dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top")
  1670  }
  1671  
  1672  func (s *DockerSuite) TestRunPortInUse(c *check.C) {
  1673  	testRequires(c, SameHostDaemon)
  1674  
  1675  	port := "1234"
  1676  	dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1677  
  1678  	out, _, err := dockerCmdWithError(c, "run", "-d", "-p", port+":80", "busybox", "top")
  1679  	if err == nil {
  1680  		c.Fatalf("Binding on used port must fail")
  1681  	}
  1682  	if !strings.Contains(out, "port is already allocated") {
  1683  		c.Fatalf("Out must be about \"port is already allocated\", got %s", out)
  1684  	}
  1685  }
  1686  
  1687  // https://github.com/docker/docker/issues/12148
  1688  func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) {
  1689  	// allocate a dynamic port to get the most recent
  1690  	out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top")
  1691  
  1692  	id := strings.TrimSpace(out)
  1693  	out, _ = dockerCmd(c, "port", id, "80")
  1694  
  1695  	strPort := strings.Split(strings.TrimSpace(out), ":")[1]
  1696  	port, err := strconv.ParseInt(strPort, 10, 64)
  1697  	if err != nil {
  1698  		c.Fatalf("invalid port, got: %s, error: %s", strPort, err)
  1699  	}
  1700  
  1701  	// allocate a static port and a dynamic port together, with static port
  1702  	// takes the next recent port in dynamic port range.
  1703  	dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top")
  1704  }
  1705  
  1706  // Regression test for #7792
  1707  func (s *DockerSuite) TestRunMountOrdering(c *check.C) {
  1708  	testRequires(c, SameHostDaemon)
  1709  
  1710  	tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test")
  1711  	if err != nil {
  1712  		c.Fatal(err)
  1713  	}
  1714  	defer os.RemoveAll(tmpDir)
  1715  
  1716  	tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2")
  1717  	if err != nil {
  1718  		c.Fatal(err)
  1719  	}
  1720  	defer os.RemoveAll(tmpDir2)
  1721  
  1722  	// Create a temporary tmpfs mounc.
  1723  	fooDir := filepath.Join(tmpDir, "foo")
  1724  	if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil {
  1725  		c.Fatalf("failed to mkdir at %s - %s", fooDir, err)
  1726  	}
  1727  
  1728  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil {
  1729  		c.Fatal(err)
  1730  	}
  1731  
  1732  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil {
  1733  		c.Fatal(err)
  1734  	}
  1735  
  1736  	if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil {
  1737  		c.Fatal(err)
  1738  	}
  1739  
  1740  	dockerCmd(c, "run",
  1741  		"-v", fmt.Sprintf("%s:/tmp", tmpDir),
  1742  		"-v", fmt.Sprintf("%s:/tmp/foo", fooDir),
  1743  		"-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2),
  1744  		"-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir),
  1745  		"busybox:latest", "sh", "-c",
  1746  		"ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me")
  1747  }
  1748  
  1749  // Regression test for https://github.com/docker/docker/issues/8259
  1750  func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) {
  1751  	testRequires(c, SameHostDaemon)
  1752  
  1753  	tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink")
  1754  	if err != nil {
  1755  		c.Fatal(err)
  1756  	}
  1757  	defer os.RemoveAll(tmpDir)
  1758  
  1759  	linkPath := os.TempDir() + "/testlink2"
  1760  	if err := os.Symlink(tmpDir, linkPath); err != nil {
  1761  		c.Fatal(err)
  1762  	}
  1763  	defer os.RemoveAll(linkPath)
  1764  
  1765  	// Create first container
  1766  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1767  
  1768  	// Create second container with same symlinked path
  1769  	// This will fail if the referenced issue is hit with a "Volume exists" error
  1770  	dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test")
  1771  }
  1772  
  1773  //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container
  1774  func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) {
  1775  	out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf")
  1776  	if !strings.Contains(out, "nameserver 127.0.0.1") {
  1777  		c.Fatal("/etc volume mount hides /etc/resolv.conf")
  1778  	}
  1779  
  1780  	out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname")
  1781  	if !strings.Contains(out, "test123") {
  1782  		c.Fatal("/etc volume mount hides /etc/hostname")
  1783  	}
  1784  
  1785  	out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
  1786  	out = strings.Replace(out, "\n", " ", -1)
  1787  	if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
  1788  		c.Fatal("/etc volume mount hides /etc/hosts")
  1789  	}
  1790  }
  1791  
  1792  func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) {
  1793  	if _, err := buildImage("dataimage",
  1794  		`FROM busybox
  1795  		RUN mkdir -p /foo
  1796  		RUN touch /foo/bar`,
  1797  		true); err != nil {
  1798  		c.Fatal(err)
  1799  	}
  1800  
  1801  	dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox")
  1802  
  1803  	if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1804  		c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out)
  1805  	}
  1806  
  1807  	tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data")
  1808  	if out, _, err := dockerCmdWithError(c, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") {
  1809  		c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out)
  1810  	}
  1811  }
  1812  
  1813  func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) {
  1814  	// just run with unknown image
  1815  	cmd := exec.Command(dockerBinary, "run", "asdfsg")
  1816  	stdout := bytes.NewBuffer(nil)
  1817  	cmd.Stdout = stdout
  1818  	if err := cmd.Run(); err == nil {
  1819  		c.Fatal("Run with unknown image should fail")
  1820  	}
  1821  	if stdout.Len() != 0 {
  1822  		c.Fatalf("Stdout contains output from pull: %s", stdout)
  1823  	}
  1824  }
  1825  
  1826  func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) {
  1827  	if _, err := buildImage("run_volumes_clean_paths",
  1828  		`FROM busybox
  1829  		VOLUME /foo/`,
  1830  		true); err != nil {
  1831  		c.Fatal(err)
  1832  	}
  1833  
  1834  	dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths")
  1835  
  1836  	out, err := inspectMountSourceField("dark_helmet", "/foo/")
  1837  	if err != errMountNotFound {
  1838  		c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out)
  1839  	}
  1840  
  1841  	out, err = inspectMountSourceField("dark_helmet", "/foo")
  1842  	c.Assert(err, check.IsNil)
  1843  	if !strings.Contains(out, volumesConfigPath) {
  1844  		c.Fatalf("Volume was not defined for /foo\n%q", out)
  1845  	}
  1846  
  1847  	out, err = inspectMountSourceField("dark_helmet", "/bar/")
  1848  	if err != errMountNotFound {
  1849  		c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out)
  1850  	}
  1851  
  1852  	out, err = inspectMountSourceField("dark_helmet", "/bar")
  1853  	c.Assert(err, check.IsNil)
  1854  	if !strings.Contains(out, volumesConfigPath) {
  1855  		c.Fatalf("Volume was not defined for /bar\n%q", out)
  1856  	}
  1857  }
  1858  
  1859  // Regression test for #3631
  1860  func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) {
  1861  	cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv")
  1862  
  1863  	stdout, err := cont.StdoutPipe()
  1864  	if err != nil {
  1865  		c.Fatal(err)
  1866  	}
  1867  
  1868  	if err := cont.Start(); err != nil {
  1869  		c.Fatal(err)
  1870  	}
  1871  	n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil)
  1872  	if err != nil {
  1873  		c.Fatal(err)
  1874  	}
  1875  
  1876  	expected := 2 * 1024 * 2000
  1877  	if n != expected {
  1878  		c.Fatalf("Expected %d, got %d", expected, n)
  1879  	}
  1880  }
  1881  
  1882  func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
  1883  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top")
  1884  
  1885  	id := strings.TrimSpace(out)
  1886  	portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  1887  	c.Assert(err, check.IsNil)
  1888  	var ports nat.PortMap
  1889  	if err = unmarshalJSON([]byte(portstr), &ports); err != nil {
  1890  		c.Fatal(err)
  1891  	}
  1892  	for port, binding := range ports {
  1893  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  1894  		if portnum < 3000 || portnum > 3003 {
  1895  			c.Fatalf("Port %d is out of range ", portnum)
  1896  		}
  1897  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  1898  			c.Fatalf("Port is not mapped for the port %d", port)
  1899  		}
  1900  	}
  1901  }
  1902  
  1903  // test docker run expose a invalid port
  1904  func (s *DockerSuite) TestRunExposePort(c *check.C) {
  1905  	out, _, err := dockerCmdWithError(c, "run", "--expose", "80000", "busybox")
  1906  	//expose a invalid port should with a error out
  1907  	if err == nil || !strings.Contains(out, "Invalid range format for --expose") {
  1908  		c.Fatalf("run --expose a invalid port should with error out")
  1909  	}
  1910  }
  1911  
  1912  func (s *DockerSuite) TestRunUnknownCommand(c *check.C) {
  1913  	testRequires(c, NativeExecDriver)
  1914  	out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada")
  1915  
  1916  	cID := strings.TrimSpace(out)
  1917  	_, _, err := dockerCmdWithError(c, "start", cID)
  1918  	c.Assert(err, check.NotNil)
  1919  
  1920  	rc, err := inspectField(cID, "State.ExitCode")
  1921  	c.Assert(err, check.IsNil)
  1922  	if rc == "0" {
  1923  		c.Fatalf("ExitCode(%v) cannot be 0", rc)
  1924  	}
  1925  }
  1926  
  1927  func (s *DockerSuite) TestRunModeIpcHost(c *check.C) {
  1928  	testRequires(c, SameHostDaemon)
  1929  
  1930  	hostIpc, err := os.Readlink("/proc/1/ns/ipc")
  1931  	if err != nil {
  1932  		c.Fatal(err)
  1933  	}
  1934  
  1935  	out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc")
  1936  	out = strings.Trim(out, "\n")
  1937  	if hostIpc != out {
  1938  		c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out)
  1939  	}
  1940  
  1941  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc")
  1942  	out = strings.Trim(out, "\n")
  1943  	if hostIpc == out {
  1944  		c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out)
  1945  	}
  1946  }
  1947  
  1948  func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) {
  1949  	testRequires(c, SameHostDaemon)
  1950  
  1951  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1952  
  1953  	id := strings.TrimSpace(out)
  1954  	state, err := inspectField(id, "State.Running")
  1955  	c.Assert(err, check.IsNil)
  1956  	if state != "true" {
  1957  		c.Fatal("Container state is 'not running'")
  1958  	}
  1959  	pid1, err := inspectField(id, "State.Pid")
  1960  	c.Assert(err, check.IsNil)
  1961  
  1962  	parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1))
  1963  	if err != nil {
  1964  		c.Fatal(err)
  1965  	}
  1966  
  1967  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc")
  1968  	out = strings.Trim(out, "\n")
  1969  	if parentContainerIpc != out {
  1970  		c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out)
  1971  	}
  1972  }
  1973  
  1974  func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) {
  1975  	out, _, err := dockerCmdWithError(c, "run", "-d", "--ipc", "container:abcd1234", "busybox", "top")
  1976  	if !strings.Contains(out, "abcd1234") || err == nil {
  1977  		c.Fatalf("run IPC from a non exists container should with correct error out")
  1978  	}
  1979  }
  1980  
  1981  func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) {
  1982  	testRequires(c, SameHostDaemon)
  1983  
  1984  	out, _ := dockerCmd(c, "create", "busybox")
  1985  
  1986  	id := strings.TrimSpace(out)
  1987  	out, _, err := dockerCmdWithError(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox")
  1988  	if err == nil {
  1989  		c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err)
  1990  	}
  1991  }
  1992  
  1993  func (s *DockerSuite) TestContainerNetworkMode(c *check.C) {
  1994  	testRequires(c, SameHostDaemon)
  1995  
  1996  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  1997  	id := strings.TrimSpace(out)
  1998  	if err := waitRun(id); err != nil {
  1999  		c.Fatal(err)
  2000  	}
  2001  	pid1, err := inspectField(id, "State.Pid")
  2002  	c.Assert(err, check.IsNil)
  2003  
  2004  	parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2005  	if err != nil {
  2006  		c.Fatal(err)
  2007  	}
  2008  
  2009  	out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net")
  2010  	out = strings.Trim(out, "\n")
  2011  	if parentContainerNet != out {
  2012  		c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out)
  2013  	}
  2014  }
  2015  
  2016  func (s *DockerSuite) TestRunModePidHost(c *check.C) {
  2017  	testRequires(c, NativeExecDriver, SameHostDaemon)
  2018  
  2019  	hostPid, err := os.Readlink("/proc/1/ns/pid")
  2020  	if err != nil {
  2021  		c.Fatal(err)
  2022  	}
  2023  
  2024  	out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid")
  2025  	out = strings.Trim(out, "\n")
  2026  	if hostPid != out {
  2027  		c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out)
  2028  	}
  2029  
  2030  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid")
  2031  	out = strings.Trim(out, "\n")
  2032  	if hostPid == out {
  2033  		c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out)
  2034  	}
  2035  }
  2036  
  2037  func (s *DockerSuite) TestRunModeUTSHost(c *check.C) {
  2038  	testRequires(c, NativeExecDriver, SameHostDaemon)
  2039  
  2040  	hostUTS, err := os.Readlink("/proc/1/ns/uts")
  2041  	if err != nil {
  2042  		c.Fatal(err)
  2043  	}
  2044  
  2045  	out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts")
  2046  	out = strings.Trim(out, "\n")
  2047  	if hostUTS != out {
  2048  		c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out)
  2049  	}
  2050  
  2051  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts")
  2052  	out = strings.Trim(out, "\n")
  2053  	if hostUTS == out {
  2054  		c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out)
  2055  	}
  2056  }
  2057  
  2058  func (s *DockerSuite) TestRunTLSverify(c *check.C) {
  2059  	if out, code, err := dockerCmdWithError(c, "ps"); err != nil || code != 0 {
  2060  		c.Fatalf("Should have worked: %v:\n%v", err, out)
  2061  	}
  2062  
  2063  	// Regardless of whether we specify true or false we need to
  2064  	// test to make sure tls is turned on if --tlsverify is specified at all
  2065  	out, code, err := dockerCmdWithError(c, "--tlsverify=false", "ps")
  2066  	if err == nil || code == 0 || !strings.Contains(out, "trying to connect") {
  2067  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2068  	}
  2069  
  2070  	out, code, err = dockerCmdWithError(c, "--tlsverify=true", "ps")
  2071  	if err == nil || code == 0 || !strings.Contains(out, "cert") {
  2072  		c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err)
  2073  	}
  2074  }
  2075  
  2076  func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) {
  2077  	// first find allocator current position
  2078  	out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2079  
  2080  	id := strings.TrimSpace(out)
  2081  	out, _ = dockerCmd(c, "port", id)
  2082  
  2083  	out = strings.TrimSpace(out)
  2084  	if out == "" {
  2085  		c.Fatal("docker port command output is empty")
  2086  	}
  2087  	out = strings.Split(out, ":")[1]
  2088  	lastPort, err := strconv.Atoi(out)
  2089  	if err != nil {
  2090  		c.Fatal(err)
  2091  	}
  2092  	port := lastPort + 1
  2093  	l, err := net.Listen("tcp", ":"+strconv.Itoa(port))
  2094  	if err != nil {
  2095  		c.Fatal(err)
  2096  	}
  2097  	defer l.Close()
  2098  
  2099  	out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top")
  2100  
  2101  	id = strings.TrimSpace(out)
  2102  	dockerCmd(c, "port", id)
  2103  }
  2104  
  2105  func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) {
  2106  	errChan := make(chan error)
  2107  	go func() {
  2108  		defer close(errChan)
  2109  
  2110  		cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true")
  2111  		if _, err := cmd.StdinPipe(); err != nil {
  2112  			errChan <- err
  2113  			return
  2114  		}
  2115  
  2116  		expected := "cannot enable tty mode"
  2117  		if out, _, err := runCommandWithOutput(cmd); err == nil {
  2118  			errChan <- fmt.Errorf("run should have failed")
  2119  			return
  2120  		} else if !strings.Contains(out, expected) {
  2121  			errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected)
  2122  			return
  2123  		}
  2124  	}()
  2125  
  2126  	select {
  2127  	case err := <-errChan:
  2128  		c.Assert(err, check.IsNil)
  2129  	case <-time.After(3 * time.Second):
  2130  		c.Fatal("container is running but should have failed")
  2131  	}
  2132  }
  2133  
  2134  func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) {
  2135  	addr := "00:16:3E:08:00:50"
  2136  
  2137  	if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) {
  2138  		c.Fatalf("Output should have contained %q: %s", addr, out)
  2139  	}
  2140  }
  2141  
  2142  func (s *DockerSuite) TestRunNetHost(c *check.C) {
  2143  	testRequires(c, SameHostDaemon)
  2144  
  2145  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2146  	if err != nil {
  2147  		c.Fatal(err)
  2148  	}
  2149  
  2150  	out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net")
  2151  	out = strings.Trim(out, "\n")
  2152  	if hostNet != out {
  2153  		c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out)
  2154  	}
  2155  
  2156  	out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net")
  2157  	out = strings.Trim(out, "\n")
  2158  	if hostNet == out {
  2159  		c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out)
  2160  	}
  2161  }
  2162  
  2163  func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) {
  2164  	testRequires(c, SameHostDaemon)
  2165  
  2166  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2167  	dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true")
  2168  }
  2169  
  2170  func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) {
  2171  	testRequires(c, SameHostDaemon)
  2172  
  2173  	hostNet, err := os.Readlink("/proc/1/ns/net")
  2174  	if err != nil {
  2175  		c.Fatal(err)
  2176  	}
  2177  
  2178  	dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top")
  2179  
  2180  	out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net")
  2181  	out = strings.Trim(out, "\n")
  2182  	if hostNet != out {
  2183  		c.Fatalf("Container should have host network namespace")
  2184  	}
  2185  }
  2186  
  2187  func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) {
  2188  	out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top")
  2189  
  2190  	id := strings.TrimSpace(out)
  2191  	portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports")
  2192  	c.Assert(err, check.IsNil)
  2193  
  2194  	var ports nat.PortMap
  2195  	err = unmarshalJSON([]byte(portstr), &ports)
  2196  	for port, binding := range ports {
  2197  		portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0])
  2198  		if portnum < 3000 || portnum > 3003 {
  2199  			c.Fatalf("Port %d is out of range ", portnum)
  2200  		}
  2201  		if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
  2202  			c.Fatal("Port is not mapped for the port "+port, out)
  2203  		}
  2204  	}
  2205  }
  2206  
  2207  func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) {
  2208  	dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top")
  2209  
  2210  	out, err := inspectField("test", "HostConfig.RestartPolicy.Name")
  2211  	c.Assert(err, check.IsNil)
  2212  	if out != "no" {
  2213  		c.Fatalf("Set default restart policy failed")
  2214  	}
  2215  }
  2216  
  2217  func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) {
  2218  	out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false")
  2219  
  2220  	id := strings.TrimSpace(string(out))
  2221  	if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil {
  2222  		c.Fatal(err)
  2223  	}
  2224  
  2225  	count, err := inspectField(id, "RestartCount")
  2226  	c.Assert(err, check.IsNil)
  2227  	if count != "3" {
  2228  		c.Fatalf("Container was restarted %s times, expected %d", count, 3)
  2229  	}
  2230  
  2231  	MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount")
  2232  	c.Assert(err, check.IsNil)
  2233  	if MaximumRetryCount != "3" {
  2234  		c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3")
  2235  	}
  2236  }
  2237  
  2238  func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) {
  2239  	dockerCmd(c, "run", "--rm", "busybox", "touch", "/file")
  2240  }
  2241  
  2242  func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) {
  2243  	testRequires(c, NativeExecDriver)
  2244  
  2245  	for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/sys/kernel", "/dev/.dont.touch.me"} {
  2246  		testReadOnlyFile(f, c)
  2247  	}
  2248  }
  2249  
  2250  func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) {
  2251  	testRequires(c, NativeExecDriver)
  2252  
  2253  	// Ensure we have not broken writing /dev/pts
  2254  	out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount")
  2255  	if status != 0 {
  2256  		c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.")
  2257  	}
  2258  	expected := "type devpts (rw,"
  2259  	if !strings.Contains(string(out), expected) {
  2260  		c.Fatalf("expected output to contain %s but contains %s", expected, out)
  2261  	}
  2262  }
  2263  
  2264  func testReadOnlyFile(filename string, c *check.C) {
  2265  	testRequires(c, NativeExecDriver)
  2266  
  2267  	out, _, err := dockerCmdWithError(c, "run", "--read-only", "--rm", "busybox", "touch", filename)
  2268  	if err == nil {
  2269  		c.Fatal("expected container to error on run with read only error")
  2270  	}
  2271  	expected := "Read-only file system"
  2272  	if !strings.Contains(string(out), expected) {
  2273  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2274  	}
  2275  
  2276  	out, _, err = dockerCmdWithError(c, "run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename)
  2277  	if err == nil {
  2278  		c.Fatal("expected container to error on run with read only error")
  2279  	}
  2280  	expected = "Read-only file system"
  2281  	if !strings.Contains(string(out), expected) {
  2282  		c.Fatalf("expected output from failure to contain %s but contains %s", expected, out)
  2283  	}
  2284  }
  2285  
  2286  func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) {
  2287  	testRequires(c, NativeExecDriver)
  2288  
  2289  	dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top")
  2290  
  2291  	out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts")
  2292  	if !strings.Contains(string(out), "testlinked") {
  2293  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled")
  2294  	}
  2295  }
  2296  
  2297  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) {
  2298  	testRequires(c, NativeExecDriver)
  2299  
  2300  	out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf")
  2301  	if !strings.Contains(string(out), "1.1.1.1") {
  2302  		c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used")
  2303  	}
  2304  }
  2305  
  2306  func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) {
  2307  	testRequires(c, NativeExecDriver)
  2308  
  2309  	out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts")
  2310  	if !strings.Contains(string(out), "testreadonly") {
  2311  		c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used")
  2312  	}
  2313  }
  2314  
  2315  func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) {
  2316  	dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox")
  2317  	dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top")
  2318  
  2319  	// Remove the main volume container and restart the consuming container
  2320  	dockerCmd(c, "rm", "-f", "voltest")
  2321  
  2322  	// This should not fail since the volumes-from were already applied
  2323  	dockerCmd(c, "restart", "restarter")
  2324  }
  2325  
  2326  // run container with --rm should remove container if exit code != 0
  2327  func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) {
  2328  	name := "flowers"
  2329  	out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "ls", "/notexists")
  2330  	if err == nil {
  2331  		c.Fatal("Expected docker run to fail", out, err)
  2332  	}
  2333  
  2334  	out, err = getAllContainers()
  2335  	if err != nil {
  2336  		c.Fatal(out, err)
  2337  	}
  2338  
  2339  	if out != "" {
  2340  		c.Fatal("Expected not to have containers", out)
  2341  	}
  2342  }
  2343  
  2344  func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) {
  2345  	name := "sparkles"
  2346  	out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "commandNotFound")
  2347  	if err == nil {
  2348  		c.Fatal("Expected docker run to fail", out, err)
  2349  	}
  2350  
  2351  	out, err = getAllContainers()
  2352  	if err != nil {
  2353  		c.Fatal(out, err)
  2354  	}
  2355  
  2356  	if out != "" {
  2357  		c.Fatal("Expected not to have containers", out)
  2358  	}
  2359  }
  2360  
  2361  func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) {
  2362  	name := "ibuildthecloud"
  2363  	dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi")
  2364  
  2365  	time.Sleep(1 * time.Second)
  2366  	errchan := make(chan error)
  2367  	go func() {
  2368  		if out, _, err := dockerCmdWithError(c, "kill", name); err != nil {
  2369  			errchan <- fmt.Errorf("%v:\n%s", err, out)
  2370  		}
  2371  		close(errchan)
  2372  	}()
  2373  	select {
  2374  	case err := <-errchan:
  2375  		c.Assert(err, check.IsNil)
  2376  	case <-time.After(5 * time.Second):
  2377  		c.Fatal("Kill container timed out")
  2378  	}
  2379  }
  2380  
  2381  func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) {
  2382  	// this memory limit is 1 byte less than the min, which is 4MB
  2383  	// https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22
  2384  	out, _, err := dockerCmdWithError(c, "run", "-m", "4194303", "busybox")
  2385  	if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") {
  2386  		c.Fatalf("expected run to fail when using too low a memory limit: %q", out)
  2387  	}
  2388  }
  2389  
  2390  func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) {
  2391  	_, code, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version")
  2392  	if err == nil || code == 0 {
  2393  		c.Fatal("standard container should not be able to write to /proc/asound")
  2394  	}
  2395  }
  2396  
  2397  func (s *DockerSuite) TestRunReadProcTimer(c *check.C) {
  2398  	testRequires(c, NativeExecDriver)
  2399  	out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/timer_stats")
  2400  	if code != 0 {
  2401  		return
  2402  	}
  2403  	if err != nil {
  2404  		c.Fatal(err)
  2405  	}
  2406  	if strings.Trim(out, "\n ") != "" {
  2407  		c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out)
  2408  	}
  2409  }
  2410  
  2411  func (s *DockerSuite) TestRunReadProcLatency(c *check.C) {
  2412  	testRequires(c, NativeExecDriver)
  2413  	// some kernels don't have this configured so skip the test if this file is not found
  2414  	// on the host running the tests.
  2415  	if _, err := os.Stat("/proc/latency_stats"); err != nil {
  2416  		c.Skip("kernel doesnt have latency_stats configured")
  2417  		return
  2418  	}
  2419  	out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/latency_stats")
  2420  	if code != 0 {
  2421  		return
  2422  	}
  2423  	if err != nil {
  2424  		c.Fatal(err)
  2425  	}
  2426  	if strings.Trim(out, "\n ") != "" {
  2427  		c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out)
  2428  	}
  2429  }
  2430  
  2431  func (s *DockerSuite) TestRunReadFilteredProc(c *check.C) {
  2432  	testRequires(c, Apparmor)
  2433  
  2434  	testReadPaths := []string{
  2435  		"/proc/latency_stats",
  2436  		"/proc/timer_stats",
  2437  		"/proc/kcore",
  2438  	}
  2439  	for i, filePath := range testReadPaths {
  2440  		name := fmt.Sprintf("procsieve-%d", i)
  2441  		shellCmd := fmt.Sprintf("exec 3<%s", filePath)
  2442  
  2443  		out, exitCode, err := dockerCmdWithError(c, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2444  		if exitCode != 0 {
  2445  			return
  2446  		}
  2447  		if err != nil {
  2448  			c.Fatalf("Open FD for read should have failed with permission denied, got: %s, %v", out, err)
  2449  		}
  2450  	}
  2451  }
  2452  
  2453  func (s *DockerSuite) TestMountIntoProc(c *check.C) {
  2454  	testRequires(c, NativeExecDriver)
  2455  	_, code, err := dockerCmdWithError(c, "run", "-v", "/proc//sys", "busybox", "true")
  2456  	if err == nil || code == 0 {
  2457  		c.Fatal("container should not be able to mount into /proc")
  2458  	}
  2459  }
  2460  
  2461  func (s *DockerSuite) TestMountIntoSys(c *check.C) {
  2462  	testRequires(c, NativeExecDriver)
  2463  	dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true")
  2464  }
  2465  
  2466  func (s *DockerSuite) TestRunUnshareProc(c *check.C) {
  2467  	testRequires(c, Apparmor, NativeExecDriver)
  2468  
  2469  	name := "acidburn"
  2470  	if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") {
  2471  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2472  	}
  2473  
  2474  	name = "cereal"
  2475  	if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") {
  2476  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2477  	}
  2478  
  2479  	/* Ensure still fails if running privileged with the default policy */
  2480  	name = "crashoverride"
  2481  	if out, _, err := dockerCmdWithError(c, "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") {
  2482  		c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err)
  2483  	}
  2484  }
  2485  
  2486  func (s *DockerSuite) TestRunPublishPort(c *check.C) {
  2487  	dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top")
  2488  	out, _ := dockerCmd(c, "port", "test")
  2489  	out = strings.Trim(out, "\r\n")
  2490  	if out != "" {
  2491  		c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out)
  2492  	}
  2493  }
  2494  
  2495  // Issue #10184.
  2496  func (s *DockerSuite) TestDevicePermissions(c *check.C) {
  2497  	testRequires(c, NativeExecDriver)
  2498  	const permissions = "crw-rw-rw-"
  2499  	out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse")
  2500  	if status != 0 {
  2501  		c.Fatalf("expected status 0, got %d", status)
  2502  	}
  2503  	if !strings.HasPrefix(out, permissions) {
  2504  		c.Fatalf("output should begin with %q, got %q", permissions, out)
  2505  	}
  2506  }
  2507  
  2508  func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) {
  2509  	testRequires(c, NativeExecDriver)
  2510  	out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok")
  2511  
  2512  	if actual := strings.Trim(out, "\r\n"); actual != "ok" {
  2513  		c.Fatalf("expected output ok received %s", actual)
  2514  	}
  2515  }
  2516  
  2517  // https://github.com/docker/docker/pull/14498
  2518  func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) {
  2519  	dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true")
  2520  	dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true")
  2521  	dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true")
  2522  
  2523  	mRO, err := inspectMountPoint("test-volumes-1", "/test")
  2524  	c.Assert(err, check.IsNil)
  2525  	if mRO.RW {
  2526  		c.Fatalf("Expected RO volume was RW")
  2527  	}
  2528  
  2529  	mRW, err := inspectMountPoint("test-volumes-2", "/test")
  2530  	c.Assert(err, check.IsNil)
  2531  	if !mRW.RW {
  2532  		c.Fatalf("Expected RW volume was RO")
  2533  	}
  2534  }
  2535  
  2536  func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) {
  2537  	testRequires(c, Apparmor, NativeExecDriver)
  2538  
  2539  	testWritePaths := []string{
  2540  		/* modprobe and core_pattern should both be denied by generic
  2541  		 * policy of denials for /proc/sys/kernel. These files have been
  2542  		 * picked to be checked as they are particularly sensitive to writes */
  2543  		"/proc/sys/kernel/modprobe",
  2544  		"/proc/sys/kernel/core_pattern",
  2545  		"/proc/sysrq-trigger",
  2546  		"/proc/kcore",
  2547  	}
  2548  	for i, filePath := range testWritePaths {
  2549  		name := fmt.Sprintf("writeprocsieve-%d", i)
  2550  
  2551  		shellCmd := fmt.Sprintf("exec 3>%s", filePath)
  2552  		out, code, err := dockerCmdWithError(c, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd)
  2553  		if code != 0 {
  2554  			return
  2555  		}
  2556  		if err != nil {
  2557  			c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err)
  2558  		}
  2559  	}
  2560  }
  2561  
  2562  func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) {
  2563  	testRequires(c, SameHostDaemon)
  2564  	name := "test-nwfiles-mount"
  2565  
  2566  	f, err := ioutil.TempFile("", name)
  2567  	c.Assert(err, check.IsNil)
  2568  
  2569  	filename := f.Name()
  2570  	defer os.Remove(filename)
  2571  
  2572  	expected := "test123"
  2573  
  2574  	err = ioutil.WriteFile(filename, []byte(expected), 0644)
  2575  	c.Assert(err, check.IsNil)
  2576  
  2577  	var actual string
  2578  	actual, _ = dockerCmd(c, "run", "-v", filename+":/etc/resolv.conf", "busybox", "cat", "/etc/resolv.conf")
  2579  	if actual != expected {
  2580  		c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual)
  2581  	}
  2582  }
  2583  
  2584  func (s *DockerTrustSuite) TestTrustedRun(c *check.C) {
  2585  	repoName := s.setupTrustedImage(c, "trusted-run")
  2586  
  2587  	// Try run
  2588  	runCmd := exec.Command(dockerBinary, "run", repoName)
  2589  	s.trustedCmd(runCmd)
  2590  	out, _, err := runCommandWithOutput(runCmd)
  2591  	if err != nil {
  2592  		c.Fatalf("Error running trusted run: %s\n%s\n", err, out)
  2593  	}
  2594  
  2595  	if !strings.Contains(string(out), "Tagging") {
  2596  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2597  	}
  2598  
  2599  	dockerCmd(c, "rmi", repoName)
  2600  
  2601  	// Try untrusted run to ensure we pushed the tag to the registry
  2602  	runCmd = exec.Command(dockerBinary, "run", "--disable-content-trust=true", repoName)
  2603  	s.trustedCmd(runCmd)
  2604  	out, _, err = runCommandWithOutput(runCmd)
  2605  	if err != nil {
  2606  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2607  	}
  2608  
  2609  	if !strings.Contains(string(out), "Status: Downloaded") {
  2610  		c.Fatalf("Missing expected output on trusted run with --disable-content-trust:\n%s", out)
  2611  	}
  2612  }
  2613  
  2614  func (s *DockerTrustSuite) TestUntrustedRun(c *check.C) {
  2615  	repoName := fmt.Sprintf("%v/dockercli/trusted:latest", privateRegistryURL)
  2616  	// tag the image and upload it to the private registry
  2617  	dockerCmd(c, "tag", "busybox", repoName)
  2618  	dockerCmd(c, "push", repoName)
  2619  	dockerCmd(c, "rmi", repoName)
  2620  
  2621  	// Try trusted run on untrusted tag
  2622  	runCmd := exec.Command(dockerBinary, "run", repoName)
  2623  	s.trustedCmd(runCmd)
  2624  	out, _, err := runCommandWithOutput(runCmd)
  2625  	if err == nil {
  2626  		c.Fatalf("Error expected when running trusted run with:\n%s", out)
  2627  	}
  2628  
  2629  	if !strings.Contains(string(out), "no trust data available") {
  2630  		c.Fatalf("Missing expected output on trusted run:\n%s", out)
  2631  	}
  2632  }
  2633  
  2634  func (s *DockerTrustSuite) TestRunWhenCertExpired(c *check.C) {
  2635  	c.Skip("Currently changes system time, causing instability")
  2636  	repoName := s.setupTrustedImage(c, "trusted-run-expired")
  2637  
  2638  	// Certificates have 10 years of expiration
  2639  	elevenYearsFromNow := time.Now().Add(time.Hour * 24 * 365 * 11)
  2640  
  2641  	runAtDifferentDate(elevenYearsFromNow, func() {
  2642  		// Try run
  2643  		runCmd := exec.Command(dockerBinary, "run", repoName)
  2644  		s.trustedCmd(runCmd)
  2645  		out, _, err := runCommandWithOutput(runCmd)
  2646  		if err == nil {
  2647  			c.Fatalf("Error running trusted run in the distant future: %s\n%s", err, out)
  2648  		}
  2649  
  2650  		if !strings.Contains(string(out), "could not validate the path to a trusted root") {
  2651  			c.Fatalf("Missing expected output on trusted run in the distant future:\n%s", out)
  2652  		}
  2653  	})
  2654  
  2655  	runAtDifferentDate(elevenYearsFromNow, func() {
  2656  		// Try run
  2657  		runCmd := exec.Command(dockerBinary, "run", "--disable-content-trust", repoName)
  2658  		s.trustedCmd(runCmd)
  2659  		out, _, err := runCommandWithOutput(runCmd)
  2660  		if err != nil {
  2661  			c.Fatalf("Error running untrusted run in the distant future: %s\n%s", err, out)
  2662  		}
  2663  
  2664  		if !strings.Contains(string(out), "Status: Downloaded") {
  2665  			c.Fatalf("Missing expected output on untrusted run in the distant future:\n%s", out)
  2666  		}
  2667  	})
  2668  }
  2669  
  2670  func (s *DockerTrustSuite) TestTrustedRunFromBadTrustServer(c *check.C) {
  2671  	repoName := fmt.Sprintf("%v/dockerclievilrun/trusted:latest", privateRegistryURL)
  2672  	evilLocalConfigDir, err := ioutil.TempDir("", "evil-local-config-dir")
  2673  	if err != nil {
  2674  		c.Fatalf("Failed to create local temp dir")
  2675  	}
  2676  
  2677  	// tag the image and upload it to the private registry
  2678  	dockerCmd(c, "tag", "busybox", repoName)
  2679  
  2680  	pushCmd := exec.Command(dockerBinary, "push", repoName)
  2681  	s.trustedCmd(pushCmd)
  2682  	out, _, err := runCommandWithOutput(pushCmd)
  2683  	if err != nil {
  2684  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2685  	}
  2686  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2687  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2688  	}
  2689  
  2690  	dockerCmd(c, "rmi", repoName)
  2691  
  2692  	// Try run
  2693  	runCmd := exec.Command(dockerBinary, "run", repoName)
  2694  	s.trustedCmd(runCmd)
  2695  	out, _, err = runCommandWithOutput(runCmd)
  2696  	if err != nil {
  2697  		c.Fatalf("Error running trusted run: %s\n%s", err, out)
  2698  	}
  2699  
  2700  	if !strings.Contains(string(out), "Tagging") {
  2701  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2702  	}
  2703  
  2704  	dockerCmd(c, "rmi", repoName)
  2705  
  2706  	// Kill the notary server, start a new "evil" one.
  2707  	s.not.Close()
  2708  	s.not, err = newTestNotary(c)
  2709  	if err != nil {
  2710  		c.Fatalf("Restarting notary server failed.")
  2711  	}
  2712  
  2713  	// In order to make an evil server, lets re-init a client (with a different trust dir) and push new data.
  2714  	// tag an image and upload it to the private registry
  2715  	dockerCmd(c, "--config", evilLocalConfigDir, "tag", "busybox", repoName)
  2716  
  2717  	// Push up to the new server
  2718  	pushCmd = exec.Command(dockerBinary, "--config", evilLocalConfigDir, "push", repoName)
  2719  	s.trustedCmd(pushCmd)
  2720  	out, _, err = runCommandWithOutput(pushCmd)
  2721  	if err != nil {
  2722  		c.Fatalf("Error running trusted push: %s\n%s", err, out)
  2723  	}
  2724  	if !strings.Contains(string(out), "Signing and pushing trust metadata") {
  2725  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2726  	}
  2727  
  2728  	// Now, try running with the original client from this new trust server. This should fail.
  2729  	runCmd = exec.Command(dockerBinary, "run", repoName)
  2730  	s.trustedCmd(runCmd)
  2731  	out, _, err = runCommandWithOutput(runCmd)
  2732  	if err == nil {
  2733  		c.Fatalf("Expected to fail on this run due to different remote data: %s\n%s", err, out)
  2734  	}
  2735  
  2736  	if !strings.Contains(string(out), "failed to validate data with current trusted certificates") {
  2737  		c.Fatalf("Missing expected output on trusted push:\n%s", out)
  2738  	}
  2739  }
  2740  
  2741  func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) {
  2742  	testRequires(c, SameHostDaemon)
  2743  
  2744  	out, _ := dockerCmd(c, "run", "-d", "busybox", "top")
  2745  	id := strings.TrimSpace(out)
  2746  	if err := waitRun(id); err != nil {
  2747  		c.Fatal(err)
  2748  	}
  2749  	pid1, err := inspectField(id, "State.Pid")
  2750  	c.Assert(err, check.IsNil)
  2751  
  2752  	_, err = os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1))
  2753  	if err != nil {
  2754  		c.Fatal(err)
  2755  	}
  2756  }
  2757  
  2758  func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) {
  2759  	testRequires(c, SameHostDaemon)
  2760  	testRequires(c, Apparmor)
  2761  
  2762  	// Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace
  2763  	// itself, but pid>1 should not be able to trace pid1.
  2764  	_, exitCode, _ := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "readlink /proc/1/ns/net")
  2765  	if exitCode == 0 {
  2766  		c.Fatal("ptrace was not successfully restricted by AppArmor")
  2767  	}
  2768  }
  2769  
  2770  func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) {
  2771  	testRequires(c, SameHostDaemon)
  2772  	testRequires(c, Apparmor)
  2773  
  2774  	_, exitCode, _ := dockerCmdWithError(c, "run", "busybox", "readlink", "/proc/1/ns/net")
  2775  	if exitCode != 0 {
  2776  		c.Fatal("ptrace of self failed.")
  2777  	}
  2778  }