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