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