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