github.com/jiasir/docker@v1.3.3-0.20170609024000-252e610103e7/integration-cli/docker_cli_run_unix_test.go (about)

     1  // +build !windows
     2  
     3  package main
     4  
     5  import (
     6  	"bufio"
     7  	"encoding/json"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"os"
    11  	"os/exec"
    12  	"path/filepath"
    13  	"regexp"
    14  	"strconv"
    15  	"strings"
    16  	"syscall"
    17  	"time"
    18  
    19  	"github.com/docker/docker/integration-cli/checker"
    20  	"github.com/docker/docker/integration-cli/cli"
    21  	"github.com/docker/docker/integration-cli/cli/build"
    22  	"github.com/docker/docker/pkg/homedir"
    23  	"github.com/docker/docker/pkg/mount"
    24  	"github.com/docker/docker/pkg/parsers"
    25  	"github.com/docker/docker/pkg/sysinfo"
    26  	icmd "github.com/docker/docker/pkg/testutil/cmd"
    27  	"github.com/go-check/check"
    28  	"github.com/kr/pty"
    29  )
    30  
    31  // #6509
    32  func (s *DockerSuite) TestRunRedirectStdout(c *check.C) {
    33  	checkRedirect := func(command string) {
    34  		_, tty, err := pty.Open()
    35  		c.Assert(err, checker.IsNil, check.Commentf("Could not open pty"))
    36  		cmd := exec.Command("sh", "-c", command)
    37  		cmd.Stdin = tty
    38  		cmd.Stdout = tty
    39  		cmd.Stderr = tty
    40  		c.Assert(cmd.Start(), checker.IsNil)
    41  		ch := make(chan error)
    42  		go func() {
    43  			ch <- cmd.Wait()
    44  			close(ch)
    45  		}()
    46  
    47  		select {
    48  		case <-time.After(10 * time.Second):
    49  			c.Fatal("command timeout")
    50  		case err := <-ch:
    51  			c.Assert(err, checker.IsNil, check.Commentf("wait err"))
    52  		}
    53  	}
    54  
    55  	checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
    56  	checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
    57  }
    58  
    59  // Test recursive bind mount works by default
    60  func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) {
    61  	// /tmp gets permission denied
    62  	testRequires(c, NotUserNamespace, SameHostDaemon)
    63  	tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test")
    64  	c.Assert(err, checker.IsNil)
    65  
    66  	defer os.RemoveAll(tmpDir)
    67  
    68  	// Create a temporary tmpfs mount.
    69  	tmpfsDir := filepath.Join(tmpDir, "tmpfs")
    70  	c.Assert(os.MkdirAll(tmpfsDir, 0777), checker.IsNil, check.Commentf("failed to mkdir at %s", tmpfsDir))
    71  	c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir))
    72  
    73  	f, err := ioutil.TempFile(tmpfsDir, "touch-me")
    74  	c.Assert(err, checker.IsNil)
    75  	defer f.Close()
    76  
    77  	out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
    78  	c.Assert(out, checker.Contains, filepath.Base(f.Name()), check.Commentf("Recursive bind mount test failed. Expected file not found"))
    79  }
    80  
    81  func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) {
    82  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
    83  	if _, err := os.Stat("/dev/snd"); err != nil {
    84  		c.Skip("Host does not have /dev/snd")
    85  	}
    86  
    87  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
    88  	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "timer", check.Commentf("expected output /dev/snd/timer"))
    89  
    90  	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
    91  	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "seq", check.Commentf("expected output /dev/othersnd/seq"))
    92  }
    93  
    94  // TestRunAttachDetach checks attaching and detaching with the default escape sequence.
    95  func (s *DockerSuite) TestRunAttachDetach(c *check.C) {
    96  	name := "attach-detach"
    97  
    98  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
    99  
   100  	cmd := exec.Command(dockerBinary, "attach", name)
   101  	stdout, err := cmd.StdoutPipe()
   102  	c.Assert(err, checker.IsNil)
   103  	cpty, tty, err := pty.Open()
   104  	c.Assert(err, checker.IsNil)
   105  	defer cpty.Close()
   106  	cmd.Stdin = tty
   107  	c.Assert(cmd.Start(), checker.IsNil)
   108  	c.Assert(waitRun(name), check.IsNil)
   109  
   110  	_, err = cpty.Write([]byte("hello\n"))
   111  	c.Assert(err, checker.IsNil)
   112  
   113  	out, err := bufio.NewReader(stdout).ReadString('\n')
   114  	c.Assert(err, checker.IsNil)
   115  	c.Assert(strings.TrimSpace(out), checker.Equals, "hello")
   116  
   117  	// escape sequence
   118  	_, err = cpty.Write([]byte{16})
   119  	c.Assert(err, checker.IsNil)
   120  	time.Sleep(100 * time.Millisecond)
   121  	_, err = cpty.Write([]byte{17})
   122  	c.Assert(err, checker.IsNil)
   123  
   124  	ch := make(chan struct{})
   125  	go func() {
   126  		cmd.Wait()
   127  		ch <- struct{}{}
   128  	}()
   129  
   130  	select {
   131  	case <-ch:
   132  	case <-time.After(10 * time.Second):
   133  		c.Fatal("timed out waiting for container to exit")
   134  	}
   135  
   136  	running := inspectField(c, name, "State.Running")
   137  	c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
   138  
   139  	out, _ = dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name)
   140  	// attach and detach event should be monitored
   141  	c.Assert(out, checker.Contains, "attach")
   142  	c.Assert(out, checker.Contains, "detach")
   143  }
   144  
   145  // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags.
   146  func (s *DockerSuite) TestRunAttachDetachFromFlag(c *check.C) {
   147  	name := "attach-detach"
   148  	keyCtrlA := []byte{1}
   149  	keyA := []byte{97}
   150  
   151  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   152  
   153  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   154  	stdout, err := cmd.StdoutPipe()
   155  	if err != nil {
   156  		c.Fatal(err)
   157  	}
   158  	cpty, tty, err := pty.Open()
   159  	if err != nil {
   160  		c.Fatal(err)
   161  	}
   162  	defer cpty.Close()
   163  	cmd.Stdin = tty
   164  	if err := cmd.Start(); err != nil {
   165  		c.Fatal(err)
   166  	}
   167  	c.Assert(waitRun(name), check.IsNil)
   168  
   169  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   170  		c.Fatal(err)
   171  	}
   172  
   173  	out, err := bufio.NewReader(stdout).ReadString('\n')
   174  	if err != nil {
   175  		c.Fatal(err)
   176  	}
   177  	if strings.TrimSpace(out) != "hello" {
   178  		c.Fatalf("expected 'hello', got %q", out)
   179  	}
   180  
   181  	// escape sequence
   182  	if _, err := cpty.Write(keyCtrlA); err != nil {
   183  		c.Fatal(err)
   184  	}
   185  	time.Sleep(100 * time.Millisecond)
   186  	if _, err := cpty.Write(keyA); err != nil {
   187  		c.Fatal(err)
   188  	}
   189  
   190  	ch := make(chan struct{})
   191  	go func() {
   192  		cmd.Wait()
   193  		ch <- struct{}{}
   194  	}()
   195  
   196  	select {
   197  	case <-ch:
   198  	case <-time.After(10 * time.Second):
   199  		c.Fatal("timed out waiting for container to exit")
   200  	}
   201  
   202  	running := inspectField(c, name, "State.Running")
   203  	c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
   204  }
   205  
   206  // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags.
   207  func (s *DockerSuite) TestRunAttachDetachFromInvalidFlag(c *check.C) {
   208  	name := "attach-detach"
   209  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top")
   210  	c.Assert(waitRun(name), check.IsNil)
   211  
   212  	// specify an invalid detach key, container will ignore it and use default
   213  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name)
   214  	stdout, err := cmd.StdoutPipe()
   215  	if err != nil {
   216  		c.Fatal(err)
   217  	}
   218  	cpty, tty, err := pty.Open()
   219  	if err != nil {
   220  		c.Fatal(err)
   221  	}
   222  	defer cpty.Close()
   223  	cmd.Stdin = tty
   224  	if err := cmd.Start(); err != nil {
   225  		c.Fatal(err)
   226  	}
   227  
   228  	bufReader := bufio.NewReader(stdout)
   229  	out, err := bufReader.ReadString('\n')
   230  	if err != nil {
   231  		c.Fatal(err)
   232  	}
   233  	// it should print a warning to indicate the detach key flag is invalid
   234  	errStr := "Invalid detach keys (ctrl-A,a) provided"
   235  	c.Assert(strings.TrimSpace(out), checker.Equals, errStr)
   236  }
   237  
   238  // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file.
   239  func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) {
   240  	keyCtrlA := []byte{1}
   241  	keyA := []byte{97}
   242  
   243  	// Setup config
   244  	homeKey := homedir.Key()
   245  	homeVal := homedir.Get()
   246  	tmpDir, err := ioutil.TempDir("", "fake-home")
   247  	c.Assert(err, checker.IsNil)
   248  	defer os.RemoveAll(tmpDir)
   249  
   250  	dotDocker := filepath.Join(tmpDir, ".docker")
   251  	os.Mkdir(dotDocker, 0600)
   252  	tmpCfg := filepath.Join(dotDocker, "config.json")
   253  
   254  	defer func() { os.Setenv(homeKey, homeVal) }()
   255  	os.Setenv(homeKey, tmpDir)
   256  
   257  	data := `{
   258  		"detachKeys": "ctrl-a,a"
   259  	}`
   260  
   261  	err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
   262  	c.Assert(err, checker.IsNil)
   263  
   264  	// Then do the work
   265  	name := "attach-detach"
   266  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   267  
   268  	cmd := exec.Command(dockerBinary, "attach", name)
   269  	stdout, err := cmd.StdoutPipe()
   270  	if err != nil {
   271  		c.Fatal(err)
   272  	}
   273  	cpty, tty, err := pty.Open()
   274  	if err != nil {
   275  		c.Fatal(err)
   276  	}
   277  	defer cpty.Close()
   278  	cmd.Stdin = tty
   279  	if err := cmd.Start(); err != nil {
   280  		c.Fatal(err)
   281  	}
   282  	c.Assert(waitRun(name), check.IsNil)
   283  
   284  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   285  		c.Fatal(err)
   286  	}
   287  
   288  	out, err := bufio.NewReader(stdout).ReadString('\n')
   289  	if err != nil {
   290  		c.Fatal(err)
   291  	}
   292  	if strings.TrimSpace(out) != "hello" {
   293  		c.Fatalf("expected 'hello', got %q", out)
   294  	}
   295  
   296  	// escape sequence
   297  	if _, err := cpty.Write(keyCtrlA); err != nil {
   298  		c.Fatal(err)
   299  	}
   300  	time.Sleep(100 * time.Millisecond)
   301  	if _, err := cpty.Write(keyA); err != nil {
   302  		c.Fatal(err)
   303  	}
   304  
   305  	ch := make(chan struct{})
   306  	go func() {
   307  		cmd.Wait()
   308  		ch <- struct{}{}
   309  	}()
   310  
   311  	select {
   312  	case <-ch:
   313  	case <-time.After(10 * time.Second):
   314  		c.Fatal("timed out waiting for container to exit")
   315  	}
   316  
   317  	running := inspectField(c, name, "State.Running")
   318  	c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
   319  }
   320  
   321  // TestRunAttachDetachKeysOverrideConfig checks attaching and detaching with the detach flags, making sure it overrides config file
   322  func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) {
   323  	keyCtrlA := []byte{1}
   324  	keyA := []byte{97}
   325  
   326  	// Setup config
   327  	homeKey := homedir.Key()
   328  	homeVal := homedir.Get()
   329  	tmpDir, err := ioutil.TempDir("", "fake-home")
   330  	c.Assert(err, checker.IsNil)
   331  	defer os.RemoveAll(tmpDir)
   332  
   333  	dotDocker := filepath.Join(tmpDir, ".docker")
   334  	os.Mkdir(dotDocker, 0600)
   335  	tmpCfg := filepath.Join(dotDocker, "config.json")
   336  
   337  	defer func() { os.Setenv(homeKey, homeVal) }()
   338  	os.Setenv(homeKey, tmpDir)
   339  
   340  	data := `{
   341  		"detachKeys": "ctrl-e,e"
   342  	}`
   343  
   344  	err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
   345  	c.Assert(err, checker.IsNil)
   346  
   347  	// Then do the work
   348  	name := "attach-detach"
   349  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   350  
   351  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   352  	stdout, err := cmd.StdoutPipe()
   353  	if err != nil {
   354  		c.Fatal(err)
   355  	}
   356  	cpty, tty, err := pty.Open()
   357  	if err != nil {
   358  		c.Fatal(err)
   359  	}
   360  	defer cpty.Close()
   361  	cmd.Stdin = tty
   362  	if err := cmd.Start(); err != nil {
   363  		c.Fatal(err)
   364  	}
   365  	c.Assert(waitRun(name), check.IsNil)
   366  
   367  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   368  		c.Fatal(err)
   369  	}
   370  
   371  	out, err := bufio.NewReader(stdout).ReadString('\n')
   372  	if err != nil {
   373  		c.Fatal(err)
   374  	}
   375  	if strings.TrimSpace(out) != "hello" {
   376  		c.Fatalf("expected 'hello', got %q", out)
   377  	}
   378  
   379  	// escape sequence
   380  	if _, err := cpty.Write(keyCtrlA); err != nil {
   381  		c.Fatal(err)
   382  	}
   383  	time.Sleep(100 * time.Millisecond)
   384  	if _, err := cpty.Write(keyA); err != nil {
   385  		c.Fatal(err)
   386  	}
   387  
   388  	ch := make(chan struct{})
   389  	go func() {
   390  		cmd.Wait()
   391  		ch <- struct{}{}
   392  	}()
   393  
   394  	select {
   395  	case <-ch:
   396  	case <-time.After(10 * time.Second):
   397  		c.Fatal("timed out waiting for container to exit")
   398  	}
   399  
   400  	running := inspectField(c, name, "State.Running")
   401  	c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running"))
   402  }
   403  
   404  func (s *DockerSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *check.C) {
   405  	name := "attach-detach"
   406  	keyA := []byte{97}
   407  	keyB := []byte{98}
   408  
   409  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   410  
   411  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name)
   412  	stdout, err := cmd.StdoutPipe()
   413  	if err != nil {
   414  		c.Fatal(err)
   415  	}
   416  	cpty, tty, err := pty.Open()
   417  	if err != nil {
   418  		c.Fatal(err)
   419  	}
   420  	defer cpty.Close()
   421  	cmd.Stdin = tty
   422  	if err := cmd.Start(); err != nil {
   423  		c.Fatal(err)
   424  	}
   425  	c.Assert(waitRun(name), check.IsNil)
   426  
   427  	// Invalid escape sequence aba, should print aba in output
   428  	if _, err := cpty.Write(keyA); err != nil {
   429  		c.Fatal(err)
   430  	}
   431  	time.Sleep(100 * time.Millisecond)
   432  	if _, err := cpty.Write(keyB); err != nil {
   433  		c.Fatal(err)
   434  	}
   435  	time.Sleep(100 * time.Millisecond)
   436  	if _, err := cpty.Write(keyA); err != nil {
   437  		c.Fatal(err)
   438  	}
   439  	time.Sleep(100 * time.Millisecond)
   440  	if _, err := cpty.Write([]byte("\n")); err != nil {
   441  		c.Fatal(err)
   442  	}
   443  
   444  	out, err := bufio.NewReader(stdout).ReadString('\n')
   445  	if err != nil {
   446  		c.Fatal(err)
   447  	}
   448  	if strings.TrimSpace(out) != "aba" {
   449  		c.Fatalf("expected 'aba', got %q", out)
   450  	}
   451  }
   452  
   453  // "test" should be printed
   454  func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) {
   455  	testRequires(c, cpuCfsQuota)
   456  
   457  	file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
   458  	out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
   459  	c.Assert(strings.TrimSpace(out), checker.Equals, "8000")
   460  
   461  	out = inspectField(c, "test", "HostConfig.CpuQuota")
   462  	c.Assert(out, checker.Equals, "8000", check.Commentf("setting the CPU CFS quota failed"))
   463  }
   464  
   465  func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) {
   466  	testRequires(c, cpuCfsPeriod)
   467  
   468  	file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
   469  	out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
   470  	c.Assert(strings.TrimSpace(out), checker.Equals, "50000")
   471  
   472  	out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file)
   473  	c.Assert(strings.TrimSpace(out), checker.Equals, "100000")
   474  
   475  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
   476  	c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed"))
   477  }
   478  
   479  func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *check.C) {
   480  	testRequires(c, cpuCfsPeriod)
   481  	out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true")
   482  	c.Assert(err, check.NotNil)
   483  	expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)"
   484  	c.Assert(out, checker.Contains, expected)
   485  
   486  	out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true")
   487  	c.Assert(err, check.NotNil)
   488  	c.Assert(out, checker.Contains, expected)
   489  
   490  	out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true")
   491  	c.Assert(err, check.NotNil)
   492  	c.Assert(out, checker.Contains, expected)
   493  }
   494  
   495  func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) {
   496  	testRequires(c, kernelMemorySupport)
   497  
   498  	file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes"
   499  	cli.DockerCmd(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file).Assert(c, icmd.Expected{
   500  		Out: "52428800",
   501  	})
   502  
   503  	cli.InspectCmd(c, "test1", cli.Format(".HostConfig.KernelMemory")).Assert(c, icmd.Expected{
   504  		Out: "52428800",
   505  	})
   506  }
   507  
   508  func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) {
   509  	testRequires(c, kernelMemorySupport)
   510  
   511  	out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true")
   512  	c.Assert(err, check.NotNil)
   513  	expected := "Minimum kernel memory limit allowed is 4MB"
   514  	c.Assert(out, checker.Contains, expected)
   515  
   516  	out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test")
   517  	c.Assert(err, check.NotNil)
   518  	expected = "invalid size"
   519  	c.Assert(out, checker.Contains, expected)
   520  }
   521  
   522  func (s *DockerSuite) TestRunWithCPUShares(c *check.C) {
   523  	testRequires(c, cpuShare)
   524  
   525  	file := "/sys/fs/cgroup/cpu/cpu.shares"
   526  	out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
   527  	c.Assert(strings.TrimSpace(out), checker.Equals, "1000")
   528  
   529  	out = inspectField(c, "test", "HostConfig.CPUShares")
   530  	c.Assert(out, check.Equals, "1000")
   531  }
   532  
   533  // "test" should be printed
   534  func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) {
   535  	testRequires(c, cpuShare)
   536  	testRequires(c, memoryLimitSupport)
   537  	cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{
   538  		Out: "test\n",
   539  	})
   540  }
   541  
   542  func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) {
   543  	testRequires(c, cgroupCpuset)
   544  
   545  	file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
   546  	out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
   547  	c.Assert(strings.TrimSpace(out), checker.Equals, "0")
   548  
   549  	out = inspectField(c, "test", "HostConfig.CpusetCpus")
   550  	c.Assert(out, check.Equals, "0")
   551  }
   552  
   553  func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) {
   554  	testRequires(c, cgroupCpuset)
   555  
   556  	file := "/sys/fs/cgroup/cpuset/cpuset.mems"
   557  	out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
   558  	c.Assert(strings.TrimSpace(out), checker.Equals, "0")
   559  
   560  	out = inspectField(c, "test", "HostConfig.CpusetMems")
   561  	c.Assert(out, check.Equals, "0")
   562  }
   563  
   564  func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) {
   565  	testRequires(c, blkioWeight)
   566  
   567  	file := "/sys/fs/cgroup/blkio/blkio.weight"
   568  	out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
   569  	c.Assert(strings.TrimSpace(out), checker.Equals, "300")
   570  
   571  	out = inspectField(c, "test", "HostConfig.BlkioWeight")
   572  	c.Assert(out, check.Equals, "300")
   573  }
   574  
   575  func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) {
   576  	testRequires(c, blkioWeight)
   577  	out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
   578  	c.Assert(err, check.NotNil, check.Commentf(out))
   579  	expected := "Range of blkio weight is from 10 to 1000"
   580  	c.Assert(out, checker.Contains, expected)
   581  }
   582  
   583  func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) {
   584  	testRequires(c, blkioWeight)
   585  	out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
   586  	c.Assert(err, check.NotNil, check.Commentf(out))
   587  }
   588  
   589  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) {
   590  	testRequires(c, blkioWeight)
   591  	out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
   592  	c.Assert(err, check.NotNil, check.Commentf(out))
   593  }
   594  
   595  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) {
   596  	testRequires(c, blkioWeight)
   597  	out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
   598  	c.Assert(err, check.NotNil, check.Commentf(out))
   599  }
   600  
   601  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) {
   602  	testRequires(c, blkioWeight)
   603  	out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
   604  	c.Assert(err, check.NotNil, check.Commentf(out))
   605  }
   606  
   607  func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) {
   608  	testRequires(c, blkioWeight)
   609  	out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
   610  	c.Assert(err, check.NotNil, check.Commentf(out))
   611  }
   612  
   613  func (s *DockerSuite) TestRunOOMExitCode(c *check.C) {
   614  	testRequires(c, memoryLimitSupport, swapMemorySupport)
   615  	errChan := make(chan error)
   616  	go func() {
   617  		defer close(errChan)
   618  		out, exitCode, _ := dockerCmdWithError("run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
   619  		if expected := 137; exitCode != expected {
   620  			errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
   621  		}
   622  	}()
   623  
   624  	select {
   625  	case err := <-errChan:
   626  		c.Assert(err, check.IsNil)
   627  	case <-time.After(600 * time.Second):
   628  		c.Fatal("Timeout waiting for container to die on OOM")
   629  	}
   630  }
   631  
   632  func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) {
   633  	testRequires(c, memoryLimitSupport)
   634  
   635  	file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
   636  	cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{
   637  		Out: "33554432",
   638  	})
   639  	cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{
   640  		Out: "33554432",
   641  	})
   642  }
   643  
   644  // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
   645  // memory limit, this means the processes in the container can use
   646  // 16M memory and as much swap memory as they need (if the host
   647  // supports swap memory).
   648  func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) {
   649  	testRequires(c, DaemonIsLinux)
   650  	testRequires(c, memoryLimitSupport)
   651  	testRequires(c, swapMemorySupport)
   652  	dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
   653  }
   654  
   655  func (s *DockerSuite) TestRunWithSwappiness(c *check.C) {
   656  	testRequires(c, memorySwappinessSupport)
   657  	file := "/sys/fs/cgroup/memory/memory.swappiness"
   658  	out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
   659  	c.Assert(strings.TrimSpace(out), checker.Equals, "0")
   660  
   661  	out = inspectField(c, "test", "HostConfig.MemorySwappiness")
   662  	c.Assert(out, check.Equals, "0")
   663  }
   664  
   665  func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
   666  	testRequires(c, memorySwappinessSupport)
   667  	out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
   668  	c.Assert(err, check.NotNil)
   669  	expected := "Valid memory swappiness range is 0-100"
   670  	c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
   671  
   672  	out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
   673  	c.Assert(err, check.NotNil)
   674  	c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected))
   675  }
   676  
   677  func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
   678  	testRequires(c, memoryReservationSupport)
   679  
   680  	file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
   681  	out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
   682  	c.Assert(strings.TrimSpace(out), checker.Equals, "209715200")
   683  
   684  	out = inspectField(c, "test", "HostConfig.MemoryReservation")
   685  	c.Assert(out, check.Equals, "209715200")
   686  }
   687  
   688  func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
   689  	testRequires(c, memoryLimitSupport)
   690  	testRequires(c, memoryReservationSupport)
   691  	out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
   692  	c.Assert(err, check.NotNil)
   693  	expected := "Minimum memory limit can not be less than memory reservation limit"
   694  	c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
   695  
   696  	out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
   697  	c.Assert(err, check.NotNil)
   698  	expected = "Minimum memory reservation allowed is 4MB"
   699  	c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation"))
   700  }
   701  
   702  func (s *DockerSuite) TestStopContainerSignal(c *check.C) {
   703  	out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`)
   704  	containerID := strings.TrimSpace(out)
   705  
   706  	c.Assert(waitRun(containerID), checker.IsNil)
   707  
   708  	dockerCmd(c, "stop", containerID)
   709  	out, _ = dockerCmd(c, "logs", containerID)
   710  
   711  	c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log"))
   712  }
   713  
   714  func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) {
   715  	testRequires(c, memoryLimitSupport)
   716  	testRequires(c, swapMemorySupport)
   717  	out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
   718  	expected := "Minimum memoryswap limit should be larger than memory limit"
   719  	c.Assert(err, check.NotNil)
   720  
   721  	c.Assert(out, checker.Contains, expected)
   722  }
   723  
   724  func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) {
   725  	testRequires(c, cgroupCpuset, SameHostDaemon)
   726  
   727  	sysInfo := sysinfo.New(true)
   728  	cpus, err := parsers.ParseUintList(sysInfo.Cpus)
   729  	c.Assert(err, check.IsNil)
   730  	var invalid int
   731  	for i := 0; i <= len(cpus)+1; i++ {
   732  		if !cpus[i] {
   733  			invalid = i
   734  			break
   735  		}
   736  	}
   737  	out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
   738  	c.Assert(err, check.NotNil)
   739  	expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
   740  	c.Assert(out, checker.Contains, expected)
   741  }
   742  
   743  func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) {
   744  	testRequires(c, cgroupCpuset)
   745  
   746  	sysInfo := sysinfo.New(true)
   747  	mems, err := parsers.ParseUintList(sysInfo.Mems)
   748  	c.Assert(err, check.IsNil)
   749  	var invalid int
   750  	for i := 0; i <= len(mems)+1; i++ {
   751  		if !mems[i] {
   752  			invalid = i
   753  			break
   754  		}
   755  	}
   756  	out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
   757  	c.Assert(err, check.NotNil)
   758  	expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
   759  	c.Assert(out, checker.Contains, expected)
   760  }
   761  
   762  func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) {
   763  	testRequires(c, cpuShare, DaemonIsLinux)
   764  	out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
   765  	c.Assert(err, check.NotNil, check.Commentf(out))
   766  	expected := "The minimum allowed cpu-shares is 2"
   767  	c.Assert(out, checker.Contains, expected)
   768  
   769  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
   770  	c.Assert(err, check.NotNil, check.Commentf(out))
   771  	expected = "shares: invalid argument"
   772  	c.Assert(out, checker.Contains, expected)
   773  
   774  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
   775  	c.Assert(err, check.NotNil, check.Commentf(out))
   776  	expected = "The maximum allowed cpu-shares is"
   777  	c.Assert(out, checker.Contains, expected)
   778  }
   779  
   780  func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) {
   781  	testRequires(c, DaemonIsLinux)
   782  
   783  	name := "shm-default"
   784  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
   785  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
   786  	if !shmRegex.MatchString(out) {
   787  		c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
   788  	}
   789  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   790  	c.Assert(shmSize, check.Equals, "67108864")
   791  }
   792  
   793  func (s *DockerSuite) TestRunWithShmSize(c *check.C) {
   794  	testRequires(c, DaemonIsLinux)
   795  
   796  	name := "shm"
   797  	out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
   798  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
   799  	if !shmRegex.MatchString(out) {
   800  		c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
   801  	}
   802  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   803  	c.Assert(shmSize, check.Equals, "1073741824")
   804  }
   805  
   806  func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) {
   807  	tmpFile, err := ioutil.TempFile("", "test")
   808  	c.Assert(err, check.IsNil)
   809  	defer tmpFile.Close()
   810  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
   811  	c.Assert(out, checker.Contains, "test")
   812  }
   813  
   814  func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) {
   815  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   816  	// Windows does not support tmpfs mounts.
   817  	testRequires(c, DaemonIsLinux)
   818  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
   819  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   820  	}
   821  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
   822  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   823  	}
   824  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
   825  		c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
   826  	}
   827  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
   828  		c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
   829  	}
   830  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
   831  		c.Fatalf("Should have generated an error saying Duplicate mount  points")
   832  	}
   833  }
   834  
   835  func (s *DockerSuite) TestRunTmpfsMountsOverrideImageVolumes(c *check.C) {
   836  	name := "img-with-volumes"
   837  	buildImageSuccessfully(c, name, build.WithDockerfile(`
   838      FROM busybox
   839      VOLUME /run
   840      RUN touch /run/stuff
   841      `))
   842  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run")
   843  	c.Assert(out, checker.Not(checker.Contains), "stuff")
   844  }
   845  
   846  // Test case for #22420
   847  func (s *DockerSuite) TestRunTmpfsMountsWithOptions(c *check.C) {
   848  	testRequires(c, DaemonIsLinux)
   849  
   850  	expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   851  	out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   852  	for _, option := range expectedOptions {
   853  		c.Assert(out, checker.Contains, option)
   854  	}
   855  	c.Assert(out, checker.Not(checker.Contains), "size=")
   856  
   857  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   858  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   859  	for _, option := range expectedOptions {
   860  		c.Assert(out, checker.Contains, option)
   861  	}
   862  	c.Assert(out, checker.Not(checker.Contains), "size=")
   863  
   864  	expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"}
   865  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   866  	for _, option := range expectedOptions {
   867  		c.Assert(out, checker.Contains, option)
   868  	}
   869  
   870  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"}
   871  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   872  	for _, option := range expectedOptions {
   873  		c.Assert(out, checker.Contains, option)
   874  	}
   875  
   876  	// We use debian:jessie as there is no findmnt in busybox. Also the output will be in the format of
   877  	// TARGET PROPAGATION
   878  	// /tmp   shared
   879  	// so we only capture `shared` here.
   880  	expectedOptions = []string{"shared"}
   881  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:jessie", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp")
   882  	for _, option := range expectedOptions {
   883  		c.Assert(out, checker.Contains, option)
   884  	}
   885  }
   886  
   887  func (s *DockerSuite) TestRunSysctls(c *check.C) {
   888  	testRequires(c, DaemonIsLinux)
   889  	var err error
   890  
   891  	out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   892  	c.Assert(strings.TrimSpace(out), check.Equals, "1")
   893  
   894  	out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
   895  
   896  	sysctls := make(map[string]string)
   897  	err = json.Unmarshal([]byte(out), &sysctls)
   898  	c.Assert(err, check.IsNil)
   899  	c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1")
   900  
   901  	out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   902  	c.Assert(strings.TrimSpace(out), check.Equals, "0")
   903  
   904  	out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
   905  
   906  	err = json.Unmarshal([]byte(out), &sysctls)
   907  	c.Assert(err, check.IsNil)
   908  	c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0")
   909  
   910  	icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2",
   911  		"busybox", "cat", "/proc/sys/kernel/foobar").Assert(c, icmd.Expected{
   912  		ExitCode: 125,
   913  		Err:      "invalid argument",
   914  	})
   915  }
   916  
   917  // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted.
   918  func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) {
   919  	testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
   920  	jsonData := `{
   921  	"defaultAction": "SCMP_ACT_ALLOW",
   922  	"syscalls": [
   923  		{
   924  			"name": "unshare",
   925  			"action": "SCMP_ACT_ERRNO"
   926  		}
   927  	]
   928  }`
   929  	tmpFile, err := ioutil.TempFile("", "profile.json")
   930  	if err != nil {
   931  		c.Fatal(err)
   932  	}
   933  	defer tmpFile.Close()
   934  
   935  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   936  		c.Fatal(err)
   937  	}
   938  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "apparmor=unconfined",
   939  		"--security-opt", "seccomp="+tmpFile.Name(),
   940  		"debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc").Assert(c, icmd.Expected{
   941  		ExitCode: 1,
   942  		Err:      "Operation not permitted",
   943  	})
   944  }
   945  
   946  // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
   947  func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) {
   948  	testRequires(c, SameHostDaemon, seccompEnabled)
   949  	jsonData := `{
   950  	"defaultAction": "SCMP_ACT_ALLOW",
   951  	"syscalls": [
   952  		{
   953  			"name": "chmod",
   954  			"action": "SCMP_ACT_ERRNO"
   955  		},
   956  		{
   957  			"name":"fchmod",
   958  			"action": "SCMP_ACT_ERRNO"
   959  		},
   960  		{
   961  			"name": "fchmodat",
   962  			"action":"SCMP_ACT_ERRNO"
   963  		}
   964  	]
   965  }`
   966  	tmpFile, err := ioutil.TempFile("", "profile.json")
   967  	c.Assert(err, check.IsNil)
   968  	defer tmpFile.Close()
   969  
   970  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   971  		c.Fatal(err)
   972  	}
   973  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(),
   974  		"busybox", "chmod", "400", "/etc/hostname").Assert(c, icmd.Expected{
   975  		ExitCode: 1,
   976  		Err:      "Operation not permitted",
   977  	})
   978  }
   979  
   980  // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to
   981  // deny unshare of a userns exits with operation not permitted.
   982  func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) {
   983  	testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor)
   984  	// from sched.h
   985  	jsonData := fmt.Sprintf(`{
   986  	"defaultAction": "SCMP_ACT_ALLOW",
   987  	"syscalls": [
   988  		{
   989  			"name": "unshare",
   990  			"action": "SCMP_ACT_ERRNO",
   991  			"args": [
   992  				{
   993  					"index": 0,
   994  					"value": %d,
   995  					"op": "SCMP_CMP_EQ"
   996  				}
   997  			]
   998  		}
   999  	]
  1000  }`, uint64(0x10000000))
  1001  	tmpFile, err := ioutil.TempFile("", "profile.json")
  1002  	if err != nil {
  1003  		c.Fatal(err)
  1004  	}
  1005  	defer tmpFile.Close()
  1006  
  1007  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
  1008  		c.Fatal(err)
  1009  	}
  1010  	icmd.RunCommand(dockerBinary, "run",
  1011  		"--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(),
  1012  		"debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami").Assert(c, icmd.Expected{
  1013  		ExitCode: 1,
  1014  		Err:      "Operation not permitted",
  1015  	})
  1016  }
  1017  
  1018  // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
  1019  // with a the default seccomp profile exits with operation not permitted.
  1020  func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) {
  1021  	testRequires(c, SameHostDaemon, seccompEnabled)
  1022  	ensureSyscallTest(c)
  1023  
  1024  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1025  		ExitCode: 1,
  1026  		Err:      "clone failed: Operation not permitted",
  1027  	})
  1028  }
  1029  
  1030  // TestRunSeccompUnconfinedCloneUserns checks that
  1031  // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
  1032  func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) {
  1033  	testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone)
  1034  	ensureSyscallTest(c)
  1035  
  1036  	// make sure running w privileged is ok
  1037  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined",
  1038  		"syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1039  		Out: "nobody",
  1040  	})
  1041  }
  1042  
  1043  // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  1044  // allows creating a userns.
  1045  func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) {
  1046  	testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  1047  	ensureSyscallTest(c)
  1048  
  1049  	// make sure running w privileged is ok
  1050  	icmd.RunCommand(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1051  		Out: "nobody",
  1052  	})
  1053  }
  1054  
  1055  // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64
  1056  // with the default seccomp profile.
  1057  func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *check.C) {
  1058  	testRequires(c, SameHostDaemon, seccompEnabled, IsAmd64)
  1059  	ensureSyscallTest(c)
  1060  
  1061  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test", "id").Assert(c, icmd.Success)
  1062  }
  1063  
  1064  // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds.
  1065  func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) {
  1066  	testRequires(c, SameHostDaemon, seccompEnabled)
  1067  
  1068  	// ulimit uses setrlimit, so we want to make sure we don't break it
  1069  	icmd.RunCommand(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success)
  1070  }
  1071  
  1072  func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) {
  1073  	testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  1074  	ensureSyscallTest(c)
  1075  
  1076  	out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  1077  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1078  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1079  	}
  1080  
  1081  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  1082  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1083  		c.Fatalf("test 1: expected Operation not permitted, got: %s", out)
  1084  	}
  1085  
  1086  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1087  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1088  		c.Fatalf("test 2: expected No such file or directory, got: %s", out)
  1089  	}
  1090  
  1091  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  1092  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1093  		c.Fatalf("test 3: expected No such file or directory, got: %s", out)
  1094  	}
  1095  
  1096  	out, _, err = dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1097  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1098  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1099  	}
  1100  }
  1101  
  1102  func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) {
  1103  	testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace)
  1104  	ensureSyscallTest(c)
  1105  
  1106  	out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  1107  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1108  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1109  	}
  1110  
  1111  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  1112  	if err != nil || !strings.Contains(out, "hello1") {
  1113  		c.Fatalf("test 1: expected hello1, got: %s, %v", out, err)
  1114  	}
  1115  
  1116  	out, _, err = dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  1117  	if err != nil || !strings.Contains(out, "hello2") {
  1118  		c.Fatalf("test 2: expected hello2, got: %s, %v", out, err)
  1119  	}
  1120  
  1121  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  1122  	if err != nil || !strings.Contains(out, "hello3") {
  1123  		c.Fatalf("test 3: expected hello3, got: %s, %v", out, err)
  1124  	}
  1125  
  1126  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  1127  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1128  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1129  	}
  1130  
  1131  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  1132  	if err != nil || !strings.Contains(out, "hello4") {
  1133  		c.Fatalf("test 5: expected hello4, got: %s, %v", out, err)
  1134  	}
  1135  }
  1136  
  1137  // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents
  1138  // effective uid transtions on executing setuid binaries.
  1139  func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) {
  1140  	testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  1141  	ensureNNPTest(c)
  1142  
  1143  	// test that running a setuid binary results in no effective uid transition
  1144  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges=true", "--user", "1000",
  1145  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1146  		Out: "EUID=1000",
  1147  	})
  1148  }
  1149  
  1150  // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  1151  // effective uid transtions on executing setuid binaries.
  1152  func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *check.C) {
  1153  	testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon)
  1154  	ensureNNPTest(c)
  1155  
  1156  	// test that running a setuid binary results in no effective uid transition
  1157  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000",
  1158  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1159  		Out: "EUID=1000",
  1160  	})
  1161  }
  1162  
  1163  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *check.C) {
  1164  	testRequires(c, DaemonIsLinux)
  1165  	ensureSyscallTest(c)
  1166  
  1167  	// test that a root user has default capability CAP_CHOWN
  1168  	dockerCmd(c, "run", "busybox", "chown", "100", "/tmp")
  1169  	// test that non root user does not have default capability CAP_CHOWN
  1170  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1171  		ExitCode: 1,
  1172  		Err:      "Operation not permitted",
  1173  	})
  1174  	// test that root user can drop default capability CAP_CHOWN
  1175  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1176  		ExitCode: 1,
  1177  		Err:      "Operation not permitted",
  1178  	})
  1179  }
  1180  
  1181  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *check.C) {
  1182  	testRequires(c, DaemonIsLinux)
  1183  	ensureSyscallTest(c)
  1184  
  1185  	// test that a root user has default capability CAP_DAC_OVERRIDE
  1186  	dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd")
  1187  	// test that non root user does not have default capability CAP_DAC_OVERRIDE
  1188  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{
  1189  		ExitCode: 1,
  1190  		Err:      "Permission denied",
  1191  	})
  1192  }
  1193  
  1194  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *check.C) {
  1195  	testRequires(c, DaemonIsLinux)
  1196  	ensureSyscallTest(c)
  1197  
  1198  	// test that a root user has default capability CAP_FOWNER
  1199  	dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd")
  1200  	// test that non root user does not have default capability CAP_FOWNER
  1201  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{
  1202  		ExitCode: 1,
  1203  		Err:      "Operation not permitted",
  1204  	})
  1205  	// TODO test that root user can drop default capability CAP_FOWNER
  1206  }
  1207  
  1208  // TODO CAP_KILL
  1209  
  1210  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *check.C) {
  1211  	testRequires(c, DaemonIsLinux)
  1212  	ensureSyscallTest(c)
  1213  
  1214  	// test that a root user has default capability CAP_SETUID
  1215  	dockerCmd(c, "run", "syscall-test", "setuid-test")
  1216  	// test that non root user does not have default capability CAP_SETUID
  1217  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1218  		ExitCode: 1,
  1219  		Err:      "Operation not permitted",
  1220  	})
  1221  	// test that root user can drop default capability CAP_SETUID
  1222  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setuid", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1223  		ExitCode: 1,
  1224  		Err:      "Operation not permitted",
  1225  	})
  1226  }
  1227  
  1228  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *check.C) {
  1229  	testRequires(c, DaemonIsLinux)
  1230  	ensureSyscallTest(c)
  1231  
  1232  	// test that a root user has default capability CAP_SETGID
  1233  	dockerCmd(c, "run", "syscall-test", "setgid-test")
  1234  	// test that non root user does not have default capability CAP_SETGID
  1235  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1236  		ExitCode: 1,
  1237  		Err:      "Operation not permitted",
  1238  	})
  1239  	// test that root user can drop default capability CAP_SETGID
  1240  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setgid", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1241  		ExitCode: 1,
  1242  		Err:      "Operation not permitted",
  1243  	})
  1244  }
  1245  
  1246  // TODO CAP_SETPCAP
  1247  
  1248  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *check.C) {
  1249  	testRequires(c, DaemonIsLinux)
  1250  	ensureSyscallTest(c)
  1251  
  1252  	// test that a root user has default capability CAP_NET_BIND_SERVICE
  1253  	dockerCmd(c, "run", "syscall-test", "socket-test")
  1254  	// test that non root user does not have default capability CAP_NET_BIND_SERVICE
  1255  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1256  		ExitCode: 1,
  1257  		Err:      "Permission denied",
  1258  	})
  1259  	// test that root user can drop default capability CAP_NET_BIND_SERVICE
  1260  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_bind_service", "syscall-test", "socket-test").Assert(c, icmd.Expected{
  1261  		ExitCode: 1,
  1262  		Err:      "Permission denied",
  1263  	})
  1264  }
  1265  
  1266  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *check.C) {
  1267  	testRequires(c, DaemonIsLinux)
  1268  	ensureSyscallTest(c)
  1269  
  1270  	// test that a root user has default capability CAP_NET_RAW
  1271  	dockerCmd(c, "run", "syscall-test", "raw-test")
  1272  	// test that non root user does not have default capability CAP_NET_RAW
  1273  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1274  		ExitCode: 1,
  1275  		Err:      "Operation not permitted",
  1276  	})
  1277  	// test that root user can drop default capability CAP_NET_RAW
  1278  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_raw", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1279  		ExitCode: 1,
  1280  		Err:      "Operation not permitted",
  1281  	})
  1282  }
  1283  
  1284  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *check.C) {
  1285  	testRequires(c, DaemonIsLinux)
  1286  	ensureSyscallTest(c)
  1287  
  1288  	// test that a root user has default capability CAP_SYS_CHROOT
  1289  	dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true")
  1290  	// test that non root user does not have default capability CAP_SYS_CHROOT
  1291  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1292  		ExitCode: 1,
  1293  		Err:      "Operation not permitted",
  1294  	})
  1295  	// test that root user can drop default capability CAP_SYS_CHROOT
  1296  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "sys_chroot", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1297  		ExitCode: 1,
  1298  		Err:      "Operation not permitted",
  1299  	})
  1300  }
  1301  
  1302  func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *check.C) {
  1303  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1304  	ensureSyscallTest(c)
  1305  
  1306  	// test that a root user has default capability CAP_MKNOD
  1307  	dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2")
  1308  	// test that non root user does not have default capability CAP_MKNOD
  1309  	// test that root user can drop default capability CAP_SYS_CHROOT
  1310  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1311  		ExitCode: 1,
  1312  		Err:      "Operation not permitted",
  1313  	})
  1314  	// test that root user can drop default capability CAP_MKNOD
  1315  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "mknod", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1316  		ExitCode: 1,
  1317  		Err:      "Operation not permitted",
  1318  	})
  1319  }
  1320  
  1321  // TODO CAP_AUDIT_WRITE
  1322  // TODO CAP_SETFCAP
  1323  
  1324  func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) {
  1325  	testRequires(c, SameHostDaemon, Apparmor)
  1326  
  1327  	// running w seccomp unconfined tests the apparmor profile
  1328  	result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  1329  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1330  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1331  		c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", result.Combined(), result.Error)
  1332  	}
  1333  
  1334  	result = icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  1335  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1336  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1337  		c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", result.Combined(), result.Error)
  1338  	}
  1339  }
  1340  
  1341  // make sure the default profile can be successfully parsed (using unshare as it is
  1342  // something which we know is blocked in the default profile)
  1343  func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) {
  1344  	testRequires(c, SameHostDaemon, seccompEnabled)
  1345  
  1346  	out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1347  	c.Assert(err, checker.NotNil, check.Commentf(out))
  1348  	c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted")
  1349  }
  1350  
  1351  // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1352  func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
  1353  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon)
  1354  	if _, err := os.Stat("/dev/zero"); err != nil {
  1355  		c.Skip("Host does not have /dev/zero")
  1356  	}
  1357  
  1358  	// Create a temporary directory to create symlink
  1359  	tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests")
  1360  	c.Assert(err, checker.IsNil)
  1361  
  1362  	defer os.RemoveAll(tmpDir)
  1363  
  1364  	// Create a symbolic link to /dev/zero
  1365  	symZero := filepath.Join(tmpDir, "zero")
  1366  	err = os.Symlink("/dev/zero", symZero)
  1367  	c.Assert(err, checker.IsNil)
  1368  
  1369  	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1370  	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1371  	tmpFile := filepath.Join(tmpDir, "temp")
  1372  	err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666)
  1373  	c.Assert(err, checker.IsNil)
  1374  	symFile := filepath.Join(tmpDir, "file")
  1375  	err = os.Symlink(tmpFile, symFile)
  1376  	c.Assert(err, checker.IsNil)
  1377  
  1378  	// Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1379  	err = os.Symlink("zero", "/dev/symzero")
  1380  	if err != nil {
  1381  		c.Fatal("/dev/symzero creation failed")
  1382  	}
  1383  	// We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1384  	defer os.Remove("/dev/symzero")
  1385  
  1386  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1387  	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1388  	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1389  
  1390  	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1391  	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1392  	c.Assert(err, check.NotNil)
  1393  	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'"))
  1394  
  1395  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1396  	out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1397  	c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23"))
  1398  }
  1399  
  1400  // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
  1401  func (s *DockerSuite) TestRunPIDsLimit(c *check.C) {
  1402  	testRequires(c, pidsLimit)
  1403  
  1404  	file := "/sys/fs/cgroup/pids/pids.max"
  1405  	out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
  1406  	c.Assert(strings.TrimSpace(out), checker.Equals, "4")
  1407  
  1408  	out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1409  	c.Assert(out, checker.Equals, "4", check.Commentf("setting the pids limit failed"))
  1410  }
  1411  
  1412  func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) {
  1413  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1414  
  1415  	file := "/sys/fs/cgroup/devices/devices.list"
  1416  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1417  	c.Logf("out: %q", out)
  1418  	c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm")
  1419  }
  1420  
  1421  func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) {
  1422  	testRequires(c, DaemonIsLinux)
  1423  
  1424  	fi, err := os.Stat("/dev/snd/timer")
  1425  	if err != nil {
  1426  		c.Skip("Host does not have /dev/snd/timer")
  1427  	}
  1428  	stat, ok := fi.Sys().(*syscall.Stat_t)
  1429  	if !ok {
  1430  		c.Skip("Could not stat /dev/snd/timer")
  1431  	}
  1432  
  1433  	file := "/sys/fs/cgroup/devices/devices.list"
  1434  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1435  	c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))
  1436  }
  1437  
  1438  func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) {
  1439  	testRequires(c, SameHostDaemon, seccompEnabled)
  1440  
  1441  	s.d.StartWithBusybox(c)
  1442  
  1443  	jsonData := `{
  1444  	"defaultAction": "SCMP_ACT_ALLOW",
  1445  	"syscalls": [
  1446  		{
  1447  			"names": ["chmod", "fchmod", "fchmodat"],
  1448  			"action": "SCMP_ACT_ERRNO"
  1449  		}
  1450  	]
  1451  }`
  1452  	tmpFile, err := ioutil.TempFile("", "profile.json")
  1453  	c.Assert(err, check.IsNil)
  1454  	defer tmpFile.Close()
  1455  	_, err = tmpFile.Write([]byte(jsonData))
  1456  	c.Assert(err, check.IsNil)
  1457  
  1458  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1459  	c.Assert(err, check.NotNil)
  1460  	c.Assert(out, checker.Contains, "Operation not permitted")
  1461  }
  1462  
  1463  func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) {
  1464  	testRequires(c, SameHostDaemon, seccompEnabled)
  1465  
  1466  	s.d.StartWithBusybox(c)
  1467  
  1468  	jsonData := `{
  1469  	"defaultAction": "SCMP_ACT_ALLOW",
  1470  	"syscalls": [
  1471  		{
  1472  			"name": "chmod",
  1473  			"names": ["fchmod", "fchmodat"],
  1474  			"action": "SCMP_ACT_ERRNO"
  1475  		}
  1476  	]
  1477  }`
  1478  	tmpFile, err := ioutil.TempFile("", "profile.json")
  1479  	c.Assert(err, check.IsNil)
  1480  	defer tmpFile.Close()
  1481  	_, err = tmpFile.Write([]byte(jsonData))
  1482  	c.Assert(err, check.IsNil)
  1483  
  1484  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1485  	c.Assert(err, check.NotNil)
  1486  	c.Assert(out, checker.Contains, "'name' and 'names' were specified in the seccomp profile, use either 'name' or 'names'")
  1487  }
  1488  
  1489  func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) {
  1490  	testRequires(c, SameHostDaemon, seccompEnabled)
  1491  
  1492  	s.d.StartWithBusybox(c)
  1493  
  1494  	jsonData := `{
  1495  	"archMap": [
  1496  		{
  1497  			"architecture": "SCMP_ARCH_X86_64",
  1498  			"subArchitectures": [
  1499  				"SCMP_ARCH_X86",
  1500  				"SCMP_ARCH_X32"
  1501  			]
  1502  		}
  1503  	],
  1504  	"architectures": [
  1505  		"SCMP_ARCH_X32"
  1506  	],
  1507  	"defaultAction": "SCMP_ACT_ALLOW",
  1508  	"syscalls": [
  1509  		{
  1510  			"names": ["chmod", "fchmod", "fchmodat"],
  1511  			"action": "SCMP_ACT_ERRNO"
  1512  		}
  1513  	]
  1514  }`
  1515  	tmpFile, err := ioutil.TempFile("", "profile.json")
  1516  	c.Assert(err, check.IsNil)
  1517  	defer tmpFile.Close()
  1518  	_, err = tmpFile.Write([]byte(jsonData))
  1519  	c.Assert(err, check.IsNil)
  1520  
  1521  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1522  	c.Assert(err, check.NotNil)
  1523  	c.Assert(out, checker.Contains, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'")
  1524  }
  1525  
  1526  func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) {
  1527  	testRequires(c, SameHostDaemon, seccompEnabled)
  1528  
  1529  	s.d.StartWithBusybox(c)
  1530  
  1531  	// 1) verify I can run containers with the Docker default shipped profile which allows chmod
  1532  	_, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1533  	c.Assert(err, check.IsNil)
  1534  
  1535  	jsonData := `{
  1536  	"defaultAction": "SCMP_ACT_ALLOW",
  1537  	"syscalls": [
  1538  		{
  1539  			"name": "chmod",
  1540  			"action": "SCMP_ACT_ERRNO"
  1541  		}
  1542  	]
  1543  }`
  1544  	tmpFile, err := ioutil.TempFile("", "profile.json")
  1545  	c.Assert(err, check.IsNil)
  1546  	defer tmpFile.Close()
  1547  	_, err = tmpFile.Write([]byte(jsonData))
  1548  	c.Assert(err, check.IsNil)
  1549  
  1550  	// 2) restart the daemon and add a custom seccomp profile in which we deny chmod
  1551  	s.d.Restart(c, "--seccomp-profile="+tmpFile.Name())
  1552  
  1553  	out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1554  	c.Assert(err, check.NotNil)
  1555  	c.Assert(out, checker.Contains, "Operation not permitted")
  1556  }
  1557  
  1558  func (s *DockerSuite) TestRunWithNanoCPUs(c *check.C) {
  1559  	testRequires(c, cpuCfsQuota, cpuCfsPeriod)
  1560  
  1561  	file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  1562  	file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  1563  	out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2))
  1564  	c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000")
  1565  
  1566  	out = inspectField(c, "test", "HostConfig.NanoCpus")
  1567  	c.Assert(out, checker.Equals, "5e+08", check.Commentf("setting the Nano CPUs failed"))
  1568  	out = inspectField(c, "test", "HostConfig.CpuQuota")
  1569  	c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0"))
  1570  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
  1571  	c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0"))
  1572  
  1573  	out, _, err := dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh")
  1574  	c.Assert(err, check.NotNil)
  1575  	c.Assert(out, checker.Contains, "Conflicting options: Nano CPUs and CPU Period cannot both be set")
  1576  }