github.com/noxiouz/docker@v0.7.3-0.20160629055221-3d231c78e8c5/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 "sync" 17 "syscall" 18 "time" 19 20 "github.com/docker/docker/pkg/homedir" 21 "github.com/docker/docker/pkg/integration/checker" 22 "github.com/docker/docker/pkg/mount" 23 "github.com/docker/docker/pkg/parsers" 24 "github.com/docker/docker/pkg/sysinfo" 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 runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs") 76 out, _, _, err := runCommandWithStdoutStderr(runCmd) 77 c.Assert(err, checker.IsNil) 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 // TestRunDetach 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 // TestRunDetach 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 // TestRunDetach 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 escape keys (ctrl-A,a) provided" 235 c.Assert(strings.TrimSpace(out), checker.Equals, errStr) 236 } 237 238 // TestRunDetach 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 // TestRunDetach 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 stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "--kernel-memory", "50M", "--name", "test1", "busybox", "cat", file) 500 c.Assert(strings.TrimSpace(stdout), checker.Equals, "52428800") 501 502 out := inspectField(c, "test1", "HostConfig.KernelMemory") 503 c.Assert(out, check.Equals, "52428800") 504 } 505 506 func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) { 507 testRequires(c, kernelMemorySupport) 508 509 out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true") 510 c.Assert(err, check.NotNil) 511 expected := "Minimum kernel memory limit allowed is 4MB" 512 c.Assert(out, checker.Contains, expected) 513 514 out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test") 515 c.Assert(err, check.NotNil) 516 expected = "invalid size" 517 c.Assert(out, checker.Contains, expected) 518 } 519 520 func (s *DockerSuite) TestRunWithCPUShares(c *check.C) { 521 testRequires(c, cpuShare) 522 523 file := "/sys/fs/cgroup/cpu/cpu.shares" 524 out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file) 525 c.Assert(strings.TrimSpace(out), checker.Equals, "1000") 526 527 out = inspectField(c, "test", "HostConfig.CPUShares") 528 c.Assert(out, check.Equals, "1000") 529 } 530 531 // "test" should be printed 532 func (s *DockerSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *check.C) { 533 testRequires(c, cpuShare) 534 testRequires(c, memoryLimitSupport) 535 out, _, _ := dockerCmdWithStdoutStderr(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test") 536 c.Assert(out, checker.Equals, "test\n", check.Commentf("container should've printed 'test'")) 537 } 538 539 func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) { 540 testRequires(c, cgroupCpuset) 541 542 file := "/sys/fs/cgroup/cpuset/cpuset.cpus" 543 out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file) 544 c.Assert(strings.TrimSpace(out), checker.Equals, "0") 545 546 out = inspectField(c, "test", "HostConfig.CpusetCpus") 547 c.Assert(out, check.Equals, "0") 548 } 549 550 func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) { 551 testRequires(c, cgroupCpuset) 552 553 file := "/sys/fs/cgroup/cpuset/cpuset.mems" 554 out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file) 555 c.Assert(strings.TrimSpace(out), checker.Equals, "0") 556 557 out = inspectField(c, "test", "HostConfig.CpusetMems") 558 c.Assert(out, check.Equals, "0") 559 } 560 561 func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) { 562 testRequires(c, blkioWeight) 563 564 file := "/sys/fs/cgroup/blkio/blkio.weight" 565 out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file) 566 c.Assert(strings.TrimSpace(out), checker.Equals, "300") 567 568 out = inspectField(c, "test", "HostConfig.BlkioWeight") 569 c.Assert(out, check.Equals, "300") 570 } 571 572 func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) { 573 testRequires(c, blkioWeight) 574 out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true") 575 c.Assert(err, check.NotNil, check.Commentf(out)) 576 expected := "Range of blkio weight is from 10 to 1000" 577 c.Assert(out, checker.Contains, expected) 578 } 579 580 func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) { 581 testRequires(c, blkioWeight) 582 out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true") 583 c.Assert(err, check.NotNil, check.Commentf(out)) 584 } 585 586 func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) { 587 testRequires(c, blkioWeight) 588 out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true") 589 c.Assert(err, check.NotNil, check.Commentf(out)) 590 } 591 592 func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) { 593 testRequires(c, blkioWeight) 594 out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true") 595 c.Assert(err, check.NotNil, check.Commentf(out)) 596 } 597 598 func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) { 599 testRequires(c, blkioWeight) 600 out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true") 601 c.Assert(err, check.NotNil, check.Commentf(out)) 602 } 603 604 func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) { 605 testRequires(c, blkioWeight) 606 out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true") 607 c.Assert(err, check.NotNil, check.Commentf(out)) 608 } 609 610 func (s *DockerSuite) TestRunOOMExitCode(c *check.C) { 611 testRequires(c, memoryLimitSupport, swapMemorySupport) 612 errChan := make(chan error) 613 go func() { 614 defer close(errChan) 615 //changing memory to 40MB from 4MB due to an issue with GCCGO that test fails to start the container. 616 out, exitCode, _ := dockerCmdWithError("run", "-m", "40MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done") 617 if expected := 137; exitCode != expected { 618 errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out) 619 } 620 }() 621 622 select { 623 case err := <-errChan: 624 c.Assert(err, check.IsNil) 625 case <-time.After(600 * time.Second): 626 c.Fatal("Timeout waiting for container to die on OOM") 627 } 628 } 629 630 func (s *DockerSuite) TestRunWithMemoryLimit(c *check.C) { 631 testRequires(c, memoryLimitSupport) 632 633 file := "/sys/fs/cgroup/memory/memory.limit_in_bytes" 634 stdout, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file) 635 c.Assert(strings.TrimSpace(stdout), checker.Equals, "33554432") 636 637 out := inspectField(c, "test", "HostConfig.Memory") 638 c.Assert(out, check.Equals, "33554432") 639 } 640 641 // TestRunWithoutMemoryswapLimit sets memory limit and disables swap 642 // memory limit, this means the processes in the container can use 643 // 16M memory and as much swap memory as they need (if the host 644 // supports swap memory). 645 func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) { 646 testRequires(c, DaemonIsLinux) 647 testRequires(c, memoryLimitSupport) 648 testRequires(c, swapMemorySupport) 649 dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true") 650 } 651 652 func (s *DockerSuite) TestRunWithSwappiness(c *check.C) { 653 testRequires(c, memorySwappinessSupport) 654 file := "/sys/fs/cgroup/memory/memory.swappiness" 655 out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file) 656 c.Assert(strings.TrimSpace(out), checker.Equals, "0") 657 658 out = inspectField(c, "test", "HostConfig.MemorySwappiness") 659 c.Assert(out, check.Equals, "0") 660 } 661 662 func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) { 663 testRequires(c, memorySwappinessSupport) 664 out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true") 665 c.Assert(err, check.NotNil) 666 expected := "Valid memory swappiness range is 0-100" 667 c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected)) 668 669 out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true") 670 c.Assert(err, check.NotNil) 671 c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected)) 672 } 673 674 func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) { 675 testRequires(c, memoryReservationSupport) 676 677 file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes" 678 out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file) 679 c.Assert(strings.TrimSpace(out), checker.Equals, "209715200") 680 681 out = inspectField(c, "test", "HostConfig.MemoryReservation") 682 c.Assert(out, check.Equals, "209715200") 683 } 684 685 func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) { 686 testRequires(c, memoryLimitSupport) 687 testRequires(c, memoryReservationSupport) 688 out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true") 689 c.Assert(err, check.NotNil) 690 expected := "Minimum memory limit should be larger than memory reservation limit" 691 c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation")) 692 693 out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true") 694 c.Assert(err, check.NotNil) 695 expected = "Minimum memory reservation allowed is 4MB" 696 c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation")) 697 } 698 699 func (s *DockerSuite) TestStopContainerSignal(c *check.C) { 700 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`) 701 containerID := strings.TrimSpace(out) 702 703 c.Assert(waitRun(containerID), checker.IsNil) 704 705 dockerCmd(c, "stop", containerID) 706 out, _ = dockerCmd(c, "logs", containerID) 707 708 c.Assert(out, checker.Contains, "exit trapped", check.Commentf("Expected `exit trapped` in the log")) 709 } 710 711 func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) { 712 testRequires(c, memoryLimitSupport) 713 testRequires(c, swapMemorySupport) 714 out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test") 715 expected := "Minimum memoryswap limit should be larger than memory limit" 716 c.Assert(err, check.NotNil) 717 718 c.Assert(out, checker.Contains, expected) 719 } 720 721 func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) { 722 testRequires(c, cgroupCpuset, SameHostDaemon) 723 724 sysInfo := sysinfo.New(true) 725 cpus, err := parsers.ParseUintList(sysInfo.Cpus) 726 c.Assert(err, check.IsNil) 727 var invalid int 728 for i := 0; i <= len(cpus)+1; i++ { 729 if !cpus[i] { 730 invalid = i 731 break 732 } 733 } 734 out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true") 735 c.Assert(err, check.NotNil) 736 expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus) 737 c.Assert(out, checker.Contains, expected) 738 } 739 740 func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) { 741 testRequires(c, cgroupCpuset) 742 743 sysInfo := sysinfo.New(true) 744 mems, err := parsers.ParseUintList(sysInfo.Mems) 745 c.Assert(err, check.IsNil) 746 var invalid int 747 for i := 0; i <= len(mems)+1; i++ { 748 if !mems[i] { 749 invalid = i 750 break 751 } 752 } 753 out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true") 754 c.Assert(err, check.NotNil) 755 expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems) 756 c.Assert(out, checker.Contains, expected) 757 } 758 759 func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) { 760 testRequires(c, cpuShare, DaemonIsLinux) 761 out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test") 762 c.Assert(err, check.NotNil, check.Commentf(out)) 763 expected := "The minimum allowed cpu-shares is 2" 764 c.Assert(out, checker.Contains, expected) 765 766 out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test") 767 c.Assert(err, check.NotNil, check.Commentf(out)) 768 expected = "shares: invalid argument" 769 c.Assert(out, checker.Contains, expected) 770 771 out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test") 772 c.Assert(err, check.NotNil, check.Commentf(out)) 773 expected = "The maximum allowed cpu-shares is" 774 c.Assert(out, checker.Contains, expected) 775 } 776 777 func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) { 778 testRequires(c, DaemonIsLinux) 779 780 name := "shm-default" 781 out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount") 782 shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`) 783 if !shmRegex.MatchString(out) { 784 c.Fatalf("Expected shm of 64MB in mount command, got %v", out) 785 } 786 shmSize := inspectField(c, name, "HostConfig.ShmSize") 787 c.Assert(shmSize, check.Equals, "67108864") 788 } 789 790 func (s *DockerSuite) TestRunWithShmSize(c *check.C) { 791 testRequires(c, DaemonIsLinux) 792 793 name := "shm" 794 out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount") 795 shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`) 796 if !shmRegex.MatchString(out) { 797 c.Fatalf("Expected shm of 1GB in mount command, got %v", out) 798 } 799 shmSize := inspectField(c, name, "HostConfig.ShmSize") 800 c.Assert(shmSize, check.Equals, "1073741824") 801 } 802 803 func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) { 804 tmpFile, err := ioutil.TempFile("", "test") 805 c.Assert(err, check.IsNil) 806 defer tmpFile.Close() 807 out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run") 808 c.Assert(out, checker.Contains, "test") 809 } 810 811 func (s *DockerSuite) TestRunTmpfsMounts(c *check.C) { 812 // TODO Windows (Post TP5): This test cannot run on a Windows daemon as 813 // Windows does not support tmpfs mounts. 814 testRequires(c, DaemonIsLinux) 815 if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "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", "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,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil { 822 c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out) 823 } 824 if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil { 825 c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option") 826 } 827 if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil { 828 c.Fatalf("Should have generated an error saying Duplicate mount points") 829 } 830 } 831 832 func (s *DockerSuite) TestRunTmpfsMountsOverrideImageVolumes(c *check.C) { 833 name := "img-with-volumes" 834 _, err := buildImage( 835 name, 836 ` 837 FROM busybox 838 VOLUME /run 839 RUN touch /run/stuff 840 `, 841 true) 842 if err != nil { 843 c.Fatal(err) 844 } 845 out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run") 846 c.Assert(out, checker.Not(checker.Contains), "stuff") 847 } 848 849 // Test case for #22420 850 func (s *DockerSuite) TestRunTmpfsMountsWithOptions(c *check.C) { 851 testRequires(c, DaemonIsLinux) 852 853 expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"} 854 out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") 855 for _, option := range expectedOptions { 856 c.Assert(out, checker.Contains, option) 857 } 858 c.Assert(out, checker.Not(checker.Contains), "size=") 859 860 expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"} 861 out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") 862 for _, option := range expectedOptions { 863 c.Assert(out, checker.Contains, option) 864 } 865 c.Assert(out, checker.Not(checker.Contains), "size=") 866 867 expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"} 868 out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") 869 for _, option := range expectedOptions { 870 c.Assert(out, checker.Contains, option) 871 } 872 873 expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"} 874 out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") 875 for _, option := range expectedOptions { 876 c.Assert(out, checker.Contains, option) 877 } 878 879 // We use debian:jessie as there is no findmnt in busybox. Also the output will be in the format of 880 // TARGET PROPAGATION 881 // /tmp shared 882 // so we only capture `shared` here. 883 expectedOptions = []string{"shared"} 884 out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:jessie", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp") 885 for _, option := range expectedOptions { 886 c.Assert(out, checker.Contains, option) 887 } 888 } 889 890 func (s *DockerSuite) TestRunSysctls(c *check.C) { 891 892 testRequires(c, DaemonIsLinux) 893 var err error 894 895 out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward") 896 c.Assert(strings.TrimSpace(out), check.Equals, "1") 897 898 out = inspectFieldJSON(c, "test", "HostConfig.Sysctls") 899 900 sysctls := make(map[string]string) 901 err = json.Unmarshal([]byte(out), &sysctls) 902 c.Assert(err, check.IsNil) 903 c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1") 904 905 out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward") 906 c.Assert(strings.TrimSpace(out), check.Equals, "0") 907 908 out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls") 909 910 err = json.Unmarshal([]byte(out), &sysctls) 911 c.Assert(err, check.IsNil) 912 c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0") 913 914 runCmd := exec.Command(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2", "busybox", "cat", "/proc/sys/kernel/foobar") 915 out, _, _ = runCommandWithOutput(runCmd) 916 if !strings.Contains(out, "invalid argument") { 917 c.Fatalf("expected --sysctl to fail, got %s", out) 918 } 919 } 920 921 // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted. 922 func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) { 923 testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor) 924 jsonData := `{ 925 "defaultAction": "SCMP_ACT_ALLOW", 926 "syscalls": [ 927 { 928 "name": "unshare", 929 "action": "SCMP_ACT_ERRNO" 930 } 931 ] 932 }` 933 tmpFile, err := ioutil.TempFile("", "profile.json") 934 defer tmpFile.Close() 935 if err != nil { 936 c.Fatal(err) 937 } 938 939 if _, err := tmpFile.Write([]byte(jsonData)); err != nil { 940 c.Fatal(err) 941 } 942 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(), "debian:jessie", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc") 943 out, _, _ := runCommandWithOutput(runCmd) 944 if !strings.Contains(out, "Operation not permitted") { 945 c.Fatalf("expected unshare with seccomp profile denied to fail, got %s", out) 946 } 947 } 948 949 // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted. 950 func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) { 951 testRequires(c, SameHostDaemon, seccompEnabled) 952 jsonData := `{ 953 "defaultAction": "SCMP_ACT_ALLOW", 954 "syscalls": [ 955 { 956 "name": "chmod", 957 "action": "SCMP_ACT_ERRNO" 958 } 959 ] 960 }` 961 tmpFile, err := ioutil.TempFile("", "profile.json") 962 c.Assert(err, check.IsNil) 963 defer tmpFile.Close() 964 965 if _, err := tmpFile.Write([]byte(jsonData)); err != nil { 966 c.Fatal(err) 967 } 968 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "400", "/etc/hostname") 969 out, _, _ := runCommandWithOutput(runCmd) 970 if !strings.Contains(out, "Operation not permitted") { 971 c.Fatalf("expected chmod with seccomp profile denied to fail, got %s", out) 972 } 973 } 974 975 // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to 976 // deny unhare of a userns exits with operation not permitted. 977 func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) { 978 testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor) 979 // from sched.h 980 jsonData := fmt.Sprintf(`{ 981 "defaultAction": "SCMP_ACT_ALLOW", 982 "syscalls": [ 983 { 984 "name": "unshare", 985 "action": "SCMP_ACT_ERRNO", 986 "args": [ 987 { 988 "index": 0, 989 "value": %d, 990 "op": "SCMP_CMP_EQ" 991 } 992 ] 993 } 994 ] 995 }`, uint64(0x10000000)) 996 tmpFile, err := ioutil.TempFile("", "profile.json") 997 defer tmpFile.Close() 998 if err != nil { 999 c.Fatal(err) 1000 } 1001 1002 if _, err := tmpFile.Write([]byte(jsonData)); err != nil { 1003 c.Fatal(err) 1004 } 1005 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(), "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami") 1006 out, _, _ := runCommandWithOutput(runCmd) 1007 if !strings.Contains(out, "Operation not permitted") { 1008 c.Fatalf("expected unshare userns with seccomp profile denied to fail, got %s", out) 1009 } 1010 } 1011 1012 // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test' 1013 // with a the default seccomp profile exits with operation not permitted. 1014 func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) { 1015 testRequires(c, SameHostDaemon, seccompEnabled) 1016 1017 runCmd := exec.Command(dockerBinary, "run", "syscall-test", "userns-test", "id") 1018 out, _, err := runCommandWithOutput(runCmd) 1019 if err == nil || !strings.Contains(out, "clone failed: Operation not permitted") { 1020 c.Fatalf("expected clone userns with default seccomp profile denied to fail, got %s: %v", out, err) 1021 } 1022 } 1023 1024 // TestRunSeccompUnconfinedCloneUserns checks that 1025 // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns. 1026 func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) { 1027 testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace) 1028 1029 // make sure running w privileged is ok 1030 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "syscall-test", "userns-test", "id") 1031 if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") { 1032 c.Fatalf("expected clone userns with --security-opt seccomp=unconfined to succeed, got %s: %v", out, err) 1033 } 1034 } 1035 1036 // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test' 1037 // allows creating a userns. 1038 func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) { 1039 testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace) 1040 1041 // make sure running w privileged is ok 1042 runCmd := exec.Command(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id") 1043 if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "nobody") { 1044 c.Fatalf("expected clone userns with --privileged to succeed, got %s: %v", out, err) 1045 } 1046 } 1047 1048 // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds. 1049 func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) { 1050 testRequires(c, SameHostDaemon, seccompEnabled) 1051 1052 // ulimit uses setrlimit, so we want to make sure we don't break it 1053 runCmd := exec.Command(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510") 1054 if out, _, err := runCommandWithOutput(runCmd); err != nil { 1055 c.Fatalf("expected ulimit with seccomp to succeed, got %s: %v", out, err) 1056 } 1057 } 1058 1059 func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) { 1060 testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace) 1061 1062 var group sync.WaitGroup 1063 group.Add(5) 1064 errChan := make(chan error, 5) 1065 go func() { 1066 out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test") 1067 if err == nil || !strings.Contains(out, "Operation not permitted") { 1068 errChan <- fmt.Errorf("goroutine 0: expected Operation not permitted, got: %s", out) 1069 } 1070 group.Done() 1071 }() 1072 1073 go func() { 1074 out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test") 1075 if err == nil || !strings.Contains(out, "Operation not permitted") { 1076 errChan <- fmt.Errorf("goroutine 1: expected Operation not permitted, got: %s", out) 1077 } 1078 group.Done() 1079 }() 1080 1081 go func() { 1082 out, _, err := dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test") 1083 if err == nil || !strings.Contains(out, "No such file or directory") { 1084 errChan <- fmt.Errorf("goroutine 2: expected No such file or directory, got: %s", out) 1085 } 1086 group.Done() 1087 }() 1088 1089 go func() { 1090 out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test") 1091 if err == nil || !strings.Contains(out, "No such file or directory") { 1092 errChan <- fmt.Errorf("goroutine 3: expected No such file or directory, got: %s", out) 1093 } 1094 group.Done() 1095 }() 1096 1097 go func() { 1098 out, _, err := dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test") 1099 if err == nil || !strings.Contains(out, "No such file or directory") { 1100 errChan <- fmt.Errorf("goroutine 4: expected No such file or directory, got: %s", out) 1101 } 1102 group.Done() 1103 }() 1104 1105 group.Wait() 1106 close(errChan) 1107 1108 for err := range errChan { 1109 c.Assert(err, checker.IsNil) 1110 } 1111 } 1112 1113 func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) { 1114 testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace) 1115 1116 var group sync.WaitGroup 1117 group.Add(6) 1118 errChan := make(chan error, 6) 1119 1120 go func() { 1121 out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0") 1122 if err == nil || !strings.Contains(out, "Operation not permitted") { 1123 errChan <- fmt.Errorf("goroutine 0: expected Operation not permitted, got: %s", out) 1124 } 1125 group.Done() 1126 }() 1127 1128 go func() { 1129 out, _, err := dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1") 1130 if err != nil || !strings.Contains(out, "hello1") { 1131 errChan <- fmt.Errorf("goroutine 1: expected hello1, got: %s, %v", out, err) 1132 } 1133 group.Done() 1134 }() 1135 1136 go func() { 1137 out, _, err := dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2") 1138 if err != nil || !strings.Contains(out, "hello2") { 1139 errChan <- fmt.Errorf("goroutine 2: expected hello2, got: %s, %v", out, err) 1140 } 1141 group.Done() 1142 }() 1143 1144 go func() { 1145 out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3") 1146 if err != nil || !strings.Contains(out, "hello3") { 1147 errChan <- fmt.Errorf("goroutine 3: expected hello3, got: %s, %v", out, err) 1148 } 1149 group.Done() 1150 }() 1151 1152 go func() { 1153 out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test") 1154 if err == nil || !strings.Contains(out, "No such file or directory") { 1155 errChan <- fmt.Errorf("goroutine 4: expected No such file or directory, got: %s", out) 1156 } 1157 group.Done() 1158 }() 1159 1160 go func() { 1161 out, _, err := dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4") 1162 if err != nil || !strings.Contains(out, "hello4") { 1163 errChan <- fmt.Errorf("goroutine 5: expected hello4, got: %s, %v", out, err) 1164 } 1165 group.Done() 1166 }() 1167 1168 group.Wait() 1169 close(errChan) 1170 1171 for err := range errChan { 1172 c.Assert(err, checker.IsNil) 1173 } 1174 } 1175 1176 // TestRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents 1177 // effective uid transtions on executing setuid binaries. 1178 func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) { 1179 testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) 1180 1181 // test that running a setuid binary results in no effective uid transition 1182 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000", "nnp-test", "/usr/bin/nnp-test") 1183 if out, _, err := runCommandWithOutput(runCmd); err != nil || !strings.Contains(out, "EUID=1000") { 1184 c.Fatalf("expected output to contain EUID=1000, got %s: %v", out, err) 1185 } 1186 } 1187 1188 func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) { 1189 testRequires(c, SameHostDaemon, Apparmor) 1190 1191 // running w seccomp unconfined tests the apparmor profile 1192 runCmd := exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup") 1193 if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) { 1194 c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", out, err) 1195 } 1196 1197 runCmd = exec.Command(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current") 1198 if out, _, err := runCommandWithOutput(runCmd); err == nil || !(strings.Contains(out, "Permission denied") || strings.Contains(out, "Operation not permitted")) { 1199 c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", out, err) 1200 } 1201 } 1202 1203 // make sure the default profile can be successfully parsed (using unshare as it is 1204 // something which we know is blocked in the default profile) 1205 func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) { 1206 testRequires(c, SameHostDaemon, seccompEnabled, NotArm, NotPpc64le, NotS390X) 1207 1208 out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami") 1209 c.Assert(err, checker.NotNil, check.Commentf(out)) 1210 c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted") 1211 } 1212 1213 // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271) 1214 func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { 1215 testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon) 1216 if _, err := os.Stat("/dev/zero"); err != nil { 1217 c.Skip("Host does not have /dev/zero") 1218 } 1219 1220 // Create a temporary directory to create symlink 1221 tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests") 1222 c.Assert(err, checker.IsNil) 1223 1224 defer os.RemoveAll(tmpDir) 1225 1226 // Create a symbolic link to /dev/zero 1227 symZero := filepath.Join(tmpDir, "zero") 1228 err = os.Symlink("/dev/zero", symZero) 1229 c.Assert(err, checker.IsNil) 1230 1231 // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp", 1232 // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp". 1233 tmpFile := filepath.Join(tmpDir, "temp") 1234 err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666) 1235 c.Assert(err, checker.IsNil) 1236 symFile := filepath.Join(tmpDir, "file") 1237 err = os.Symlink(tmpFile, symFile) 1238 c.Assert(err, checker.IsNil) 1239 1240 // Create a symbolic link to /dev/zero, this time with a relative path (#22271) 1241 err = os.Symlink("zero", "/dev/symzero") 1242 if err != nil { 1243 c.Fatal("/dev/symzero creation failed") 1244 } 1245 // We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above 1246 defer os.Remove("/dev/symzero") 1247 1248 // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 1249 out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") 1250 c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23")) 1251 1252 // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device. 1253 out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") 1254 c.Assert(err, check.NotNil) 1255 c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("expected output 'not a device node'")) 1256 1257 // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271) 1258 out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") 1259 c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "bb7df04e1b0a2570657527a7e108ae23", check.Commentf("expected output bb7df04e1b0a2570657527a7e108ae23")) 1260 } 1261 1262 // TestRunPidsLimit makes sure the pids cgroup is set with --pids-limit 1263 func (s *DockerSuite) TestRunPidsLimit(c *check.C) { 1264 testRequires(c, pidsLimit) 1265 1266 file := "/sys/fs/cgroup/pids/pids.max" 1267 out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "2", "busybox", "cat", file) 1268 c.Assert(strings.TrimSpace(out), checker.Equals, "2") 1269 1270 out = inspectField(c, "skittles", "HostConfig.PidsLimit") 1271 c.Assert(out, checker.Equals, "2", check.Commentf("setting the pids limit failed")) 1272 } 1273 1274 func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) { 1275 testRequires(c, DaemonIsLinux, NotUserNamespace) 1276 1277 file := "/sys/fs/cgroup/devices/devices.list" 1278 out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file) 1279 c.Logf("out: %q", out) 1280 c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm") 1281 } 1282 1283 func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) { 1284 testRequires(c, DaemonIsLinux) 1285 1286 fi, err := os.Stat("/dev/snd/timer") 1287 if err != nil { 1288 c.Skip("Host does not have /dev/snd/timer") 1289 } 1290 stat, ok := fi.Sys().(*syscall.Stat_t) 1291 if !ok { 1292 c.Skip("Could not stat /dev/snd/timer") 1293 } 1294 1295 file := "/sys/fs/cgroup/devices/devices.list" 1296 out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file) 1297 c.Assert(out, checker.Contains, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256)) 1298 }